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

#include "DDImage/Knobs.h"
#include "DDImage/Row.h"

#include "boost/signal.hpp"
#include "boost/bind.hpp"
#include "boost/lexical_cast.hpp"

#include "IECore/LRUCache.h"
#include "IECore/ImageDisplayDriver.h"

#include "IECoreNuke/DisplayIop.h"
#include "IECoreNuke/TypeIds.h"

using namespace IECore;
using namespace IECoreNuke;
using namespace DD::Image;
using namespace Imath;

//////////////////////////////////////////////////////////////////////////
// DisplayDriverServer cache. Many nodes may all want to use a server on
// the same port. We therefore use an LRUCache to manage the lifetime of
// the servers and provide them to the nodes.
//////////////////////////////////////////////////////////////////////////

typedef LRUCache<int, DisplayDriverServerPtr> ServerCache;

// key is the port number for the server.
static DisplayDriverServerPtr serverCacheGetter( int key, size_t cost )
{
	cost = 1;
	return new DisplayDriverServer( key );
}

// max cost of 4 means we will never have more than 4 unused servers at any one time.
static ServerCache g_servers( serverCacheGetter, 4 );

//////////////////////////////////////////////////////////////////////////
// NukeDisplayDriver implementation
//////////////////////////////////////////////////////////////////////////

namespace IECoreNuke
{

class NukeDisplayDriver : public IECore::ImageDisplayDriver
{

	public :

		IE_CORE_DECLARERUNTIMETYPEDEXTENSION( NukeDisplayDriver, NukeDisplayDriverTypeId, ImageDisplayDriver );

		NukeDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, ConstCompoundDataPtr parameters )
			:	ImageDisplayDriver( displayWindow, dataWindow, channelNames, parameters )
		{
			if( parameters )
			{
				m_parameters = parameters->copy();
			}
			else
			{
				m_parameters = new CompoundData;
			}

			instanceCreatedSignal( this );
		}

		virtual ~NukeDisplayDriver()
		{
		}

		/// Returns a copy of the parameters used in creating this instance. This
		/// is useful in recognising relevant instances in the instanceCreatedSignal.
		ConstCompoundDataPtr parameters() const
		{
			return m_parameters;
		}

		/// Updates the current image, and then emits the dataReceivedSignal.
		virtual void imageData( const Imath::Box2i &box, const float *data, size_t dataSize )
		{
			ImageDisplayDriver::imageData( box, data, dataSize );
			dataReceivedSignal( this, box );
		}

		/// This signal is emitted when a new NukeDisplayDriver has been created.
		/// This allows nuke nodes to pick up the new DisplayDrivers even when they're
		/// created in some other code, such as a DisplayDriverServer.
		typedef boost::signal<void( NukeDisplayDriver * )> InstanceCreatedSignal;
		static InstanceCreatedSignal instanceCreatedSignal;

		/// This signal is emitted when this NukeDisplayDriver instance receives new data.
		typedef boost::signal<void( NukeDisplayDriver *, const Imath::Box2i &box )> DataReceivedSignal;
		DataReceivedSignal dataReceivedSignal;

	private :

		static const DisplayDriverDescription<NukeDisplayDriver> g_description;

		ConstCompoundDataPtr m_parameters;

};

NukeDisplayDriver::InstanceCreatedSignal NukeDisplayDriver::instanceCreatedSignal;
const DisplayDriver::DisplayDriverDescription<NukeDisplayDriver> NukeDisplayDriver::g_description;

} // namespace IECoreNuke

//////////////////////////////////////////////////////////////////////////
// DisplayIop implementation
//////////////////////////////////////////////////////////////////////////

const DD::Image::Iop::Description DisplayIop::g_description( "ieDisplay", DisplayIop::build );

DisplayIop::DisplayIop( Node *node )
	:	Iop( node ), m_portNumber( 1559 ), m_server( g_servers.get( m_portNumber ) ), m_updateCount( 0 ), m_driver( 0 )
{
	inputs( 0 );
	slowness( 0 ); // disable caching as we're buffering everything internally ourselves
	NukeDisplayDriver::instanceCreatedSignal.connect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
}

DisplayIop::~DisplayIop()
{
	NukeDisplayDriver::instanceCreatedSignal.disconnect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
	connectToDriver( 0 );
}

const char *DisplayIop::Class() const
{
	return "ieDisplay";
}

const char *DisplayIop::node_help() const
{
	return "Acts as a framebuffer for external renderers.";
}

void DisplayIop::knobs( DD::Image::Knob_Callback f )
{
	Iop::knobs( f );

	Int_knob( f, &m_portNumber, "portNumber", "Port Number" );
	// we must have KNOB_CHANGED_RECURSIVE set otherwise nuke doesn't give us knob_changed()
	// calls when the knob value is changed from a knobChanged method of a PythonPanel.
	SetFlags( f, Knob::KNOB_CHANGED_ALWAYS | Knob::KNOB_CHANGED_RECURSIVE | Knob::NO_ANIMATION );
	Tooltip(
		f,
		"The port on which to receive images. This must match "
		"the port being used by the renderer to send images."
	);

}

int DisplayIop::knob_changed( DD::Image::Knob *knob )
{
	if( knob->is( "portNumber" ) )
	{
	 	int portNumber = this->knob( "portNumber" )->get_value();
		m_server = g_servers.get( portNumber );
		return 1;
	}

	return Iop::knob_changed( knob );
}

void DisplayIop::append( DD::Image::Hash &hash )
{
	Iop::append( hash );

	hash.append( __DATE__ );
	hash.append( __TIME__ );
	hash.append( firstDisplayIop()->m_updateCount );
}

void DisplayIop::_validate( bool forReal )
{
	Box2i displayWindow( V2i( 0, 0 ), V2i( 255, 255 ) );

	if( firstDisplayIop()->m_driver )
	{
		displayWindow = firstDisplayIop()->m_driver->image()->getDisplayWindow();
	}

	m_format = m_fullSizeFormat = Format( displayWindow.size().x + 1, displayWindow.size().y + 1 );
	// these set function don't copy the format, but instead reference its address.
	// we therefore have to store the format as member data.
	info_.format( m_format );
	info_.full_size_format( m_fullSizeFormat );
	info_.set( m_format );

	info_.channels( Mask_RGBA );
}

void DisplayIop::engine( int y, int x, int r, const DD::Image::ChannelSet &channels, DD::Image::Row &row )
{
	Channel outputChannels[4] = { Chan_Red, Chan_Green, Chan_Blue, Chan_Alpha };
	const char *inputChannels[] = { "R", "G", "B", "A", 0 };

	const ImagePrimitive *image = 0;
	Box2i inputDataWindow;
	Box2i inputDisplayWindow;
	if( firstDisplayIop()->m_driver )
	{
		image = firstDisplayIop()->m_driver->image().get();
		inputDataWindow = image->getDataWindow();
		inputDisplayWindow = image->getDisplayWindow();
	}

	int i = 0;
	while( inputChannels[i] )
	{
		const FloatVectorData *inputData = image ? image->variableData<FloatVectorData>( inputChannels[i] ) : 0;
		if( inputData )
		{
			float *output = row.writable( outputChannels[i] ) + x;
			// remap coordinate relative to our data window. nuke images have pixel origin at bottom,
			// cortex images have pixel origin at top.
			V2i pDataWindow = V2i( x, inputDisplayWindow.max.y - y ) - inputDataWindow.min;
			const float *input = &((inputData->readable())[pDataWindow.y*(inputDataWindow.size().x+1) + pDataWindow.x]);
			memcpy( output, input, (r-x) * sizeof( float ) );
		}
		else
		{
			row.erase( outputChannels[i] );
		}
		i++;
	}
}

DD::Image::Op *DisplayIop::build( Node *node )
{
	return new DisplayIop( node );
}

DisplayIop *DisplayIop::firstDisplayIop()
{
	return static_cast<DisplayIop *>( firstOp() );
}

void DisplayIop::driverCreated( NukeDisplayDriver *driver )
{
	ConstStringDataPtr portNumber = driver->parameters()->member<StringData>( "displayPort" );
	if( portNumber && boost::lexical_cast<int>( portNumber->readable() ) == m_portNumber )
	{
		firstDisplayIop()->connectToDriver( driver );
	}
}

void DisplayIop::connectToDriver( NukeDisplayDriver *driver )
{
	assert( this == firstDisplayIop() );

	if( m_driver )
	{
		m_driver->dataReceivedSignal.disconnect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
	}

	m_driver = driver;
	if( m_driver )
	{
		m_driver->dataReceivedSignal.connect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
	}

	m_updateCount++;
	asapUpdate();
}

void DisplayIop::driverDataReceived( NukeDisplayDriver *driver, const Imath::Box2i &box )
{
	assert( this == firstDisplayIop() );
	m_updateCount++;
	asapUpdate();
}
<commit_msg>fixing warning<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2012, J3P LLC. All rights reserved.
//
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "DDImage/Knobs.h"
#include "DDImage/Row.h"

#include "boost/signal.hpp"
#include "boost/bind.hpp"
#include "boost/lexical_cast.hpp"

#include "IECore/LRUCache.h"
#include "IECore/ImageDisplayDriver.h"

#include "IECoreNuke/DisplayIop.h"
#include "IECoreNuke/TypeIds.h"

using namespace IECore;
using namespace IECoreNuke;
using namespace DD::Image;
using namespace Imath;

//////////////////////////////////////////////////////////////////////////
// DisplayDriverServer cache. Many nodes may all want to use a server on
// the same port. We therefore use an LRUCache to manage the lifetime of
// the servers and provide them to the nodes.
//////////////////////////////////////////////////////////////////////////

typedef LRUCache<int, DisplayDriverServerPtr> ServerCache;

// key is the port number for the server.
static DisplayDriverServerPtr serverCacheGetter( int key, size_t cost )
{
	cost = 1;
	return new DisplayDriverServer( key );
}

// max cost of 4 means we will never have more than 4 unused servers at any one time.
static ServerCache g_servers( serverCacheGetter, 4 );

//////////////////////////////////////////////////////////////////////////
// NukeDisplayDriver implementation
//////////////////////////////////////////////////////////////////////////

namespace IECoreNuke
{

class NukeDisplayDriver : public IECore::ImageDisplayDriver
{

	public :

		IE_CORE_DECLARERUNTIMETYPEDEXTENSION( NukeDisplayDriver, NukeDisplayDriverTypeId, ImageDisplayDriver );

		NukeDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, ConstCompoundDataPtr parameters )
			:	ImageDisplayDriver( displayWindow, dataWindow, channelNames, parameters )
		{
			if( parameters )
			{
				m_parameters = parameters->copy();
			}
			else
			{
				m_parameters = new CompoundData;
			}

			instanceCreatedSignal( this );
		}

		virtual ~NukeDisplayDriver()
		{
		}

		/// Returns a copy of the parameters used in creating this instance. This
		/// is useful in recognising relevant instances in the instanceCreatedSignal.
		ConstCompoundDataPtr parameters() const
		{
			return m_parameters;
		}

		/// Updates the current image, and then emits the dataReceivedSignal.
		virtual void imageData( const Imath::Box2i &box, const float *data, size_t dataSize )
		{
			ImageDisplayDriver::imageData( box, data, dataSize );
			dataReceivedSignal( this, box );
		}

		/// This signal is emitted when a new NukeDisplayDriver has been created.
		/// This allows nuke nodes to pick up the new DisplayDrivers even when they're
		/// created in some other code, such as a DisplayDriverServer.
		typedef boost::signal<void( NukeDisplayDriver * )> InstanceCreatedSignal;
		static InstanceCreatedSignal instanceCreatedSignal;

		/// This signal is emitted when this NukeDisplayDriver instance receives new data.
		typedef boost::signal<void( NukeDisplayDriver *, const Imath::Box2i &box )> DataReceivedSignal;
		DataReceivedSignal dataReceivedSignal;

	private :

		static const DisplayDriverDescription<NukeDisplayDriver> g_description;

		ConstCompoundDataPtr m_parameters;

};

NukeDisplayDriver::InstanceCreatedSignal NukeDisplayDriver::instanceCreatedSignal;
const DisplayDriver::DisplayDriverDescription<NukeDisplayDriver> NukeDisplayDriver::g_description;

} // namespace IECoreNuke

//////////////////////////////////////////////////////////////////////////
// DisplayIop implementation
//////////////////////////////////////////////////////////////////////////

const DD::Image::Iop::Description DisplayIop::g_description( "ieDisplay", DisplayIop::build );

DisplayIop::DisplayIop( Node *node )
	:	Iop( node ), m_portNumber( 1559 ), m_server( g_servers.get( m_portNumber ) ), m_updateCount( 0 ), m_driver( 0 )
{
	inputs( 0 );
	slowness( 0 ); // disable caching as we're buffering everything internally ourselves
	NukeDisplayDriver::instanceCreatedSignal.connect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
}

DisplayIop::~DisplayIop()
{
	NukeDisplayDriver::instanceCreatedSignal.disconnect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
	connectToDriver( 0 );
}

const char *DisplayIop::Class() const
{
	return "ieDisplay";
}

const char *DisplayIop::node_help() const
{
	return "Acts as a framebuffer for external renderers.";
}

void DisplayIop::knobs( DD::Image::Knob_Callback f )
{
	Iop::knobs( f );

	Int_knob( f, &m_portNumber, "portNumber", "Port Number" );
	// we must have KNOB_CHANGED_RECURSIVE set otherwise nuke doesn't give us knob_changed()
	// calls when the knob value is changed from a knobChanged method of a PythonPanel.
	SetFlags( f, Knob::KNOB_CHANGED_ALWAYS | Knob::KNOB_CHANGED_RECURSIVE | Knob::NO_ANIMATION );
	Tooltip(
		f,
		"The port on which to receive images. This must match "
		"the port being used by the renderer to send images."
	);

}

int DisplayIop::knob_changed( DD::Image::Knob *knob )
{
	if( knob->is( "portNumber" ) )
	{
	 	int portNumber = (int)this->knob( "portNumber" )->get_value();
		m_server = g_servers.get( portNumber );
		return 1;
	}

	return Iop::knob_changed( knob );
}

void DisplayIop::append( DD::Image::Hash &hash )
{
	Iop::append( hash );

	hash.append( __DATE__ );
	hash.append( __TIME__ );
	hash.append( firstDisplayIop()->m_updateCount );
}

void DisplayIop::_validate( bool forReal )
{
	Box2i displayWindow( V2i( 0, 0 ), V2i( 255, 255 ) );

	if( firstDisplayIop()->m_driver )
	{
		displayWindow = firstDisplayIop()->m_driver->image()->getDisplayWindow();
	}

	m_format = m_fullSizeFormat = Format( displayWindow.size().x + 1, displayWindow.size().y + 1 );
	// these set function don't copy the format, but instead reference its address.
	// we therefore have to store the format as member data.
	info_.format( m_format );
	info_.full_size_format( m_fullSizeFormat );
	info_.set( m_format );

	info_.channels( Mask_RGBA );
}

void DisplayIop::engine( int y, int x, int r, const DD::Image::ChannelSet &channels, DD::Image::Row &row )
{
	Channel outputChannels[4] = { Chan_Red, Chan_Green, Chan_Blue, Chan_Alpha };
	const char *inputChannels[] = { "R", "G", "B", "A", 0 };

	const ImagePrimitive *image = 0;
	Box2i inputDataWindow;
	Box2i inputDisplayWindow;
	if( firstDisplayIop()->m_driver )
	{
		image = firstDisplayIop()->m_driver->image().get();
		inputDataWindow = image->getDataWindow();
		inputDisplayWindow = image->getDisplayWindow();
	}

	int i = 0;
	while( inputChannels[i] )
	{
		const FloatVectorData *inputData = image ? image->variableData<FloatVectorData>( inputChannels[i] ) : 0;
		if( inputData )
		{
			float *output = row.writable( outputChannels[i] ) + x;
			// remap coordinate relative to our data window. nuke images have pixel origin at bottom,
			// cortex images have pixel origin at top.
			V2i pDataWindow = V2i( x, inputDisplayWindow.max.y - y ) - inputDataWindow.min;
			const float *input = &((inputData->readable())[pDataWindow.y*(inputDataWindow.size().x+1) + pDataWindow.x]);
			memcpy( output, input, (r-x) * sizeof( float ) );
		}
		else
		{
			row.erase( outputChannels[i] );
		}
		i++;
	}
}

DD::Image::Op *DisplayIop::build( Node *node )
{
	return new DisplayIop( node );
}

DisplayIop *DisplayIop::firstDisplayIop()
{
	return static_cast<DisplayIop *>( firstOp() );
}

void DisplayIop::driverCreated( NukeDisplayDriver *driver )
{
	ConstStringDataPtr portNumber = driver->parameters()->member<StringData>( "displayPort" );
	if( portNumber && boost::lexical_cast<int>( portNumber->readable() ) == m_portNumber )
	{
		firstDisplayIop()->connectToDriver( driver );
	}
}

void DisplayIop::connectToDriver( NukeDisplayDriver *driver )
{
	assert( this == firstDisplayIop() );

	if( m_driver )
	{
		m_driver->dataReceivedSignal.disconnect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
	}

	m_driver = driver;
	if( m_driver )
	{
		m_driver->dataReceivedSignal.connect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
	}

	m_updateCount++;
	asapUpdate();
}

void DisplayIop::driverDataReceived( NukeDisplayDriver *driver, const Imath::Box2i &box )
{
	assert( this == firstDisplayIop() );
	m_updateCount++;
	asapUpdate();
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2008 Jürgen Riegel (juergen.riegel@web.de)              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
# include <Standard_math.hxx>
#endif

#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <Gui/Application.h>
#include <Gui/WidgetFactory.h>
#include <Gui/Language/Translator.h>
#include "PropertyFemMeshItem.h"
#include "DlgSettingsFemCcxImp.h"
#include "DlgSettingsFemElmerImp.h"
#include "DlgSettingsFemExportAbaqusImp.h"
#include "DlgSettingsFemGeneralImp.h"
#include "DlgSettingsFemGmshImp.h"
#include "DlgSettingsFemInOutVtkImp.h"
#include "DlgSettingsFemMaterialImp.h"
#include "DlgSettingsFemZ88Imp.h"
#include "ViewProviderFemMesh.h"
#include "ViewProviderFemMeshShape.h"
#include "ViewProviderFemMeshShapeNetgen.h"
#include "ViewProviderAnalysis.h"
#include "ViewProviderSolver.h"
#include "ViewProviderSetNodes.h"
#include "ViewProviderSetElements.h"
#include "ViewProviderSetFaces.h"
#include "ViewProviderSetGeometry.h"
#include "ViewProviderFemConstraint.h"
#include "ViewProviderFemConstraintBearing.h"
#include "ViewProviderFemConstraintFixed.h"
#include "ViewProviderFemConstraintForce.h"
#include "ViewProviderFemConstraintFluidBoundary.h"
#include "ViewProviderFemConstraintPressure.h"
#include "ViewProviderFemConstraintGear.h"
#include "ViewProviderFemConstraintPulley.h"
#include "ViewProviderFemConstraintDisplacement.h"
#include "ViewProviderFemConstraintTemperature.h"
#include "ViewProviderFemConstraintHeatflux.h"
#include "ViewProviderFemConstraintInitialTemperature.h"
#include "ViewProviderFemConstraintPlaneRotation.h"
#include "ViewProviderFemConstraintContact.h"
#include "ViewProviderFemConstraintTransform.h"
#include "ViewProviderResult.h"
#include "Workbench.h"

#ifdef FC_USE_VTK
#include "ViewProviderFemPostObject.h"
#include "ViewProviderFemPostPipeline.h"
#include "ViewProviderFemPostFunction.h"
#include "ViewProviderFemPostFilter.h"
#endif

// use a different name to CreateCommand()
void CreateFemCommands(void);

void loadFemResource()
{
    // add resources and reloads the translators
    Q_INIT_RESOURCE(Fem);
    Gui::Translator::instance()->refresh();
}

namespace FemGui {
extern PyObject* initModule();
}

/* Python entry */
PyMOD_INIT_FUNC(FemGui)
{
    if (!Gui::Application::Instance) {
        PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application.");
        PyMOD_Return(0);
    }

    PyObject* mod = FemGui::initModule();
    Base::Console().Log("Loading GUI of Fem module... done\n");

    // instantiating the commands
    CreateFemCommands();

    // addition objects
    FemGui::Workbench                                           ::init();
    FemGui::ViewProviderFemAnalysis                             ::init();
    FemGui::ViewProviderFemAnalysisPython                       ::init();
    FemGui::ViewProviderFemMesh                                 ::init();
    FemGui::ViewProviderFemMeshPython                           ::init();
    FemGui::ViewProviderFemMeshShape                            ::init();
    FemGui::ViewProviderFemMeshShapeNetgen                      ::init();
    FemGui::ViewProviderSolver                                  ::init();
    FemGui::ViewProviderSolverPython                            ::init();
    FemGui::ViewProviderSetNodes                                ::init();
    FemGui::ViewProviderSetElements                             ::init();
    FemGui::ViewProviderSetFaces                                ::init();
    FemGui::ViewProviderSetGeometry                             ::init();
    FemGui::ViewProviderFemConstraint                           ::init();
    FemGui::ViewProviderFemConstraintPython                     ::init();
    FemGui::ViewProviderFemConstraintBearing                    ::init();
    FemGui::ViewProviderFemConstraintFixed                      ::init();
    FemGui::ViewProviderFemConstraintForce                      ::init();
    FemGui::ViewProviderFemConstraintFluidBoundary              ::init();
    FemGui::ViewProviderFemConstraintPressure                   ::init();
    FemGui::ViewProviderFemConstraintGear                       ::init();
    FemGui::ViewProviderFemConstraintPulley                     ::init();
    FemGui::ViewProviderFemConstraintDisplacement               ::init();
    FemGui::ViewProviderFemConstraintHeatflux                   ::init();
    FemGui::ViewProviderFemConstraintTemperature                ::init();
    FemGui::ViewProviderFemConstraintInitialTemperature         ::init();
    FemGui::ViewProviderFemConstraintPlaneRotation              ::init();
    FemGui::ViewProviderFemConstraintContact                    ::init();
    FemGui::ViewProviderFemConstraintTransform                  ::init();
    FemGui::ViewProviderResult                                  ::init();
    FemGui::ViewProviderResultPython                            ::init();
    FemGui::PropertyFemMeshItem                                 ::init();

#ifdef FC_USE_VTK
    FemGui::ViewProviderFemPostObject                           ::init();
    FemGui::ViewProviderFemPostPipeline                         ::init();
    FemGui::ViewProviderFemPostFunction                         ::init();
    FemGui::ViewProviderFemPostFunctionProvider                 ::init();
    FemGui::ViewProviderFemPostPlaneFunction                    ::init();
    FemGui::ViewProviderFemPostSphereFunction                   ::init();
    FemGui::ViewProviderFemPostClip                             ::init();
    FemGui::ViewProviderFemPostDataAlongLine                    ::init();
    FemGui::ViewProviderFemPostDataAtPoint                      ::init();
    FemGui::ViewProviderFemPostScalarClip                       ::init();
    FemGui::ViewProviderFemPostWarpVector                       ::init();
    FemGui::ViewProviderFemPostCut                              ::init();
#endif

    // register preferences pages on FEM, the order here will be the order of the tabs in pref widget
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemGeneralImp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemGmshImp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemCcxImp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemElmerImp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemZ88Imp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemMaterialImp> (QT_TRANSLATE_NOOP("QObject","FEM"));

    // register preferences pages on Import-Export
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemExportAbaqusImp> (QT_TRANSLATE_NOOP("QObject","Import-Export"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemInOutVtkImp> (QT_TRANSLATE_NOOP("QObject","Import-Export"));

     // add resources and reloads the translators
    loadFemResource();

    PyMOD_Return(mod);
}
<commit_msg>FEM: gui py class init, sort classes<commit_after>/***************************************************************************
 *   Copyright (c) 2008 Jürgen Riegel (juergen.riegel@web.de)              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
# include <Standard_math.hxx>
#endif

#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <Gui/Application.h>
#include <Gui/WidgetFactory.h>
#include <Gui/Language/Translator.h>
#include "PropertyFemMeshItem.h"
#include "DlgSettingsFemCcxImp.h"
#include "DlgSettingsFemElmerImp.h"
#include "DlgSettingsFemExportAbaqusImp.h"
#include "DlgSettingsFemGeneralImp.h"
#include "DlgSettingsFemGmshImp.h"
#include "DlgSettingsFemInOutVtkImp.h"
#include "DlgSettingsFemMaterialImp.h"
#include "DlgSettingsFemZ88Imp.h"
#include "ViewProviderFemMesh.h"
#include "ViewProviderFemMeshShape.h"
#include "ViewProviderFemMeshShapeNetgen.h"
#include "ViewProviderAnalysis.h"
#include "ViewProviderSolver.h"
#include "ViewProviderSetNodes.h"
#include "ViewProviderSetElements.h"
#include "ViewProviderSetFaces.h"
#include "ViewProviderSetGeometry.h"
#include "ViewProviderFemConstraint.h"
#include "ViewProviderFemConstraintBearing.h"
#include "ViewProviderFemConstraintFixed.h"
#include "ViewProviderFemConstraintForce.h"
#include "ViewProviderFemConstraintFluidBoundary.h"
#include "ViewProviderFemConstraintPressure.h"
#include "ViewProviderFemConstraintGear.h"
#include "ViewProviderFemConstraintPulley.h"
#include "ViewProviderFemConstraintDisplacement.h"
#include "ViewProviderFemConstraintTemperature.h"
#include "ViewProviderFemConstraintHeatflux.h"
#include "ViewProviderFemConstraintInitialTemperature.h"
#include "ViewProviderFemConstraintPlaneRotation.h"
#include "ViewProviderFemConstraintContact.h"
#include "ViewProviderFemConstraintTransform.h"
#include "ViewProviderResult.h"
#include "Workbench.h"

#ifdef FC_USE_VTK
#include "ViewProviderFemPostObject.h"
#include "ViewProviderFemPostPipeline.h"
#include "ViewProviderFemPostFunction.h"
#include "ViewProviderFemPostFilter.h"
#endif

// use a different name to CreateCommand()
void CreateFemCommands(void);

void loadFemResource()
{
    // add resources and reloads the translators
    Q_INIT_RESOURCE(Fem);
    Gui::Translator::instance()->refresh();
}

namespace FemGui {
extern PyObject* initModule();
}

/* Python entry */
PyMOD_INIT_FUNC(FemGui)
{
    if (!Gui::Application::Instance) {
        PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application.");
        PyMOD_Return(0);
    }

    PyObject* mod = FemGui::initModule();
    Base::Console().Log("Loading GUI of Fem module... done\n");

    // instantiating the commands
    CreateFemCommands();

    // addition objects
    FemGui::Workbench                                           ::init();

    FemGui::ViewProviderFemAnalysis                             ::init();
    FemGui::ViewProviderFemAnalysisPython                       ::init();

    FemGui::ViewProviderFemConstraint                           ::init();
    FemGui::ViewProviderFemConstraintPython                     ::init();

    FemGui::ViewProviderFemConstraintBearing                    ::init();
    FemGui::ViewProviderFemConstraintContact                    ::init();
    FemGui::ViewProviderFemConstraintDisplacement               ::init();
    FemGui::ViewProviderFemConstraintFixed                      ::init();
    FemGui::ViewProviderFemConstraintFluidBoundary              ::init();
    FemGui::ViewProviderFemConstraintForce                      ::init();
    FemGui::ViewProviderFemConstraintGear                       ::init();
    FemGui::ViewProviderFemConstraintHeatflux                   ::init();
    FemGui::ViewProviderFemConstraintInitialTemperature         ::init();
    FemGui::ViewProviderFemConstraintPlaneRotation              ::init();
    FemGui::ViewProviderFemConstraintPressure                   ::init();
    FemGui::ViewProviderFemConstraintPulley                     ::init();
    FemGui::ViewProviderFemConstraintTemperature                ::init();
    FemGui::ViewProviderFemConstraintTransform                  ::init();

    FemGui::ViewProviderFemMesh                                 ::init();
    FemGui::ViewProviderFemMeshPython                           ::init();
    FemGui::ViewProviderFemMeshShape                            ::init();
    FemGui::ViewProviderFemMeshShapeNetgen                      ::init();
    FemGui::PropertyFemMeshItem                                 ::init();

    FemGui::ViewProviderSetElements                             ::init();
    FemGui::ViewProviderSetFaces                                ::init();
    FemGui::ViewProviderSetGeometry                             ::init();
    FemGui::ViewProviderSetNodes                                ::init();

    FemGui::ViewProviderSolver                                  ::init();
    FemGui::ViewProviderSolverPython                            ::init();

    FemGui::ViewProviderResult                                  ::init();
    FemGui::ViewProviderResultPython                            ::init();

#ifdef FC_USE_VTK
    FemGui::ViewProviderFemPostObject                           ::init();
    FemGui::ViewProviderFemPostPipeline                         ::init();
    FemGui::ViewProviderFemPostClip                             ::init();
    FemGui::ViewProviderFemPostCut                              ::init();
    FemGui::ViewProviderFemPostDataAlongLine                    ::init();
    FemGui::ViewProviderFemPostDataAtPoint                      ::init();
    FemGui::ViewProviderFemPostScalarClip                       ::init();
    FemGui::ViewProviderFemPostWarpVector                       ::init();

    FemGui::ViewProviderFemPostFunction                         ::init();
    FemGui::ViewProviderFemPostFunctionProvider                 ::init();
    FemGui::ViewProviderFemPostPlaneFunction                    ::init();
    FemGui::ViewProviderFemPostSphereFunction                   ::init();
#endif

    // register preferences pages on FEM, the order here will be the order of the tabs in pref widget
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemGeneralImp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemGmshImp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemCcxImp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemElmerImp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemZ88Imp> (QT_TRANSLATE_NOOP("QObject","FEM"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemMaterialImp> (QT_TRANSLATE_NOOP("QObject","FEM"));

    // register preferences pages on Import-Export
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemExportAbaqusImp> (QT_TRANSLATE_NOOP("QObject","Import-Export"));
    new Gui::PrefPageProducer<FemGui::DlgSettingsFemInOutVtkImp> (QT_TRANSLATE_NOOP("QObject","Import-Export"));

     // add resources and reloads the translators
    loadFemResource();

    PyMOD_Return(mod);
}
<|endoftext|>


<commit_before>#include "ImwWindowManagerDX11.h"
#include "ImwPlatformWindowDX11.h"

#include <imgui_impl_dx11.h>

using namespace ImWindow;

ImwWindowManagerDX11::ImwWindowManagerDX11()
{
	ImwPlatformWindowDX11::InitDX11();
}

ImwWindowManagerDX11::~ImwWindowManagerDX11()
{
	ImwPlatformWindowDX11::ShutdownDX11();
	//ImGui_ImplDX11_Shutdown();
}

void ImwWindowManagerDX11::InternalRun()
{
	MSG msg;
	if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	else
	{
		Update();
	}
}

ImwPlatformWindow* ImwWindowManagerDX11::CreatePlatformWindow(bool bMain, ImwPlatformWindow* pParent, bool bDragWindow)
{
	ImwPlatformWindowDX11* pWindow = new ImwPlatformWindowDX11(bMain, bDragWindow);
	ImwTest(pWindow->Init(pParent));
	return (ImwPlatformWindow*)pWindow;
}

ImVec2 ImwWindowManagerDX11::GetCursorPos()
{
	POINT oPoint;
	::GetCursorPos(&oPoint);
	return ImVec2(oPoint.x, oPoint.y);
}<commit_msg>Add sleep of 16 milliseconds for reduce framerate (High framerate make than my GPU do sharp creepy sound)<commit_after>#include "ImwWindowManagerDX11.h"
#include "ImwPlatformWindowDX11.h"

#include <imgui_impl_dx11.h>

using namespace ImWindow;

ImwWindowManagerDX11::ImwWindowManagerDX11()
{
	ImwPlatformWindowDX11::InitDX11();
}

ImwWindowManagerDX11::~ImwWindowManagerDX11()
{
	ImwPlatformWindowDX11::ShutdownDX11();
	//ImGui_ImplDX11_Shutdown();
}

void ImwWindowManagerDX11::InternalRun()
{
	MSG msg;
	if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	else
	{
		Update();
		Sleep(16);
	}
}

ImwPlatformWindow* ImwWindowManagerDX11::CreatePlatformWindow(bool bMain, ImwPlatformWindow* pParent, bool bDragWindow)
{
	ImwPlatformWindowDX11* pWindow = new ImwPlatformWindowDX11(bMain, bDragWindow);
	ImwTest(pWindow->Init(pParent));
	return (ImwPlatformWindow*)pWindow;
}

ImVec2 ImwWindowManagerDX11::GetCursorPos()
{
	POINT oPoint;
	::GetCursorPos(&oPoint);
	return ImVec2(oPoint.x, oPoint.y);
}<|endoftext|>


<commit_before>/*
 * opencog/atomspace/Link.cc
 *
 * Copyright (C) 2008-2010 OpenCog Foundation
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <stdio.h>

#include <opencog/atomspace/AtomTable.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/Node.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/Logger.h>

#include "Link.h"

//#define DPRINTF printf
#define DPRINTF(...)

using namespace opencog;

void Link::resort(void)
{
    // Caution: this comparison function MUST BE EXACTLY THE SAME as
    // the one in AtomTable.cc, used for Unordered links. Changing
    // this without changing the other one will break things!
    std::sort(_outgoing.begin(), _outgoing.end(), handle_less());
}

void Link::init(const std::vector<Handle>& outgoingVector)
{
    if (not classserver().isA(_type, LINK)) {
        throw InvalidParamException(TRACE_INFO,
            "Link ctor: Atom type is not a Link: '%d' %s.",
            _type, classserver().getTypeName(_type).c_str());
    }

    _outgoing = outgoingVector;
    // If the link is unordered, it will be normalized by sorting the
    // elements in the outgoing list.
    if (classserver().isA(_type, UNORDERED_LINK)) {
        resort();
    }
}

Link::~Link()
{
    DPRINTF("Deleting link:\n%s\n", this->toString().c_str());
}

std::string Link::toShortString(const std::string& indent)
{
    std::stringstream answer;
    std::string more_indent = indent + "  ";

    answer << indent << "(" << classserver().getTypeName(_type);
    answer << " " << getTruthValue()->toString() << "\n";

    // Here the target string is made. If a target is a node, its name is
    // concatenated. If it's a link, all its properties are concatenated.
    for (const Handle& h : _outgoing) {
        if (h.operator->() != NULL)
            answer << h->toShortString(more_indent);
        else
            answer << indent << "Undefined Atom!\n";
    }

    answer << indent << ") ; [" << _uuid << "]";

    if (_atomTable)
        answer << "[" << _atomTable->get_uuid() << "]\n";
    else
        answer << "[NULL]\n";

    return answer.str();
}

std::string Link::toString(const std::string& indent)
{
    std::string answer = indent;
    std::string more_indent = indent + "  ";

    answer += "(" + classserver().getTypeName(_type);

    // Print the TV and AV only if its not the default.
    if (not getAttentionValue()->isDefaultAV())
        answer += " (av " +
             std::to_string(getAttentionValue()->getSTI()) + " " +
             std::to_string(getAttentionValue()->getLTI()) + " " +
             std::to_string(getAttentionValue()->getVLTI()) + ")";

    if (not getTruthValue()->isDefaultTV())
        answer += " " + getTruthValue()->toString();

    answer += "\n";
    // Here, the outset string is made. If a target is a node,
    // its name is concatenated. If it's a link, then recurse.
    for (const Handle& h : _outgoing) {
        if (h.operator->() != NULL)
            answer += h->toString(more_indent);
        else
            answer += more_indent + "Undefined Atom!\n";
    }

    answer += indent + ") ; [" +
            std::to_string(_uuid) + "][" +
            std::to_string(_atomTable? _atomTable->get_uuid() : -1) +
            "]\n";

    return answer;
}

bool Link::isSource(Handle handle) const
{
    // On ordered links, only the first position in the outgoing set is a source
    // of this link. So, if the handle given is equal to the first position,
    // true is returned.
    Arity arity = getArity();
    if (classserver().isA(_type, ORDERED_LINK)) {
        return arity > 0 && _outgoing[0] == handle;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // If the link is unordered, the outgoing set is scanned, and the
        // method returns true if any position is equal to the handle given.
        for (Arity i = 0; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isSource(Handle) unknown link type %d", _type);
    }
    return false;
}

bool Link::isSource(size_t i) const
{
    // tests if the int given is valid.
    if (i > getArity()) {
        throw IndexErrorException(TRACE_INFO, "Link::isSource(size_t) invalid index argument");
    }

    // on ordered links, only the first position in the outgoing set is a source
    // of this link. So, if the int passed is 0, true is returned.
    if (classserver().isA(_type, ORDERED_LINK)) {
        return i == 0;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // on unordered links, the only thing that matters is if the int passed
        // is valid (if it is within 0..arity).
        return true;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isSource(int) unknown link type %d", _type);
    }
}

bool Link::isTarget(Handle handle) const
{
    // On ordered links, the first position of the outgoing set defines the
    // source of the link. The other positions are targets. So, it scans the
    // outgoing set from the second position searching for the given handle. If
    // it is found, true is returned.
    Arity arity = getArity();
    if (classserver().isA(_type, ORDERED_LINK)) {
        for (Arity i = 1; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // If the links is unordered, all the outgoing set is scanned.
        for (Arity i = 0; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isTarget(Handle) unknown link type %d", _type);
    }
    return false;
}

bool Link::isTarget(size_t i) const
{
    // tests if the int given is valid.
    if (i > getArity()) {
        throw IndexErrorException(TRACE_INFO, "Link::istarget(int) invalid index argument");
    }

    // on ordered links, the first position of the outgoing set defines the
    // source of the link. The other positions are targets.
    if (classserver().isA(_type, ORDERED_LINK)) {
        return i != 0;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // on unorderd links, the only thing that matter is if the position is
        // valid.
        return true;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isTarget(int) unkown link type");
    }
    return false;
}

bool Link::operator==(const Atom& other) const
{
    if (getType() != other.getType()) return false;
    const Link& olink = dynamic_cast<const Link&>(other);

    Arity arity = getArity();
    if (arity != olink.getArity()) return false;
    for (Arity i = 0; i < arity; i++)
    {
        NodePtr tn(NodeCast(_outgoing[i]));
        NodePtr on(NodeCast(olink._outgoing[i]));
        if (tn and on and *tn != *on) return false;

        LinkPtr tl(LinkCast(_outgoing[i]));
        LinkPtr ol(LinkCast(olink._outgoing[i]));
        if (tl and ol and *tl != *ol) return false;
    }
    return true;
}

bool Link::operator!=(const Atom& other) const
{
    return !(*this == other);
}

<commit_msg>Avoid printing the default TV<commit_after>/*
 * opencog/atomspace/Link.cc
 *
 * Copyright (C) 2008-2010 OpenCog Foundation
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <stdio.h>

#include <opencog/atomspace/AtomTable.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/Node.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/Logger.h>

#include "Link.h"

//#define DPRINTF printf
#define DPRINTF(...)

using namespace opencog;

void Link::resort(void)
{
    // Caution: this comparison function MUST BE EXACTLY THE SAME as
    // the one in AtomTable.cc, used for Unordered links. Changing
    // this without changing the other one will break things!
    std::sort(_outgoing.begin(), _outgoing.end(), handle_less());
}

void Link::init(const std::vector<Handle>& outgoingVector)
{
    if (not classserver().isA(_type, LINK)) {
        throw InvalidParamException(TRACE_INFO,
            "Link ctor: Atom type is not a Link: '%d' %s.",
            _type, classserver().getTypeName(_type).c_str());
    }

    _outgoing = outgoingVector;
    // If the link is unordered, it will be normalized by sorting the
    // elements in the outgoing list.
    if (classserver().isA(_type, UNORDERED_LINK)) {
        resort();
    }
}

Link::~Link()
{
    DPRINTF("Deleting link:\n%s\n", this->toString().c_str());
}

std::string Link::toShortString(const std::string& indent)
{
    std::stringstream answer;
    std::string more_indent = indent + "  ";

    answer << indent << "(" << classserver().getTypeName(_type);
    if (not getTruthValue()->isDefaultTV())
        answer << " " << getTruthValue()->toString();
    answer << "\n";

    // Here the target string is made. If a target is a node, its name is
    // concatenated. If it's a link, all its properties are concatenated.
    for (const Handle& h : _outgoing) {
        if (h.operator->() != NULL)
            answer << h->toShortString(more_indent);
        else
            answer << more_indent << "Undefined Atom!\n";
    }

    answer << indent << ") ; [" << _uuid << "]";

    if (_atomTable)
        answer << "[" << _atomTable->get_uuid() << "]\n";
    else
        answer << "[NULL]\n";

    return answer.str();
}

std::string Link::toString(const std::string& indent)
{
    std::string answer = indent;
    std::string more_indent = indent + "  ";

    answer += "(" + classserver().getTypeName(_type);

    // Print the TV and AV only if its not the default.
    if (not getAttentionValue()->isDefaultAV())
        answer += " (av " +
             std::to_string(getAttentionValue()->getSTI()) + " " +
             std::to_string(getAttentionValue()->getLTI()) + " " +
             std::to_string(getAttentionValue()->getVLTI()) + ")";

    if (not getTruthValue()->isDefaultTV())
        answer += " " + getTruthValue()->toString();

    answer += "\n";
    // Here, the outset string is made. If a target is a node,
    // its name is concatenated. If it's a link, then recurse.
    for (const Handle& h : _outgoing) {
        if (h.operator->() != NULL)
            answer += h->toString(more_indent);
        else
            answer += more_indent + "Undefined Atom!\n";
    }

    answer += indent + ") ; [" +
            std::to_string(_uuid) + "][" +
            std::to_string(_atomTable? _atomTable->get_uuid() : -1) +
            "]\n";

    return answer;
}

bool Link::isSource(Handle handle) const
{
    // On ordered links, only the first position in the outgoing set is a source
    // of this link. So, if the handle given is equal to the first position,
    // true is returned.
    Arity arity = getArity();
    if (classserver().isA(_type, ORDERED_LINK)) {
        return arity > 0 && _outgoing[0] == handle;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // If the link is unordered, the outgoing set is scanned, and the
        // method returns true if any position is equal to the handle given.
        for (Arity i = 0; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isSource(Handle) unknown link type %d", _type);
    }
    return false;
}

bool Link::isSource(size_t i) const
{
    // tests if the int given is valid.
    if (i > getArity()) {
        throw IndexErrorException(TRACE_INFO, "Link::isSource(size_t) invalid index argument");
    }

    // on ordered links, only the first position in the outgoing set is a source
    // of this link. So, if the int passed is 0, true is returned.
    if (classserver().isA(_type, ORDERED_LINK)) {
        return i == 0;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // on unordered links, the only thing that matters is if the int passed
        // is valid (if it is within 0..arity).
        return true;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isSource(int) unknown link type %d", _type);
    }
}

bool Link::isTarget(Handle handle) const
{
    // On ordered links, the first position of the outgoing set defines the
    // source of the link. The other positions are targets. So, it scans the
    // outgoing set from the second position searching for the given handle. If
    // it is found, true is returned.
    Arity arity = getArity();
    if (classserver().isA(_type, ORDERED_LINK)) {
        for (Arity i = 1; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // If the links is unordered, all the outgoing set is scanned.
        for (Arity i = 0; i < arity; i++) {
            if (_outgoing[i] == handle) {
                return true;
            }
        }
        return false;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isTarget(Handle) unknown link type %d", _type);
    }
    return false;
}

bool Link::isTarget(size_t i) const
{
    // tests if the int given is valid.
    if (i > getArity()) {
        throw IndexErrorException(TRACE_INFO, "Link::istarget(int) invalid index argument");
    }

    // on ordered links, the first position of the outgoing set defines the
    // source of the link. The other positions are targets.
    if (classserver().isA(_type, ORDERED_LINK)) {
        return i != 0;
    } else if (classserver().isA(_type, UNORDERED_LINK)) {
        // on unorderd links, the only thing that matter is if the position is
        // valid.
        return true;
    } else {
        throw InvalidParamException(TRACE_INFO, "Link::isTarget(int) unkown link type");
    }
    return false;
}

bool Link::operator==(const Atom& other) const
{
    if (getType() != other.getType()) return false;
    const Link& olink = dynamic_cast<const Link&>(other);

    Arity arity = getArity();
    if (arity != olink.getArity()) return false;
    for (Arity i = 0; i < arity; i++)
    {
        NodePtr tn(NodeCast(_outgoing[i]));
        NodePtr on(NodeCast(olink._outgoing[i]));
        if (tn and on and *tn != *on) return false;

        LinkPtr tl(LinkCast(_outgoing[i]));
        LinkPtr ol(LinkCast(olink._outgoing[i]));
        if (tl and ol and *tl != *ol) return false;
    }
    return true;
}

bool Link::operator!=(const Atom& other) const
{
    return !(*this == other);
}

<|endoftext|>


<commit_before>/* This file is part of the KDE libraries
   Copyright (C) 2001, 2003 Christoph Cullmann <cullmann@kde.org>
   Copyright (C) 2001 Charles Samuels <charles@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

// $Id$

#include "katecmds.h"

#include "katedocument.h"
#include "kateview.h"

#include <kdebug.h>

#include <qregexp.h>

namespace KateCommands
{

static void replace(QString &s, const QString &needle, const QString &with)
{
  int pos=0;
  while (1)
  {
    pos=s.find(needle, pos);
    if (pos==-1) break;
    s.replace(pos, needle.length(), with);
    pos+=with.length();
  }

}

static int backslashString(const QString &haystack, const QString &needle, int index)
{
  int len=haystack.length();
  int searchlen=needle.length();
  bool evenCount=true;
  while (index<len)
  {
    if (haystack[index]=='\\')
    {
      evenCount=!evenCount;
    }
    else
    {  // isn't a slash
      if (!evenCount)
      {
        if (haystack.mid(index, searchlen)==needle)
          return index-1;
      }
      evenCount=true;
    }
    index++;

  }

  return -1;
}

// exchange "\t" for the actual tab character, for example
static void exchangeAbbrevs(QString &str)
{
  // the format is (findreplace)*[nullzero]
  const char *magic="a\x07t\t";

  while (*magic)
  {
    int index=0;
    char replace=magic[1];
    while ((index=backslashString(str, QChar(*magic), index))!=-1)
    {
      str.replace(index, 2, QChar(replace));
      index++;
    }
    magic++;
    magic++;
  }
}

QString SedReplace::sedMagic(QString textLine, const QString &find, const QString &repOld, bool noCase, bool repeat)
{

  QRegExp matcher(find, noCase);

  int start=0;
  while (start!=-1)
  {
    start=matcher.search(textLine, start);

    if (start==-1) break;

    int length=matcher.matchedLength();

    QString rep=repOld;

    // now set the backreferences in the replacement
    QStringList backrefs=matcher.capturedTexts();
    int refnum=1;

    QStringList::Iterator i = backrefs.begin();
    ++i;

    for (; i!=backrefs.end(); ++i)
    {
      // I need to match "\\" or "", but not "\"
      QString number=QString::number(refnum);

      int index=0;
      while (index!=-1)
      {
        index=backslashString(rep, number, index);
        if (index>=0)
        {
          rep.replace(index, 2, *i);
          index+=(*i).length();
        }
      }

      refnum++;
    }

    replace(rep, "\\\\", "\\");
    replace(rep, "\\/", "/");

    textLine.replace(start, length, rep);
    if (!repeat) break;
    start+=rep.length();
  }

  return textLine;
}

static void setLineText(Kate::View *view, int line, const QString &text)
{
  if (view->getDoc()->insertLine(line, text))
    view->getDoc()->removeLine(line+1);
}

bool SedReplace::exec (Kate::View *view, const QString &cmd, QString &)
{
  kdDebug(13010)<<"SedReplace::execCmd()"<<endl;

  if (QRegExp("[$%]?s/.+/.*/[ig]*").search(cmd, 0)==-1)
    return false;

  bool fullFile=cmd[0]=='%';
  bool noCase=cmd[cmd.length()-1]=='i' || cmd[cmd.length()-2]=='i';
  bool repeat=cmd[cmd.length()-1]=='g' || cmd[cmd.length()-2]=='g';
  bool onlySelect=cmd[0]=='$';

  QRegExp splitter("^[$%]?s/((?:[^\\\\/]|\\\\.)*)/((?:[^\\\\/]|\\\\.)*)/[ig]*$");
  if (splitter.search(cmd)<0) return false;

  QString find=splitter.cap(1);
  kdDebug(13010)<< "SedReplace: find=" << find.latin1() <<endl;

  QString replace=splitter.cap(2);
  exchangeAbbrevs(replace);
  kdDebug(13010)<< "SedReplace: replace=" << replace.latin1() <<endl;

  if (fullFile)
  {
    int numLines=view->getDoc()->numLines();
    for (int line=0; line < numLines; line++)
    {
      QString text=view->getDoc()->textLine(line);
      text=sedMagic(text, find, replace, noCase, repeat);
      setLineText(view, line, text);
    }
  }
  else if (onlySelect)
  {
    // Not implemented
  }
  else
  { // just this line
    QString textLine=view->currentTextLine();
    int line=view->cursorLine();
    textLine=sedMagic(textLine, find, replace, noCase, repeat);
    setLineText(view, line, textLine);
  }
  return true;
}

bool Character::exec (Kate::View *view, const QString &_cmd, QString &)
{
  QString cmd = _cmd;

  // hex, octal, base 9+1
  QRegExp num("^char: *(0?x[0-9A-Fa-f]{1,4}|0[0-7]{1,6}|[0-9]{1,3})$");
  if (num.search(cmd)==-1) return false;

  cmd=num.cap(1);

  // identify the base

  unsigned short int number=0;
  int base=10;
  if (cmd[0]=='x' || cmd.left(2)=="0x")
  {
    cmd.replace(QRegExp("^0?x"), "");
    base=16;
  }
  else if (cmd[0]=='0')
    base=8;
  bool ok;
  number=cmd.toUShort(&ok, base);
  if (!ok || number==0) return false;
  if (number<=255)
  {
    char buf[2];
    buf[0]=(char)number;
    buf[1]=0;
    view->insertText(QString(buf));
  }
  else
  { // do the unicode thing
    QChar c(number);
    view->insertText(QString(&c, 1));
  }

  return true;
}

bool Goto::exec (Kate::View *view, const QString &cmd, QString &)
{
  if (cmd.left(5) != "goto:")
    return false;

  view->gotoLineNumber (cmd.mid(5, cmd.length()-5).toInt());

  return true;
}

bool Date::exec (Kate::View *view, const QString &cmd, QString &)
{
  if (cmd.left(4) != "date")
    return false;

  if (QDateTime::currentDateTime().toString(cmd.mid(5, cmd.length()-5)).length() > 0)
    view->insertText(QDateTime::currentDateTime().toString(cmd.mid(5, cmd.length()-5)));
  else
    view->insertText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

  return true;
}

}

// vim: noet

<commit_msg>let goto and char cmd even work sometimes<commit_after>/* This file is part of the KDE libraries
   Copyright (C) 2001, 2003 Christoph Cullmann <cullmann@kde.org>
   Copyright (C) 2001 Charles Samuels <charles@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

// $Id$

#include "katecmds.h"

#include "katedocument.h"
#include "kateview.h"

#include <kdebug.h>

#include <qregexp.h>

namespace KateCommands
{

static void replace(QString &s, const QString &needle, const QString &with)
{
  int pos=0;
  while (1)
  {
    pos=s.find(needle, pos);
    if (pos==-1) break;
    s.replace(pos, needle.length(), with);
    pos+=with.length();
  }

}

static int backslashString(const QString &haystack, const QString &needle, int index)
{
  int len=haystack.length();
  int searchlen=needle.length();
  bool evenCount=true;
  while (index<len)
  {
    if (haystack[index]=='\\')
    {
      evenCount=!evenCount;
    }
    else
    {  // isn't a slash
      if (!evenCount)
      {
        if (haystack.mid(index, searchlen)==needle)
          return index-1;
      }
      evenCount=true;
    }
    index++;

  }

  return -1;
}

// exchange "\t" for the actual tab character, for example
static void exchangeAbbrevs(QString &str)
{
  // the format is (findreplace)*[nullzero]
  const char *magic="a\x07t\t";

  while (*magic)
  {
    int index=0;
    char replace=magic[1];
    while ((index=backslashString(str, QChar(*magic), index))!=-1)
    {
      str.replace(index, 2, QChar(replace));
      index++;
    }
    magic++;
    magic++;
  }
}

QString SedReplace::sedMagic(QString textLine, const QString &find, const QString &repOld, bool noCase, bool repeat)
{

  QRegExp matcher(find, noCase);

  int start=0;
  while (start!=-1)
  {
    start=matcher.search(textLine, start);

    if (start==-1) break;

    int length=matcher.matchedLength();

    QString rep=repOld;

    // now set the backreferences in the replacement
    QStringList backrefs=matcher.capturedTexts();
    int refnum=1;

    QStringList::Iterator i = backrefs.begin();
    ++i;

    for (; i!=backrefs.end(); ++i)
    {
      // I need to match "\\" or "", but not "\"
      QString number=QString::number(refnum);

      int index=0;
      while (index!=-1)
      {
        index=backslashString(rep, number, index);
        if (index>=0)
        {
          rep.replace(index, 2, *i);
          index+=(*i).length();
        }
      }

      refnum++;
    }

    replace(rep, "\\\\", "\\");
    replace(rep, "\\/", "/");

    textLine.replace(start, length, rep);
    if (!repeat) break;
    start+=rep.length();
  }

  return textLine;
}

static void setLineText(Kate::View *view, int line, const QString &text)
{
  if (view->getDoc()->insertLine(line, text))
    view->getDoc()->removeLine(line+1);
}

bool SedReplace::exec (Kate::View *view, const QString &cmd, QString &)
{
  kdDebug(13010)<<"SedReplace::execCmd()"<<endl;

  if (QRegExp("[$%]?s/.+/.*/[ig]*").search(cmd, 0)==-1)
    return false;

  bool fullFile=cmd[0]=='%';
  bool noCase=cmd[cmd.length()-1]=='i' || cmd[cmd.length()-2]=='i';
  bool repeat=cmd[cmd.length()-1]=='g' || cmd[cmd.length()-2]=='g';
  bool onlySelect=cmd[0]=='$';

  QRegExp splitter("^[$%]?s/((?:[^\\\\/]|\\\\.)*)/((?:[^\\\\/]|\\\\.)*)/[ig]*$");
  if (splitter.search(cmd)<0) return false;

  QString find=splitter.cap(1);
  kdDebug(13010)<< "SedReplace: find=" << find.latin1() <<endl;

  QString replace=splitter.cap(2);
  exchangeAbbrevs(replace);
  kdDebug(13010)<< "SedReplace: replace=" << replace.latin1() <<endl;

  if (fullFile)
  {
    int numLines=view->getDoc()->numLines();
    for (int line=0; line < numLines; line++)
    {
      QString text=view->getDoc()->textLine(line);
      text=sedMagic(text, find, replace, noCase, repeat);
      setLineText(view, line, text);
    }
  }
  else if (onlySelect)
  {
    // Not implemented
  }
  else
  { // just this line
    QString textLine=view->currentTextLine();
    int line=view->cursorLine();
    textLine=sedMagic(textLine, find, replace, noCase, repeat);
    setLineText(view, line, textLine);
  }
  return true;
}

bool Character::exec (Kate::View *view, const QString &_cmd, QString &)
{
  QString cmd = _cmd;

  // hex, octal, base 9+1
  QRegExp num("^char *(0?x[0-9A-Fa-f]{1,4}|0[0-7]{1,6}|[0-9]{1,3})$");
  if (num.search(cmd)==-1) return false;

  cmd=num.cap(1);

  // identify the base

  unsigned short int number=0;
  int base=10;
  if (cmd[0]=='x' || cmd.left(2)=="0x")
  {
    cmd.replace(QRegExp("^0?x"), "");
    base=16;
  }
  else if (cmd[0]=='0')
    base=8;
  bool ok;
  number=cmd.toUShort(&ok, base);
  if (!ok || number==0) return false;
  if (number<=255)
  {
    char buf[2];
    buf[0]=(char)number;
    buf[1]=0;
    view->insertText(QString(buf));
  }
  else
  { // do the unicode thing
    QChar c(number);
    view->insertText(QString(&c, 1));
  }

  return true;
}

bool Goto::exec (Kate::View *view, const QString &cmd, QString &)
{
  if (cmd.left(4) != "goto")
    return false;

  QStringList args( QStringList::split( QRegExp("\\s+"), cmd ) );
  args.remove( args.first() );

  view->gotoLineNumber (args[0].toInt());

  return true;
}

bool Date::exec (Kate::View *view, const QString &cmd, QString &)
{
  if (cmd.left(4) != "date")
    return false;

  if (QDateTime::currentDateTime().toString(cmd.mid(5, cmd.length()-5)).length() > 0)
    view->insertText(QDateTime::currentDateTime().toString(cmd.mid(5, cmd.length()-5)));
  else
    view->insertText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

  return true;
}

}

// vim: noet

<|endoftext|>


<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#include "hadesmem/detail/initialize.hpp"

#include <ctime>
#include <random>
#include <iostream>

#include <hadesmem/detail/warning_disable_prefix.hpp>
#include <boost/assert.hpp>
#include <boost/locale.hpp>
#include <boost/filesystem.hpp>
#include <hadesmem/detail/warning_disable_suffix.hpp>

#include <hadesmem/config.hpp>
#include <windows.h>
// Required for ::_CrtSetDbgFlag.
// Does not compile under GCC.
#if !defined(HADESMEM_GCC)
// Macro unused under Clang.
#if !defined(HADESMEM_CLANG)
#define _CRTDBG_MAP_ALLOC
#endif // #if !defined(HADESMEM_CLANG)
#include <stdlib.h>
#include <crtdbg.h>
#endif // #if !defined(HADESMEM_GCC)

#include <hadesmem/error.hpp>

#ifndef PROCESS_CALLBACK_FILTER_ENABLED
#define PROCESS_CALLBACK_FILTER_ENABLED 0x1UL
#endif // #ifndef PROCESS_CALLBACK_FILTER_ENABLED

namespace hadesmem
{

namespace detail
{

void DisableUserModeCallbackExceptionFilter()
{
  HMODULE const k32_mod = ::GetModuleHandle(L"kernel32");
  if (!k32_mod)
  {
    DWORD const last_error = ::GetLastError();
    HADESMEM_THROW_EXCEPTION(hadesmem::Error() <<
      hadesmem::ErrorString("GetModuleHandle failed.") <<
      hadesmem::ErrorCodeWinLast(last_error));
  }

  typedef BOOL (NTAPI *GetProcessUserModeExceptionPolicyPtr)(LPDWORD lpFlags);
  typedef BOOL (NTAPI *SetProcessUserModeExceptionPolicyPtr)(DWORD dwFlags);

  // These APIs are not available by default until Windows 7 SP1, so they
  // must be called dynamically.
  auto const get_policy =
    reinterpret_cast<GetProcessUserModeExceptionPolicyPtr>(
    ::GetProcAddress(k32_mod, "GetProcessUserModeExceptionPolicy"));
  auto const set_policy =
    reinterpret_cast<SetProcessUserModeExceptionPolicyPtr>(
    ::GetProcAddress(k32_mod, "SetProcessUserModeExceptionPolicy"));

  DWORD flags;
  if (get_policy && set_policy && get_policy(&flags))
  {
    set_policy(flags & ~PROCESS_CALLBACK_FILTER_ENABLED);
  }
}

void EnableCrtDebugFlags()
{
  // Only enable in debug mode.
#if defined(_DEBUG)
  // Does not compile under GCC.
#if !defined(HADESMEM_GCC)
  int dbg_flags = ::_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  dbg_flags |= _CRTDBG_ALLOC_MEM_DF;
  dbg_flags |= _CRTDBG_DELAY_FREE_MEM_DF;
  dbg_flags |= _CRTDBG_LEAK_CHECK_DF;
  ::_CrtSetDbgFlag(dbg_flags);
#endif // #if !defined(HADESMEM_GCC)
#endif // #if defined(_DEBUG)
}

void EnableTerminationOnHeapCorruption()
{
  if (!::HeapSetInformation(::GetProcessHeap(),
    HeapEnableTerminationOnCorruption, nullptr, 0))
  {
    DWORD const last_error = ::GetLastError();
    HADESMEM_THROW_EXCEPTION(hadesmem::Error() <<
      hadesmem::ErrorString("HeapSetInformation failed.") <<
      hadesmem::ErrorCodeWinLast(last_error));
  }
}

void EnableBottomUpRand()
{
  // This is a defense-in-depth measure, so the time should be sufficient
  // entropy in all but the rarest cases.
  std::mt19937 rand(static_cast<unsigned int>(std::time(nullptr)));
  std::uniform_int_distribution<unsigned int> uint_dist(0, 256);
  unsigned int const num_allocs = uint_dist(rand);
  for (unsigned int i = 0; i != num_allocs; ++i)
  {
    // Reserve memory only, as committing it would be a waste.
    DWORD const kAllocSize64K = 64 * 1024;
    if (!::VirtualAlloc(NULL, kAllocSize64K, MEM_RESERVE, PAGE_NOACCESS))
    {
      DWORD const last_error = ::GetLastError();
      HADESMEM_THROW_EXCEPTION(hadesmem::Error() <<
        hadesmem::ErrorString("VirtualAlloc failed.") <<
        hadesmem::ErrorCodeWinLast(last_error));
    }
  }
}

std::locale ImbueAllDefault()
{
  // Use the Windows API backend to (hopefully) provide consistent behaviour
  // across different compilers and standard library implementations (as
  // opposed to the standard library backend).
  auto backend = boost::locale::localization_backend_manager::global();
  backend.select("winapi");

  boost::locale::generator gen(backend);

  std::locale const locale = gen("");

  // Ensure the locale uses a UTF-8 backend.
  BOOST_ASSERT(std::use_facet<boost::locale::info>(locale).utf8());

  return ImbueAll(locale);
}

std::locale ImbueAll(std::locale const& locale)
{
  auto const old_loc = std::locale::global(locale);

  std::cin.imbue(locale);
  std::cout.imbue(locale);
  std::cerr.imbue(locale);
  std::clog.imbue(locale);

  std::wcin.imbue(locale);
  std::wcout.imbue(locale);
  std::wcerr.imbue(locale);
  std::wclog.imbue(locale);

  boost::filesystem::path::imbue(locale);

  // According to comments in the Boost.Locale examples, this is needed
  // to prevent the C standard library performing string conversions
  // instead of the C++ standard library on some platforms. Unfortunately,
  // it is not specified which platforms this applies to, so I'm unsure
  // if this is ever relevant to Windows, but it's better safe than sorry.
  std::ios_base::sync_with_stdio(false);

  return old_loc;
}

}

}
<commit_msg>* Disable _CRTDBG_DELAY_FREE_MEM_DF flag because of the crazy memory usage it causes under some of my test apps.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#include "hadesmem/detail/initialize.hpp"

#include <ctime>
#include <random>
#include <iostream>

#include <hadesmem/detail/warning_disable_prefix.hpp>
#include <boost/assert.hpp>
#include <boost/locale.hpp>
#include <boost/filesystem.hpp>
#include <hadesmem/detail/warning_disable_suffix.hpp>

#include <hadesmem/config.hpp>
#include <windows.h>
// Required for ::_CrtSetDbgFlag.
// Does not compile under GCC.
#if !defined(HADESMEM_GCC)
// Macro unused under Clang.
#if !defined(HADESMEM_CLANG)
#define _CRTDBG_MAP_ALLOC
#endif // #if !defined(HADESMEM_CLANG)
#include <stdlib.h>
#include <crtdbg.h>
#endif // #if !defined(HADESMEM_GCC)

#include <hadesmem/error.hpp>

#ifndef PROCESS_CALLBACK_FILTER_ENABLED
#define PROCESS_CALLBACK_FILTER_ENABLED 0x1UL
#endif // #ifndef PROCESS_CALLBACK_FILTER_ENABLED

namespace hadesmem
{

namespace detail
{

void DisableUserModeCallbackExceptionFilter()
{
  HMODULE const k32_mod = ::GetModuleHandle(L"kernel32");
  if (!k32_mod)
  {
    DWORD const last_error = ::GetLastError();
    HADESMEM_THROW_EXCEPTION(hadesmem::Error() <<
      hadesmem::ErrorString("GetModuleHandle failed.") <<
      hadesmem::ErrorCodeWinLast(last_error));
  }

  typedef BOOL (NTAPI *GetProcessUserModeExceptionPolicyPtr)(LPDWORD lpFlags);
  typedef BOOL (NTAPI *SetProcessUserModeExceptionPolicyPtr)(DWORD dwFlags);

  // These APIs are not available by default until Windows 7 SP1, so they
  // must be called dynamically.
  auto const get_policy =
    reinterpret_cast<GetProcessUserModeExceptionPolicyPtr>(
    ::GetProcAddress(k32_mod, "GetProcessUserModeExceptionPolicy"));
  auto const set_policy =
    reinterpret_cast<SetProcessUserModeExceptionPolicyPtr>(
    ::GetProcAddress(k32_mod, "SetProcessUserModeExceptionPolicy"));

  DWORD flags;
  if (get_policy && set_policy && get_policy(&flags))
  {
    set_policy(flags & ~PROCESS_CALLBACK_FILTER_ENABLED);
  }
}

void EnableCrtDebugFlags()
{
  // Only enable in debug mode.
#if defined(_DEBUG)
  // Does not compile under GCC.
#if !defined(HADESMEM_GCC)
  int dbg_flags = ::_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  dbg_flags |= _CRTDBG_ALLOC_MEM_DF;
  dbg_flags |= _CRTDBG_LEAK_CHECK_DF;
  ::_CrtSetDbgFlag(dbg_flags);
#endif // #if !defined(HADESMEM_GCC)
#endif // #if defined(_DEBUG)
}

void EnableTerminationOnHeapCorruption()
{
  if (!::HeapSetInformation(::GetProcessHeap(),
    HeapEnableTerminationOnCorruption, nullptr, 0))
  {
    DWORD const last_error = ::GetLastError();
    HADESMEM_THROW_EXCEPTION(hadesmem::Error() <<
      hadesmem::ErrorString("HeapSetInformation failed.") <<
      hadesmem::ErrorCodeWinLast(last_error));
  }
}

void EnableBottomUpRand()
{
  // This is a defense-in-depth measure, so the time should be sufficient
  // entropy in all but the rarest cases.
  std::mt19937 rand(static_cast<unsigned int>(std::time(nullptr)));
  std::uniform_int_distribution<unsigned int> uint_dist(0, 256);
  unsigned int const num_allocs = uint_dist(rand);
  for (unsigned int i = 0; i != num_allocs; ++i)
  {
    // Reserve memory only, as committing it would be a waste.
    DWORD const kAllocSize64K = 64 * 1024;
    if (!::VirtualAlloc(NULL, kAllocSize64K, MEM_RESERVE, PAGE_NOACCESS))
    {
      DWORD const last_error = ::GetLastError();
      HADESMEM_THROW_EXCEPTION(hadesmem::Error() <<
        hadesmem::ErrorString("VirtualAlloc failed.") <<
        hadesmem::ErrorCodeWinLast(last_error));
    }
  }
}

std::locale ImbueAllDefault()
{
  // Use the Windows API backend to (hopefully) provide consistent behaviour
  // across different compilers and standard library implementations (as
  // opposed to the standard library backend).
  auto backend = boost::locale::localization_backend_manager::global();
  backend.select("winapi");

  boost::locale::generator gen(backend);

  std::locale const locale = gen("");

  // Ensure the locale uses a UTF-8 backend.
  BOOST_ASSERT(std::use_facet<boost::locale::info>(locale).utf8());

  return ImbueAll(locale);
}

std::locale ImbueAll(std::locale const& locale)
{
  auto const old_loc = std::locale::global(locale);

  std::cin.imbue(locale);
  std::cout.imbue(locale);
  std::cerr.imbue(locale);
  std::clog.imbue(locale);

  std::wcin.imbue(locale);
  std::wcout.imbue(locale);
  std::wcerr.imbue(locale);
  std::wclog.imbue(locale);

  boost::filesystem::path::imbue(locale);

  // According to comments in the Boost.Locale examples, this is needed
  // to prevent the C standard library performing string conversions
  // instead of the C++ standard library on some platforms. Unfortunately,
  // it is not specified which platforms this applies to, so I'm unsure
  // if this is ever relevant to Windows, but it's better safe than sorry.
  std::ios_base::sync_with_stdio(false);

  return old_loc;
}

}

}
<|endoftext|>


<commit_before>#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring

JNICALL
Java_com_breadwallet_brcore_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}
<commit_msg>CORE: Remove Java/Core/.../native-lib.cpp (unused, autogenerated)<commit_after><|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qlocalserver.h"
#include "qlocalserver_p.h"
#include "qlocalsocket.h"
#include "qlocalsocket_p.h"

#include <qhostaddress.h>
#include <qsettings.h>
#include <qdebug.h>

QT_BEGIN_NAMESPACE

void QLocalServerPrivate::init()
{
    Q_Q(QLocalServer);
    q->connect(&tcpServer, SIGNAL(newConnection()), SLOT(_q_onNewConnection()));
}

bool QLocalServerPrivate::listen(const QString &requestedServerName)
{
    if (!tcpServer.listen(QHostAddress::LocalHost))
        return false;

    const QLatin1String prefix("QLocalServer/");
    if (requestedServerName.startsWith(prefix))
        fullServerName = requestedServerName;
    else
        fullServerName = prefix + requestedServerName;

    QSettings settings(QLatin1String("Trolltech"), QLatin1String("Qt"));
    if (settings.contains(fullServerName)) {
        qWarning("QLocalServer::listen: server name is already in use.");
        tcpServer.close();
        return false;
    }

    settings.setValue(fullServerName, tcpServer.serverPort());
    return true;
}

void QLocalServerPrivate::closeServer()
{
    QSettings settings(QLatin1String("Trolltech"), QLatin1String("Qt"));
    if (fullServerName == QLatin1String("QLocalServer"))
        settings.setValue(fullServerName, QVariant());
    else
        settings.remove(fullServerName);
    tcpServer.close();
}

void QLocalServerPrivate::waitForNewConnection(int msec, bool *timedOut)
{
    if (pendingConnections.isEmpty())
        tcpServer.waitForNewConnection(msec, timedOut);
    else
        *timedOut = false;
}

void QLocalServerPrivate::_q_onNewConnection()
{
    Q_Q(QLocalServer);
    QTcpSocket* tcpSocket = tcpServer.nextPendingConnection();
    if (!tcpSocket) {
        qWarning("QLocalServer: no pending connection");
        return;
    }

    tcpSocket->setParent(q);
    const quintptr socketDescriptor = tcpSocket->socketDescriptor();
    q->incomingConnection(socketDescriptor);
}

bool QLocalServerPrivate::removeServer(const QString &name)
{
    const QLatin1String prefix("QLocalServer/");
    QString serverName;
    if (name.startsWith(prefix))
        serverName = name;
    else
        serverName = prefix + name;

    QSettings settings(QLatin1String("Trolltech"), QLatin1String("Qt"));
    if (settings.contains(serverName))
        settings.remove(serverName);

    return true;
}

QT_END_NAMESPACE
<commit_msg>fix crash in QLocalServer on WinCE when waitForNewConnection times out<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qlocalserver.h"
#include "qlocalserver_p.h"
#include "qlocalsocket.h"
#include "qlocalsocket_p.h"

#include <qhostaddress.h>
#include <qsettings.h>
#include <qdebug.h>

QT_BEGIN_NAMESPACE

void QLocalServerPrivate::init()
{
    Q_Q(QLocalServer);
    q->connect(&tcpServer, SIGNAL(newConnection()), SLOT(_q_onNewConnection()));
}

bool QLocalServerPrivate::listen(const QString &requestedServerName)
{
    if (!tcpServer.listen(QHostAddress::LocalHost))
        return false;

    const QLatin1String prefix("QLocalServer/");
    if (requestedServerName.startsWith(prefix))
        fullServerName = requestedServerName;
    else
        fullServerName = prefix + requestedServerName;

    QSettings settings(QLatin1String("Trolltech"), QLatin1String("Qt"));
    if (settings.contains(fullServerName)) {
        qWarning("QLocalServer::listen: server name is already in use.");
        tcpServer.close();
        return false;
    }

    settings.setValue(fullServerName, tcpServer.serverPort());
    return true;
}

void QLocalServerPrivate::closeServer()
{
    QSettings settings(QLatin1String("Trolltech"), QLatin1String("Qt"));
    if (fullServerName == QLatin1String("QLocalServer"))
        settings.setValue(fullServerName, QVariant());
    else
        settings.remove(fullServerName);
    tcpServer.close();
}

void QLocalServerPrivate::waitForNewConnection(int msec, bool *timedOut)
{
    if (pendingConnections.isEmpty())
        tcpServer.waitForNewConnection(msec, timedOut);
    else if (timedOut)
        *timedOut = false;
}

void QLocalServerPrivate::_q_onNewConnection()
{
    Q_Q(QLocalServer);
    QTcpSocket* tcpSocket = tcpServer.nextPendingConnection();
    if (!tcpSocket) {
        qWarning("QLocalServer: no pending connection");
        return;
    }

    tcpSocket->setParent(q);
    const quintptr socketDescriptor = tcpSocket->socketDescriptor();
    q->incomingConnection(socketDescriptor);
}

bool QLocalServerPrivate::removeServer(const QString &name)
{
    const QLatin1String prefix("QLocalServer/");
    QString serverName;
    if (name.startsWith(prefix))
        serverName = name;
    else
        serverName = prefix + name;

    QSettings settings(QLatin1String("Trolltech"), QLatin1String("Qt"));
    if (settings.contains(serverName))
        settings.remove(serverName);

    return true;
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/*
 * Copyright 2016 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#define GL_GLEXT_PROTOTYPES 1
#ifdef OX_OS_Darwin
#define GL_SILENCE_DEPRECATION
#include <OpenGL/gl3.h>
#else
#include <GLES3/gl3.h>
#endif

#include <ox/std/error.hpp>
#include <ox/std/trace.hpp>

namespace nostalgia::core::renderer {

struct Empty {};

struct TextureBase {

	GLsizei width = 0;
	GLsizei height = 0;

};

template<auto del, typename Base = Empty>
struct GLobject: public Base {

	GLuint id = 0;

	constexpr GLobject() = default;

	explicit constexpr GLobject(GLuint id) {
		this->id = id;
	}

	constexpr GLobject(GLobject &&o) {
		id = o.id;
		o.id = 0;
	}

	~GLobject() {
		del(id);
	}

	GLobject &operator=(GLobject &&o) {
		id = o.id;
		o.id = 0;
		return *this;
	}

	constexpr GLuint release() noexcept {
		auto out = id;
		id = 0;
		return out;
	}

	constexpr operator GLuint&() noexcept {
		return id;
	}

	constexpr operator const GLuint&() const noexcept {
		return id;
	}

};

void deleteTexture(GLuint t);

extern template struct GLobject<glDeleteProgram>;
extern template struct GLobject<glDeleteShader>;
extern template struct GLobject<deleteTexture, TextureBase>;
using Shader = GLobject<glDeleteShader>;
using Program = GLobject<glDeleteProgram>;
using Texture = GLobject<deleteTexture, TextureBase>;

struct Bufferset {
	GLuint vao = 0;
	GLuint vbo = 0;
	GLuint ebo = 0;
	Texture tex;
	GLsizei eboElements = 0;
};

[[nodiscard]]
ox::Result<Program> buildShaderProgram(const GLchar *vert, const GLchar *frag);

void destroy(const Bufferset &bufferset);

}
<commit_msg>[nostalgia/core/userland] Fix GLobject to destruct upon reassignment<commit_after>/*
 * Copyright 2016 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#define GL_GLEXT_PROTOTYPES 1
#ifdef OX_OS_Darwin
#define GL_SILENCE_DEPRECATION
#include <OpenGL/gl3.h>
#else
#include <GLES3/gl3.h>
#endif

#include <ox/std/error.hpp>
#include <ox/std/trace.hpp>

namespace nostalgia::core::renderer {

struct Empty {};

struct TextureBase {

	GLsizei width = 0;
	GLsizei height = 0;

};

template<auto del, typename Base = Empty>
struct GLobject: public Base {

	GLuint id = 0;

	constexpr GLobject() = default;

	explicit constexpr GLobject(GLuint id) {
		this->id = id;
	}

	constexpr GLobject(GLobject &&o) {
		id = o.id;
		o.id = 0;
	}

	~GLobject() {
		del(id);
	}

	GLobject &operator=(GLobject &&o) {
		this->~GLobject();
		id = o.id;
		o.id = 0;
		return *this;
	}

	constexpr GLuint release() noexcept {
		auto out = id;
		id = 0;
		return out;
	}

	constexpr operator GLuint&() noexcept {
		return id;
	}

	constexpr operator const GLuint&() const noexcept {
		return id;
	}

};

void deleteTexture(GLuint t);

extern template struct GLobject<glDeleteProgram>;
extern template struct GLobject<glDeleteShader>;
extern template struct GLobject<deleteTexture, TextureBase>;
using Shader = GLobject<glDeleteShader>;
using Program = GLobject<glDeleteProgram>;
using Texture = GLobject<deleteTexture, TextureBase>;

struct Bufferset {
	GLuint vao = 0;
	GLuint vbo = 0;
	GLuint ebo = 0;
	Texture tex;
	GLsizei eboElements = 0;
};

[[nodiscard]]
ox::Result<Program> buildShaderProgram(const GLchar *vert, const GLchar *frag);

void destroy(const Bufferset &bufferset);

}
<|endoftext|>


<commit_before>
#ifndef HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H
#define HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H

#include "FFmpegDecoderAudio.hpp"
#include "FFmpegDecoderVideo.hpp"

#include <osg/Notify>

namespace osgFFmpeg {

class FormatContextPtr
{
    public:

        typedef AVFormatContext T;

        explicit FormatContextPtr() : _ptr(0) {}
        explicit FormatContextPtr(T* ptr) : _ptr(ptr) {}

        ~FormatContextPtr()
        {
            cleanup();
        }

        T* get() { return _ptr; }

        T * operator-> () const // never throws
        {
            return _ptr;
        }

        void reset(T* ptr)
        {
            if (ptr==_ptr) return;
            cleanup();
            _ptr = ptr;
        }

        void cleanup()
        {
            if (_ptr)
            {
                osg::notify(osg::NOTICE)<<"Calling av_close_input_file("<<_ptr<<")"<<std::endl;
                av_close_input_file(_ptr);
            }
            _ptr = 0;
        }

    protected:

        T* _ptr;
};

class FFmpegDecoder : public osg::Referenced
{
public:

    FFmpegDecoder();
    ~FFmpegDecoder();

    bool open(const std::string & filename);
    void close(bool waitForThreadToExit);

    bool readNextPacket();
    void rewind();

    void loop(bool loop);
    bool loop() const;

    double duration() const;

    FFmpegDecoderAudio & audio_decoder();
    FFmpegDecoderVideo & video_decoder();
    FFmpegDecoderAudio const & audio_decoder() const;
    FFmpegDecoderVideo const & video_decoder() const;

protected:

    enum State
    {
        NORMAL,
        END_OF_STREAM,
        REWINDING
    };

    typedef BoundedMessageQueue<FFmpegPacket> PacketQueue;

    void findAudioStream();
    void findVideoStream();
    void flushAudioQueue();
    void flushVideoQueue();
    bool readNextPacketNormal();
    bool readNextPacketEndOfStream();
    bool readNextPacketRewinding();
    void rewindButDontFlushQueues();

    FormatContextPtr    m_format_context;
    AVStream *            m_audio_stream;
    AVStream *            m_video_stream;

    unsigned int        m_audio_index;
    unsigned int        m_video_index;

    FFmpegClocks        m_clocks;
    FFmpegPacket        m_pending_packet;
    PacketQueue            m_audio_queue;
    PacketQueue            m_video_queue;

    FFmpegDecoderAudio    m_audio_decoder;
    FFmpegDecoderVideo    m_video_decoder;

    double                m_duration;
    double                m_start;

    State                m_state;
    bool                m_loop;
};

inline void FFmpegDecoder::loop(const bool loop)
{
    m_loop = loop;
}

inline bool FFmpegDecoder::loop() const
{
    return m_loop;
}

inline double FFmpegDecoder::duration() const
{
    return double(m_format_context->duration) / AV_TIME_BASE;
}

inline FFmpegDecoderAudio & FFmpegDecoder::audio_decoder()
{
    return m_audio_decoder;
}

inline FFmpegDecoderVideo & FFmpegDecoder::video_decoder()
{
    return m_video_decoder;
}

inline FFmpegDecoderAudio const & FFmpegDecoder::audio_decoder() const
{
    return m_audio_decoder;
}

inline FFmpegDecoderVideo const & FFmpegDecoder::video_decoder() const
{
    return m_video_decoder;
}

} // namespace osgFFmpeg

#endif // HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H
<commit_msg>Fixed warning<commit_after>
#ifndef HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H
#define HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H

#include "FFmpegDecoderAudio.hpp"
#include "FFmpegDecoderVideo.hpp"

#include <osg/Notify>

namespace osgFFmpeg {

class FormatContextPtr
{
    public:

        typedef AVFormatContext T;

        explicit FormatContextPtr() : _ptr(0) {}
        explicit FormatContextPtr(T* ptr) : _ptr(ptr) {}

        ~FormatContextPtr()
        {
            cleanup();
        }

        T* get() { return _ptr; }

        T * operator-> () const // never throws
        {
            return _ptr;
        }

        void reset(T* ptr)
        {
            if (ptr==_ptr) return;
            cleanup();
            _ptr = ptr;
        }

        void cleanup()
        {
            if (_ptr)
            {
                osg::notify(osg::NOTICE)<<"Calling av_close_input_file("<<_ptr<<")"<<std::endl;
                av_close_input_file(_ptr);
            }
            _ptr = 0;
        }

    protected:

        T* _ptr;
};

class FFmpegDecoder : public osg::Referenced
{
public:

    FFmpegDecoder();
    ~FFmpegDecoder();

    bool open(const std::string & filename);
    void close(bool waitForThreadToExit);

    bool readNextPacket();
    void rewind();

    void loop(bool loop);
    bool loop() const;

    double duration() const;

    FFmpegDecoderAudio & audio_decoder();
    FFmpegDecoderVideo & video_decoder();
    FFmpegDecoderAudio const & audio_decoder() const;
    FFmpegDecoderVideo const & video_decoder() const;

protected:

    enum State
    {
        NORMAL,
        END_OF_STREAM,
        REWINDING
    };

    typedef BoundedMessageQueue<FFmpegPacket> PacketQueue;

    void findAudioStream();
    void findVideoStream();
    void flushAudioQueue();
    void flushVideoQueue();
    bool readNextPacketNormal();
    bool readNextPacketEndOfStream();
    bool readNextPacketRewinding();
    void rewindButDontFlushQueues();

    FormatContextPtr    m_format_context;
    AVStream *            m_audio_stream;
    AVStream *            m_video_stream;

    int                 m_audio_index;
    int                 m_video_index;

    FFmpegClocks        m_clocks;
    FFmpegPacket        m_pending_packet;
    PacketQueue            m_audio_queue;
    PacketQueue            m_video_queue;

    FFmpegDecoderAudio    m_audio_decoder;
    FFmpegDecoderVideo    m_video_decoder;

    double                m_duration;
    double                m_start;

    State                m_state;
    bool                m_loop;
};

inline void FFmpegDecoder::loop(const bool loop)
{
    m_loop = loop;
}

inline bool FFmpegDecoder::loop() const
{
    return m_loop;
}

inline double FFmpegDecoder::duration() const
{
    return double(m_format_context->duration) / AV_TIME_BASE;
}

inline FFmpegDecoderAudio & FFmpegDecoder::audio_decoder()
{
    return m_audio_decoder;
}

inline FFmpegDecoderVideo & FFmpegDecoder::video_decoder()
{
    return m_video_decoder;
}

inline FFmpegDecoderAudio const & FFmpegDecoder::audio_decoder() const
{
    return m_audio_decoder;
}

inline FFmpegDecoderVideo const & FFmpegDecoder::video_decoder() const
{
    return m_video_decoder;
}

} // namespace osgFFmpeg

#endif // HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H
<|endoftext|>