<commit_before>#include "stdafx.h"
#include "CallbackHelper.h"

// *****************************************************************
//	   GDALProgressCallback()
// *****************************************************************
int CPL_STDCALL GDALProgressCallback(double dfComplete, const char* pszMessage, void *pData)
{
	CallbackParams* params = (CallbackParams*)pData;

	if (params != NULL && params->cBack != NULL)
	{
		long percent = long(dfComplete * 100.0);
		CallbackHelper::Progress(params->cBack, percent, params->sMsg);
	}
	return TRUE;
}

// ********************************************************************
//		DisplayProgress()
// ********************************************************************
void CallbackHelper::Progress(ICallback* localCback, int index, int count, const char* message, long& lastPercent)
{
	Progress(localCback, index, (double)count, message, m_globalSettings.emptyBstr, lastPercent);
}

void CallbackHelper::Progress(ICallback* localCback, int index, int count, const char* message, BSTR& key, long& lastPercent)
{
	Progress(localCback, index, (double)count, message, key, lastPercent);
}

// ********************************************************************
//		GetCurrent()
// ********************************************************************
ICallback* CallbackHelper::GetCurrent(ICallback* localCback)
{
	if (m_globalSettings.overrideLocalCallback)
	{
		return m_globalSettings.callback ? m_globalSettings.callback : localCback;
	}
	else
	{
		return localCback ? localCback : m_globalSettings.callback;
	}
}

// ********************************************************************
//		DisplayProgress()
// ********************************************************************
void CallbackHelper::Progress(ICallback* localCback, int index, double count, const char* message, BSTR& key, long& lastPercent)
{
	ICallback* callback = GetCurrent(localCback);
	if (!callback) return;

	long newpercent = (long)(((double)(index + 1) / count) * 100);
	if (newpercent > lastPercent)
	{
		lastPercent = newpercent;
		CComBSTR bstrMsg(message);
		callback->Progress(key, newpercent, bstrMsg);
	}
}

// ********************************************************************
//		DisplayProgress()
// ********************************************************************
void CallbackHelper::Progress(ICallback* localCback, int percent, const char* message, BSTR& key)
{
	ICallback* callback = GetCurrent(localCback);
	if (!callback) return;

	CComBSTR bstrMsg(message);
	callback->Progress(key, percent, bstrMsg);
}

// ********************************************************************
//		DisplayProgress()
// ********************************************************************
void CallbackHelper::Progress(ICallback* localCback, int percent, const char* message)
{
	ICallback* callback = GetCurrent(localCback);
	if (!callback) return;

	if (!message) message = "";
	CComBSTR bstrMsg(message);
	callback->Progress(m_globalSettings.emptyBstr, percent, bstrMsg);
}

// ********************************************************************
//		DisplayProgressCompleted()
// ********************************************************************
void CallbackHelper::ProgressCompleted(ICallback* localCback, BSTR& key)
{
	ICallback* callback = GetCurrent(localCback);
	if (!callback) return;

	CComBSTR bstrMsg("Completed");
	callback->Progress(key, 100, bstrMsg);
	callback->Progress(key, 0, m_globalSettings.emptyBstr);
}

// ********************************************************************
//		DisplayProgressCompleted()
// ********************************************************************
void CallbackHelper::ProgressCompleted(ICallback* localCback)
{
	ProgressCompleted(localCback, m_globalSettings.emptyBstr);
}

// ********************************************************************
//		DisplayErrorMsg()
// ********************************************************************
void CallbackHelper::ErrorMsg(CString className, ICallback* localCback, BSTR& key, const char* message, ...)
{
	ICallback* callback = GetCurrent(localCback);

	if (callback || Debug::IsDebugMode())
	{
		if (strcmp(message, "No Error") == 0) return;

		TCHAR buffer[1024];
		va_list args;
		va_start(args, message);
		vsprintf(buffer, message, args);
		CString s = buffer;

		s = className + ": " + s;
		CComBSTR bstr(s);

		if (callback) {
			callback->Error(key, bstr);
		}
		else {
			Debug::WriteError(s);
		}
	}
}
void CallbackHelper::ErrorMsg(CString className, ICallback* localCallback, CString key, const char* message, ...)
{
	if (localCallback || Debug::IsDebugMode())
	{
		CComBSTR bstrKey(key);
		ErrorMsg(className, localCallback, bstrKey.m_str, message);
	}
}

void CallbackHelper::ErrorMsg(const char* message)
{
	CString s = message;
	ErrorMsg(s);
}

void CallbackHelper::ErrorMsg(CString message)
{
	if (m_globalSettings.callback)
	{
		CComBSTR bstr(message);
		m_globalSettings.callback->Error(m_globalSettings.emptyBstr, bstr);
	}
	else {
		if (Debug::IsDebugMode())
			Debug::WriteError(message);
	}
}

// ****************************************************************
//		AssertionFailed
// ****************************************************************
void CallbackHelper::AssertionFailed(CString message)
{
	message = "Assertion failed: " + message;
	if (m_globalSettings.callback)
	{
		CComBSTR bstr(message);
		m_globalSettings.callback->Error(m_globalSettings.emptyBstr, bstr);
	}
	else {
		if (Debug::IsDebugMode())
			Debug::WriteError(message);
	}
}<commit_msg>A minor fix to enable callback notification from Utils.Polygonize.<commit_after>#include "stdafx.h"
#include "CallbackHelper.h"

// *****************************************************************
//	   GDALProgressCallback()
// *****************************************************************
int CPL_STDCALL GDALProgressCallback(double dfComplete, const char* pszMessage, void *pData)
{
	CallbackParams* params = (CallbackParams*)pData;

	// No need to check the presence of local callback,
	// global application callback can be used as a fallback.
	// There is no need to pass it as a parameter from each method.
	if (params != NULL)
	{
		long percent = long(dfComplete * 100.0);
		CallbackHelper::Progress(params->cBack, percent, params->sMsg);
	}
	return TRUE;
}

// ********************************************************************
//		DisplayProgress()
// ********************************************************************
void CallbackHelper::Progress(ICallback* localCback, int index, int count, const char* message, long& lastPercent)
{
	Progress(localCback, index, (double)count, message, m_globalSettings.emptyBstr, lastPercent);
}

void CallbackHelper::Progress(ICallback* localCback, int index, int count, const char* message, BSTR& key, long& lastPercent)
{
	Progress(localCback, index, (double)count, message, key, lastPercent);
}

// ********************************************************************
//		GetCurrent()
// ********************************************************************
ICallback* CallbackHelper::GetCurrent(ICallback* localCback)
{
	if (m_globalSettings.overrideLocalCallback)
	{
		return m_globalSettings.callback ? m_globalSettings.callback : localCback;
	}
	else
	{
		return localCback ? localCback : m_globalSettings.callback;
	}
}

// ********************************************************************
//		DisplayProgress()
// ********************************************************************
void CallbackHelper::Progress(ICallback* localCback, int index, double count, const char* message, BSTR& key, long& lastPercent)
{
	ICallback* callback = GetCurrent(localCback);
	if (!callback) return;

	long newpercent = (long)(((double)(index + 1) / count) * 100);
	if (newpercent > lastPercent)
	{
		lastPercent = newpercent;
		CComBSTR bstrMsg(message);
		callback->Progress(key, newpercent, bstrMsg);
	}
}

// ********************************************************************
//		DisplayProgress()
// ********************************************************************
void CallbackHelper::Progress(ICallback* localCback, int percent, const char* message, BSTR& key)
{
	ICallback* callback = GetCurrent(localCback);
	if (!callback) return;

	CComBSTR bstrMsg(message);
	callback->Progress(key, percent, bstrMsg);
}

// ********************************************************************
//		DisplayProgress()
// ********************************************************************
void CallbackHelper::Progress(ICallback* localCback, int percent, const char* message)
{
	ICallback* callback = GetCurrent(localCback);
	if (!callback) return;

	if (!message) message = "";
	CComBSTR bstrMsg(message);
	callback->Progress(m_globalSettings.emptyBstr, percent, bstrMsg);
}

// ********************************************************************
//		DisplayProgressCompleted()
// ********************************************************************
void CallbackHelper::ProgressCompleted(ICallback* localCback, BSTR& key)
{
	ICallback* callback = GetCurrent(localCback);
	if (!callback) return;

	CComBSTR bstrMsg("Completed");
	callback->Progress(key, 100, bstrMsg);
	callback->Progress(key, 0, m_globalSettings.emptyBstr);
}

// ********************************************************************
//		DisplayProgressCompleted()
// ********************************************************************
void CallbackHelper::ProgressCompleted(ICallback* localCback)
{
	ProgressCompleted(localCback, m_globalSettings.emptyBstr);
}

// ********************************************************************
//		DisplayErrorMsg()
// ********************************************************************
void CallbackHelper::ErrorMsg(CString className, ICallback* localCback, BSTR& key, const char* message, ...)
{
	ICallback* callback = GetCurrent(localCback);

	if (callback || Debug::IsDebugMode())
	{
		if (strcmp(message, "No Error") == 0) return;

		TCHAR buffer[1024];
		va_list args;
		va_start(args, message);
		vsprintf(buffer, message, args);
		CString s = buffer;

		s = className + ": " + s;
		CComBSTR bstr(s);

		if (callback) {
			callback->Error(key, bstr);
		}
		else {
			Debug::WriteError(s);
		}
	}
}
void CallbackHelper::ErrorMsg(CString className, ICallback* localCallback, CString key, const char* message, ...)
{
	if (localCallback || Debug::IsDebugMode())
	{
		CComBSTR bstrKey(key);
		ErrorMsg(className, localCallback, bstrKey.m_str, message);
	}
}

void CallbackHelper::ErrorMsg(const char* message)
{
	CString s = message;
	ErrorMsg(s);
}

void CallbackHelper::ErrorMsg(CString message)
{
	if (m_globalSettings.callback)
	{
		CComBSTR bstr(message);
		m_globalSettings.callback->Error(m_globalSettings.emptyBstr, bstr);
	}
	else {
		if (Debug::IsDebugMode())
			Debug::WriteError(message);
	}
}

// ****************************************************************
//		AssertionFailed
// ****************************************************************
void CallbackHelper::AssertionFailed(CString message)
{
	message = "Assertion failed: " + message;
	if (m_globalSettings.callback)
	{
		CComBSTR bstr(message);
		m_globalSettings.callback->Error(m_globalSettings.emptyBstr, bstr);
	}
	else {
		if (Debug::IsDebugMode())
			Debug::WriteError(message);
	}
}<|endoftext|>


<commit_before>/*    Copyright (c) 2010-2017, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#include "Tudat/SimulationSetup/PropagationSetup/propagationTermination.h"

namespace tudat
{

namespace propagators
{

//! Function to check whether the propagation is to be be stopped
bool FixedTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    bool stopPropagation = 0;

    // Check whether stop time has been reached
    if( propagationDirectionIsPositive_ && ( time >= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    else if( !propagationDirectionIsPositive_ && ( time <= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool FixedCPUTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    return cpuTime >= cpuStopTime_;
}

//! Function to check whether the propagation is to be be stopped
bool SingleVariableLimitPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime  )
{
    bool stopPropagation = 0;
    double currentVariable = variableRetrievalFuntion_( );
    if( useAsLowerBound_ && ( currentVariable < limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    else if( !useAsLowerBound_ && ( currentVariable > limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool HybridPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    // Check if single condition is fulfilled.
    bool stopPropagation = -1;
    if( fulFillSingleCondition_ )
    {
        stopPropagation = 0;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopPropagation = 1;
                break;
            }
        }
        return stopPropagation;
    }
    // Check all conditions are fulfilled.
    else
    {
        stopPropagation = 1;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( !propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopPropagation = 0;
                break;
            }
        }
    }

    // Save if conditions were met
    if( stopPropagation )
    {
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                isConditionMetWhenStopping_[ i ] = false;
            }
            else
            {
                isConditionMetWhenStopping_[ i ] = true;
            }
        }
    }

    return stopPropagation;

}

//! Function to create propagation termination conditions from associated settings
boost::shared_ptr< PropagationTerminationCondition > createPropagationTerminationConditions(
        const boost::shared_ptr< PropagationTerminationSettings > terminationSettings,
        const simulation_setup::NamedBodyMap& bodyMap,
        const double initialTimeStep )
{
    boost::shared_ptr< PropagationTerminationCondition > propagationTerminationCondition;

    // Check termination type.
    switch( terminationSettings->terminationType_ )
    {
    case time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationTimeTerminationSettings > timeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedTimePropagationTerminationCondition >(
                    timeTerminationSettings->terminationTime_, ( initialTimeStep > 0 ),
                    timeTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    case cpu_time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationCPUTimeTerminationSettings > cpuTimeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationCPUTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedCPUTimePropagationTerminationCondition >(
                    cpuTimeTerminationSettings->cpuTerminationTime_ );
        break;
    }
    case dependent_variable_stopping_condition:
    {
        boost::shared_ptr< PropagationDependentVariableTerminationSettings > dependentVariableTerminationSettings =
                boost::dynamic_pointer_cast< PropagationDependentVariableTerminationSettings >( terminationSettings );

        // Get dependent variable function
        boost::function< double( ) > dependentVariableFunction;
        if( getDependentVariableSaveSize( dependentVariableTerminationSettings->dependentVariableSettings_ ) == 1 )
        {
            dependentVariableFunction =
                    getDoubleDependentVariableFunction(
                        dependentVariableTerminationSettings->dependentVariableSettings_, bodyMap );
        }
        else
        {
            throw std::runtime_error( "Error, cannot make stopping condition from vector dependent variable" );
        }

        // Create dependent variable termination condition.
        propagationTerminationCondition = boost::make_shared< SingleVariableLimitPropagationTerminationCondition >(
                    dependentVariableTerminationSettings->dependentVariableSettings_,
                    dependentVariableFunction, dependentVariableTerminationSettings->limitValue_,
                    dependentVariableTerminationSettings->useAsLowerLimit_,
                    dependentVariableTerminationSettings->terminateExactlyOnFinalCondition_,
                    dependentVariableTerminationSettings->terminationRootFinderSettings_ );
        break;
    }
    case hybrid_stopping_condition:
    {
        boost::shared_ptr< PropagationHybridTerminationSettings > hybridTerminationSettings =
                boost::dynamic_pointer_cast< PropagationHybridTerminationSettings >( terminationSettings );

        // Recursively create termination condition list.
        std::vector< boost::shared_ptr< PropagationTerminationCondition > > propagationTerminationConditionList;
        for( unsigned int i = 0; i < hybridTerminationSettings->terminationSettings_.size( ); i++ )
        {
            propagationTerminationConditionList.push_back(
                        createPropagationTerminationConditions(
                            hybridTerminationSettings->terminationSettings_.at( i ),
                            bodyMap, initialTimeStep ) );
        }
        propagationTerminationCondition = boost::make_shared< HybridPropagationTerminationCondition >(
                    propagationTerminationConditionList, hybridTerminationSettings->fulFillSingleCondition_,
                    hybridTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    default:
        std::string errorMessage = "Error, stopping condition type " + std::to_string(
                    terminationSettings->terminationType_ ) + "not recognized when making stopping conditions object";
        throw std::runtime_error( errorMessage );
        break;
    }
    return propagationTerminationCondition;

} // namespace propagators

} // namespace tudat

}
<commit_msg>Fixed another small bug in accurate termination<commit_after>/*    Copyright (c) 2010-2017, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#include "Tudat/SimulationSetup/PropagationSetup/propagationTermination.h"

namespace tudat
{

namespace propagators
{

//! Function to check whether the propagation is to be be stopped
bool FixedTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    bool stopPropagation = 0;

    // Check whether stop time has been reached
    if( propagationDirectionIsPositive_ && ( time >= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    else if( !propagationDirectionIsPositive_ && ( time <= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool FixedCPUTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    return cpuTime >= cpuStopTime_;
}

//! Function to check whether the propagation is to be be stopped
bool SingleVariableLimitPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime  )
{
    bool stopPropagation = 0;
    double currentVariable = variableRetrievalFuntion_( );
    if( useAsLowerBound_ && ( currentVariable < limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    else if( !useAsLowerBound_ && ( currentVariable > limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool HybridPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    // Check if single condition is fulfilled.
    bool stopPropagation = -1;
    if( fulFillSingleCondition_ )
    {
        stopPropagation = 0;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopPropagation = 1;
                break;
            }
        }
    }
    // Check all conditions are fulfilled.
    else
    {
        stopPropagation = 1;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( !propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopPropagation = 0;
                break;
            }
        }
    }

    // Save if conditions were met
    if( stopPropagation )
    {
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                isConditionMetWhenStopping_[ i ] = false;
            }
            else
            {
                isConditionMetWhenStopping_[ i ] = true;
            }
        }
    }

    return stopPropagation;

}

//! Function to create propagation termination conditions from associated settings
boost::shared_ptr< PropagationTerminationCondition > createPropagationTerminationConditions(
        const boost::shared_ptr< PropagationTerminationSettings > terminationSettings,
        const simulation_setup::NamedBodyMap& bodyMap,
        const double initialTimeStep )
{
    boost::shared_ptr< PropagationTerminationCondition > propagationTerminationCondition;

    // Check termination type.
    switch( terminationSettings->terminationType_ )
    {
    case time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationTimeTerminationSettings > timeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedTimePropagationTerminationCondition >(
                    timeTerminationSettings->terminationTime_, ( initialTimeStep > 0 ),
                    timeTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    case cpu_time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationCPUTimeTerminationSettings > cpuTimeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationCPUTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedCPUTimePropagationTerminationCondition >(
                    cpuTimeTerminationSettings->cpuTerminationTime_ );
        break;
    }
    case dependent_variable_stopping_condition:
    {
        boost::shared_ptr< PropagationDependentVariableTerminationSettings > dependentVariableTerminationSettings =
                boost::dynamic_pointer_cast< PropagationDependentVariableTerminationSettings >( terminationSettings );

        // Get dependent variable function
        boost::function< double( ) > dependentVariableFunction;
        if( getDependentVariableSaveSize( dependentVariableTerminationSettings->dependentVariableSettings_ ) == 1 )
        {
            dependentVariableFunction =
                    getDoubleDependentVariableFunction(
                        dependentVariableTerminationSettings->dependentVariableSettings_, bodyMap );
        }
        else
        {
            throw std::runtime_error( "Error, cannot make stopping condition from vector dependent variable" );
        }

        // Create dependent variable termination condition.
        propagationTerminationCondition = boost::make_shared< SingleVariableLimitPropagationTerminationCondition >(
                    dependentVariableTerminationSettings->dependentVariableSettings_,
                    dependentVariableFunction, dependentVariableTerminationSettings->limitValue_,
                    dependentVariableTerminationSettings->useAsLowerLimit_,
                    dependentVariableTerminationSettings->terminateExactlyOnFinalCondition_,
                    dependentVariableTerminationSettings->terminationRootFinderSettings_ );
        break;
    }
    case hybrid_stopping_condition:
    {
        boost::shared_ptr< PropagationHybridTerminationSettings > hybridTerminationSettings =
                boost::dynamic_pointer_cast< PropagationHybridTerminationSettings >( terminationSettings );

        // Recursively create termination condition list.
        std::vector< boost::shared_ptr< PropagationTerminationCondition > > propagationTerminationConditionList;
        for( unsigned int i = 0; i < hybridTerminationSettings->terminationSettings_.size( ); i++ )
        {
            propagationTerminationConditionList.push_back(
                        createPropagationTerminationConditions(
                            hybridTerminationSettings->terminationSettings_.at( i ),
                            bodyMap, initialTimeStep ) );
        }
        propagationTerminationCondition = boost::make_shared< HybridPropagationTerminationCondition >(
                    propagationTerminationConditionList, hybridTerminationSettings->fulFillSingleCondition_,
                    hybridTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    default:
        std::string errorMessage = "Error, stopping condition type " + std::to_string(
                    terminationSettings->terminationType_ ) + "not recognized when making stopping conditions object";
        throw std::runtime_error( errorMessage );
        break;
    }
    return propagationTerminationCondition;

} // namespace propagators

} // namespace tudat

}
<|endoftext|>


<commit_before>//===-- lldb.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/lldb-private.h"

using namespace lldb;
using namespace lldb_private;

#include "clang/Basic/Version.h"

#ifdef HAVE_SVN_VERSION_INC
#  include "SVNVersion.inc"
#endif

#ifdef HAVE_APPLE_VERSION_INC
#  include "AppleVersion.inc"
#endif

static const char *GetLLDBRevision() {
#ifdef LLDB_REVISION
  return LLDB_REVISION;
#else
  return NULL;
#endif
}

static const char *GetLLDBRepository() {
#ifdef LLDB_REPOSITORY
  return LLDB_REPOSITORY;
#else
  return NULL;
#endif
}

#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)

const char *lldb_private::GetVersion() {
  // On platforms other than Darwin, report a version number in the same style
  // as the clang tool.
  static std::string g_version_str;
  if (g_version_str.empty()) {
    g_version_str += "lldb version ";
    g_version_str += CLANG_VERSION_STRING;

    const char *lldb_repo = GetLLDBRepository();
    const char *lldb_rev = GetLLDBRevision();
    if (lldb_repo || lldb_rev) {
      g_version_str += " (";
      if (lldb_repo)
        g_version_str += lldb_repo;
      if (lldb_rev) {
        g_version_str += " revision ";
        g_version_str += lldb_rev;
      }
      g_version_str += ")";
    }

    std::string clang_rev(clang::getClangRevision());
    if (clang_rev.length() > 0) {
      g_version_str += "\n  clang revision ";
      g_version_str += clang_rev;
    }
    std::string llvm_rev(clang::getLLVMRevision());
    if (llvm_rev.length() > 0) {
      g_version_str += "\n  llvm revision ";
      g_version_str += llvm_rev;
    }

  }
  return g_version_str.c_str();
}
<commit_msg>Run clang-format on lldb.cpp<commit_after>//===-- lldb.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/lldb-private.h"

using namespace lldb;
using namespace lldb_private;

#include "clang/Basic/Version.h"

#ifdef HAVE_SVN_VERSION_INC
#include "SVNVersion.inc"
#endif

#ifdef HAVE_APPLE_VERSION_INC
#include "AppleVersion.inc"
#endif

static const char *GetLLDBRevision() {
#ifdef LLDB_REVISION
  return LLDB_REVISION;
#else
  return NULL;
#endif
}

static const char *GetLLDBRepository() {
#ifdef LLDB_REPOSITORY
  return LLDB_REPOSITORY;
#else
  return NULL;
#endif
}

#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)

const char *lldb_private::GetVersion() {
  // On platforms other than Darwin, report a version number in the same style
  // as the clang tool.
  static std::string g_version_str;
  if (g_version_str.empty()) {
    g_version_str += "lldb version ";
    g_version_str += CLANG_VERSION_STRING;

    const char *lldb_repo = GetLLDBRepository();
    const char *lldb_rev = GetLLDBRevision();
    if (lldb_repo || lldb_rev) {
      g_version_str += " (";
      if (lldb_repo)
        g_version_str += lldb_repo;
      if (lldb_rev) {
        g_version_str += " revision ";
        g_version_str += lldb_rev;
      }
      g_version_str += ")";
    }

    std::string clang_rev(clang::getClangRevision());
    if (clang_rev.length() > 0) {
      g_version_str += "\n  clang revision ";
      g_version_str += clang_rev;
    }
    std::string llvm_rev(clang::getLLVMRevision());
    if (llvm_rev.length() > 0) {
      g_version_str += "\n  llvm revision ";
      g_version_str += llvm_rev;
    }
  }
  return g_version_str.c_str();
}
<|endoftext|>


<commit_before>//
//
//  Created by Steven Massey on 4/15/19.
//  Copyright © 2019 Steven Massey. All rights reserved.
//

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

#include "m3.hpp"

#include <time.h>

extern "C"
{
#	include "m3_core.h"
}

#include "m3_host.h"

void  m3Output  (const char * i_string)
{
	printf ("%s\n", i_string);
}

int  main  (int i_argc, const char * i_argv [])
{
	M3Result result = c_m3Err_none;

	m3_PrintM3Info ();

	if (i_argc >= 2)
	{
		FILE * f = fopen (i_argv [1], "rb");

		if (f)
		{
			fseek (f, 0, SEEK_END);
			size_t fsize = ftell (f);
			fseek (f, 0, SEEK_SET);

			if (fsize < 100000)
			{
				u8 * wasm = (u8 *) malloc (fsize);

				if (wasm)
				{
					IM3Runtime env = nullptr;

					try
					{
						fread (wasm, 1, fsize, f);
						fclose (f);

						IM3Module module;
						result = m3_ParseModule (& module, wasm, (u32) fsize); if (result) throw result;

						env = m3_NewRuntime (32768);

						result = m3_LoadModule (env, module); if (result) throw result;

						m3_LinkFunction (module, "_m3TestOut", "v(iFi)", (void *) m3TestOut);
						m3_LinkFunction (module, "_m3StdOut", "v(*)", (void *) m3Output);
						m3_LinkFunction (module, "_m3Export", "v(*i)", (void *) m3Export);
						m3_LinkFunction (module, "_m3Out_f64", "v(F)", (void *) m3Out_f64);
						m3_LinkFunction (module, "_m3Out_i32", "v(i)", (void *) m3Out_i32);
						m3_LinkFunction (module, "_TestReturn", "F(i)", (void *) TestReturn);

						m3_LinkFunction (module, "abortStackOverflow",	"v(i)",		(void *) m3_abort);

						result = m3_LinkCStd (module); if (result) throw result;

						m3_PrintRuntimeInfo (env);

						IM3Function f;
						result = m3_FindFunction (& f, env, "__post_instantiate"); //if (result) throw result;

						if (not result)
						{
							result = m3_Call (f); if (result) throw result;
						}

						IM3Function main;
						result = m3_FindFunction (& main, env, "_main"); if (result) throw result;

						if (main)
						{
							printf ("found _main\n");

							clock_t start = clock ();

//							result = m3_Call (main);

							if (i_argc)
							{
								--i_argc;
								++i_argv;
							}

							result = m3_CallWithArgs (main, i_argc, i_argv);

							clock_t end = clock ();
							double elapsed_time = (end - start) / (double) CLOCKS_PER_SEC ;
							printf("%lf\n", elapsed_time);

//							printf ("call: %s\n", result);

							m3_PrintProfilerInfo ();
						}

					}

					catch (const M3Result & r) {}

					if (result)
					{
						printf ("result: %s", result);

						if (env)
						{
							M3ErrorInfo info = m3_GetErrorInfo (env);
							printf (" (%s)", info.message);
						}

						printf ("\n");
					}

					m3_FreeRuntime (env);
				}

				free (wasm);
			}
		}
		else printf ("couldn't open '%s'\n", i_argv [1]);
	}

	printf ("\n");

	return 0;
}
<commit_msg>Allow running arbitrary exported function<commit_after>//
//
//  Created by Steven Massey on 4/15/19.
//  Copyright © 2019 Steven Massey. All rights reserved.
//

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

#include "m3.hpp"

#include <time.h>

extern "C"
{
#	include "m3_core.h"
}

#include "m3_host.h"

void  m3Output  (const char * i_string)
{
	printf ("%s\n", i_string);
}

int  main  (int i_argc, const char * i_argv [])
{
	M3Result result = c_m3Err_none;

	if (i_argc >= 2)
	{
		FILE * f = fopen (i_argv [1], "rb");

		if (f)
		{
			fseek (f, 0, SEEK_END);
			size_t fsize = ftell (f);
			fseek (f, 0, SEEK_SET);

			if (fsize < 100000)
			{
				u8 * wasm = (u8 *) malloc (fsize);

				if (wasm)
				{
					IM3Runtime env = nullptr;

					try
					{
						fread (wasm, 1, fsize, f);
						fclose (f);

						IM3Module module;
						result = m3_ParseModule (& module, wasm, (u32) fsize); if (result) throw result;

						env = m3_NewRuntime (32768);

						result = m3_LoadModule (env, module); if (result) throw result;

						m3_LinkFunction (module, "_m3TestOut", "v(iFi)", (void *) m3TestOut);
						m3_LinkFunction (module, "_m3StdOut", "v(*)", (void *) m3Output);
						m3_LinkFunction (module, "_m3Export", "v(*i)", (void *) m3Export);
						m3_LinkFunction (module, "_m3Out_f64", "v(F)", (void *) m3Out_f64);
						m3_LinkFunction (module, "_m3Out_i32", "v(i)", (void *) m3Out_i32);
						m3_LinkFunction (module, "_TestReturn", "F(i)", (void *) TestReturn);

						m3_LinkFunction (module, "abortStackOverflow",	"v(i)",		(void *) m3_abort);

						result = m3_LinkCStd (module); if (result) throw result;

						m3_PrintRuntimeInfo (env);

						IM3Function f;
						result = m3_FindFunction (& f, env, "__post_instantiate"); //if (result) throw result;

						if (not result)
						{
							result = m3_Call (f); if (result) throw result;
						}

						IM3Function main;
						result = m3_FindFunction (& main, env, i_argv[2]); if (result) throw result;

						if (main)
						{
							printf ("found %s\n", i_argv[2]);

							clock_t start = clock ();

//							result = m3_Call (main);

							if (i_argc)
							{
								i_argc -= 2;
								i_argv += 2;
							}

							result = m3_CallWithArgs (main, i_argc, i_argv);

							clock_t end = clock ();
							double elapsed_time = (end - start) / (double) CLOCKS_PER_SEC ;
							printf("Time: %.3lf s\n", elapsed_time);

//							printf ("call: %s\n", result);

							m3_PrintProfilerInfo ();
						}

					}

					catch (const M3Result & r) {}

					if (result)
					{
						printf ("result: %s", result);

						if (env)
						{
							M3ErrorInfo info = m3_GetErrorInfo (env);
							printf (" (%s)", info.message);
						}

						printf ("\n");
                        return 1;
					}

					m3_FreeRuntime (env);
				}

				free (wasm);
			}
		}
		else printf ("couldn't open '%s'\n", i_argv [1]);
	} else printf ("not enough arguments\n");

	printf ("\n");

	return 0;
}
<|endoftext|>


<commit_before>#include <ctrcommon/app.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include <stdio.h>

#include <sstream>
#include <iomanip>

#include <sys/dirent.h>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE,
    LAUNCH_TITLE
} Mode;

int main(int argc, char **argv) {
    if(!platformInit()) {
        return 0;
    }

    bool ninjhax = platformIsNinjhax();

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool netInstall = false;
    u64 freeSpace = fsGetFreeSpace(destination);
    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else if(mode == DELETE_TITLE) {
                mode = LAUNCH_TITLE;
            } else if(mode == LAUNCH_TITLE) {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "FBI v1.3.4" << "\n";
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
            stream << "Y - Receive an app over the network" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        if(ninjhax) {
            stream << "START - Exit to launcher" << "\n";
        }

        std::string str = stream.str();
        screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);

        return breakLoop;
    };

    std::string batchInfo = "";

    auto onProgress = [&](u64 pos, u64 totalSize) {
        std::stringstream details;
        details << batchInfo;
        details << "(" << pos << " / " << totalSize << ")" << "\n";
        details << "Press B to cancel.";

        uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, (u32) ((pos * 100) / totalSize));
        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    while(platformIsRunning()) {
        std::string fileTarget;
        App appTarget;
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            if(netInstall && !exit) {
                screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);

                RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
                if(file.fd == NULL) {
                    netInstall = false;
                    continue;
                }

                std::stringstream confirmStream;
                confirmStream << "Install the received application?" << "\n";
                confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
                if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                    AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                    std::stringstream resultMsg;
                    resultMsg << "Install ";
                    if(ret == APP_SUCCESS) {
                        resultMsg << "succeeded!";
                    } else {
                        resultMsg << "failed!" << "\n";
                        resultMsg << appGetResultString(ret) << "\n";
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                }

                fclose(file.fd);
                continue;
            }

            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        u32 currItem = 0;
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            std::string fileName = (*it).name;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                if(mode == INSTALL_CIA) {
                                    std::stringstream batchInstallStream;
                                    batchInstallStream << fileName << " (" << currItem << ")" << "\n";

                                    batchInfo = batchInstallStream.str();
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    batchInfo = "";
                                    if(ret != APP_SUCCESS) {
                                        Error error = platformGetError();
                                        platformSetError(error);

                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << appGetResultString(ret) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        if(error.module != MODULE_AM || error.description != DESCRIPTION_ALREADY_EXISTS) {
                                            failed = true;
                                            break;
                                        }
                                    }
                                } else {
                                    std::stringstream deleteStream;
                                    deleteStream << "Deleting CIA..." << "\n";
                                    deleteStream << fileName << " (" << currItem << ")" << "\n";

                                    uiDisplayMessage(TOP_SCREEN, deleteStream.str());
                                    if(!fsDelete(path)) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << platformGetErrorString(platformGetError()) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }

                            currItem++;
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        AppResult ret = appInstallFile(destination, path, onProgress);
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }
                    } else {
                        uiDisplayMessage(TOP_SCREEN, "Deleting CIA...");
                        if(fsDelete(path)) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError()) << "\n";
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
            uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(mode == DELETE_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                        AppResult ret = appDelete(app);

                        std::stringstream resultMsg;
                        resultMsg << "Delete ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                        freeSpace = fsGetFreeSpace(destination);
                    }
                } else if(mode == LAUNCH_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Launching title...");
                        AppResult ret = appLaunch(app);

                        if(ret != APP_SUCCESS) {
                            std::stringstream resultMsg;
                            resultMsg << "Launch failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                            uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                        } else {
                            while(true) {
                            }
                        }
                    }
                }

                return false;
            });
        }

        if(exit) {
            break;
        }
    }

    platformCleanup();
    return 0;
}
<commit_msg>Add option to disable prompts when installing over the network.<commit_after>#include <ctrcommon/app.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include <stdio.h>

#include <sstream>
#include <iomanip>

#include <sys/dirent.h>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE,
    LAUNCH_TITLE
} Mode;

int main(int argc, char **argv) {
    if(!platformInit()) {
        return 0;
    }

    bool ninjhax = platformIsNinjhax();

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool netInstall = false;
    u64 freeSpace = fsGetFreeSpace(destination);
    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else if(mode == DELETE_TITLE) {
                mode = LAUNCH_TITLE;
            } else if(mode == LAUNCH_TITLE) {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "FBI v1.3.5" << "\n";
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
            stream << "Y - Receive an app over the network" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        if(ninjhax) {
            stream << "START - Exit to launcher" << "\n";
        }

        std::string str = stream.str();
        screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);

        return breakLoop;
    };

    std::string batchInfo = "";

    auto onProgress = [&](u64 pos, u64 totalSize) {
        std::stringstream details;
        details << batchInfo;
        details << "(" << pos << " / " << totalSize << ")" << "\n";
        details << "Press B to cancel.";

        uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, (u32) ((pos * 100) / totalSize));
        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    bool showNetworkPrompts = true;

    while(platformIsRunning()) {
        std::string fileTarget;
        App appTarget;
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            if(netInstall && !exit) {
                screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);

                RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
                    if(inputIsPressed(BUTTON_A)) {
                        showNetworkPrompts = !showNetworkPrompts;
                    }

                    infoStream << "\n";
                    infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
                    infoStream << "Press A to toggle prompts." << "\n";
                });

                if(file.fd == NULL) {
                    netInstall = false;
                    continue;
                }

                std::stringstream confirmStream;
                confirmStream << "Install the received application?" << "\n";
                confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
                if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                    AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                    if(showNetworkPrompts || ret != APP_SUCCESS) {
                        std::stringstream resultMsg;
                        resultMsg << "Install ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                    }
                }

                fclose(file.fd);
                continue;
            }

            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        u32 currItem = 0;
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            std::string fileName = (*it).name;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                if(mode == INSTALL_CIA) {
                                    std::stringstream batchInstallStream;
                                    batchInstallStream << fileName << " (" << currItem << ")" << "\n";

                                    batchInfo = batchInstallStream.str();
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    batchInfo = "";
                                    if(ret != APP_SUCCESS) {
                                        Error error = platformGetError();
                                        platformSetError(error);

                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << appGetResultString(ret) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        if(error.module != MODULE_AM || error.description != DESCRIPTION_ALREADY_EXISTS) {
                                            failed = true;
                                            break;
                                        }
                                    }
                                } else {
                                    std::stringstream deleteStream;
                                    deleteStream << "Deleting CIA..." << "\n";
                                    deleteStream << fileName << " (" << currItem << ")" << "\n";

                                    uiDisplayMessage(TOP_SCREEN, deleteStream.str());
                                    if(!fsDelete(path)) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << platformGetErrorString(platformGetError()) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }

                            currItem++;
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        AppResult ret = appInstallFile(destination, path, onProgress);
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }
                    } else {
                        uiDisplayMessage(TOP_SCREEN, "Deleting CIA...");
                        if(fsDelete(path)) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError()) << "\n";
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
            uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(mode == DELETE_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                        AppResult ret = appDelete(app);

                        std::stringstream resultMsg;
                        resultMsg << "Delete ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                        freeSpace = fsGetFreeSpace(destination);
                    }
                } else if(mode == LAUNCH_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Launching title...");
                        AppResult ret = appLaunch(app);

                        if(ret != APP_SUCCESS) {
                            std::stringstream resultMsg;
                            resultMsg << "Launch failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                            uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                        } else {
                            while(true) {
                            }
                        }
                    }
                }

                return false;
            });
        }

        if(exit) {
            break;
        }
    }

    platformCleanup();
    return 0;
}
<|endoftext|>


<commit_before>#include <type_traits>

#define GLM_FORCE_RADIANS

#include <glow/VertexArrayObject.h>
#include <glow/Error.h>
#include <glow/StaticStringSource.h>
#include <glow/Program.h>
#include <glow/Buffer.h>
#include <glow/VertexAttributeBinding.h>

#include <glowutils/StringTemplate.h>

#include <glowwindow/Context.h>
#include <glowwindow/ContextFormat.h>
#include <glowwindow/MainLoop.h>
#include <glowwindow/Window.h>
#include <glowwindow/WindowEventHandler.h>
#include <glowwindow/events.h>

#include <GL/glx.h>

namespace {
    const char* vertexShaderCode = R"(
#version 140
#extension GL_ARB_explicit_attrib_location : require

layout (location = 0) in vec2 corner;

out vec4 color;

void main()
{
    gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0);
    color = vec4(corner, 0.0, 1.0);
}

)";
    const char* fragmentShaderCode = R"(
#version 140
#extension GL_ARB_explicit_attrib_location : require

layout (location = 0) out vec4 fragColor;

in vec4 color;

void main()
{
    fragColor = color;
}

)";
}

namespace {
    __GLXextFuncPtr (*glowGetProcAddress) (const GLubyte*) = glXGetProcAddressARB;

    GLenum (*glowGetError) (void);

    inline void CheckGlowError()
    {
        assert(glowGetError() == GL_NO_ERROR);
    }

    template <typename ReturnType, typename... Arguments>
    class GlowFunction
    {
    public:
        using FunctionSignature = ReturnType (*) (Arguments...);

        GlowFunction()
        : m_valid(false)
        {
        }

        GlowFunction(FunctionSignature functionPointer)
        : m_functionPointer(functionPointer)
        , m_valid(true)
        {
        }

        void setFunction(FunctionSignature functionPointer)
        {
            m_valid = true;

            m_functionPointer = functionPointer;
        }

        ReturnType operator()(Arguments... arguments)
        {
            assert(m_valid);

            ReturnType returnValue = m_functionPointer(std::forward<Arguments>(arguments)...);
            CheckGlowError();

            return returnValue;
        }
    protected:
        FunctionSignature m_functionPointer;
        bool m_valid;
    };

    template <typename... Arguments>
    class GlowFunction<void, Arguments...>
    {
    public:
        using FunctionSignature = void (*) (Arguments...);

        GlowFunction()
        : m_valid(false)
        {
        }

        GlowFunction(FunctionSignature functionPointer)
        : m_functionPointer(functionPointer)
        , m_valid(true)
        {
        }

        void setFunction(FunctionSignature functionPointer)
        {
            m_valid = true;

            m_functionPointer = functionPointer;
        }

        void operator()(Arguments... arguments)
        {
            assert(m_valid);

            m_functionPointer(std::forward<Arguments>(arguments)...);
            CheckGlowError();
        }
    protected:
        FunctionSignature m_functionPointer;
        bool m_valid;
    };

    template <typename ReturnType, typename... Arguments>
    void initializeCheckedGlowFunction(const char* name, GlowFunction<ReturnType, Arguments...> & functor)
    {
        functor.setFunction(
            reinterpret_cast<typename GlowFunction<ReturnType, Arguments...>::FunctionSignature>(
                glowGetProcAddress(reinterpret_cast<const GLubyte*>(name))
            )
        );
    }

    template <typename FunctionSignature>
    void initializeGlowFunction(const char* name, FunctionSignature & functionPointer)
    {
        functionPointer = reinterpret_cast<FunctionSignature>(glowGetProcAddress(reinterpret_cast<const GLubyte*>(name)));
    }

    GlowFunction<void, GLbitfield> glowClear;
    GlowFunction<void, GLfloat, GLfloat, GLfloat, GLfloat> glowClearColor;
    GlowFunction<void, GLsizei, GLuint*> glowGenBuffers;
    GlowFunction<void, GLsizei, GLuint*> glowDeleteBuffers;
}

class EventHandler : public glowwindow::WindowEventHandler
{
public:
    EventHandler()
    {
    }

    virtual ~EventHandler()
    {
        cornerBuffer->unref();
        program->unref();
        vao->unref();

        glowDeleteBuffers(1, &m_cornerBuffer);
        CheckGlowError();
    }

    virtual void initialize(glowwindow::Window &) override
    {
        initializeGlowFunction("glGetError", glowGetError);
        initializeCheckedGlowFunction("glClear", glowClear);
        initializeCheckedGlowFunction("glClearColor", glowClearColor);
        initializeCheckedGlowFunction("glGenBuffers", glowGenBuffers);
        initializeCheckedGlowFunction("glDeleteBuffers", glowDeleteBuffers);

        glowClearColor(0.2f, 0.3f, 0.4f, 1.f);
        CheckGlowError();

        auto vertexShaderSource = new glow::StaticStringSource(vertexShaderCode);
        auto fragmentShaderSource = new glow::StaticStringSource(fragmentShaderCode);

        glowGenBuffers(1, &m_cornerBuffer);
        CheckGlowError();

        cornerBuffer = glow::Buffer::fromId(m_cornerBuffer, false);
        cornerBuffer->ref();
        program = new glow::Program();
        program->ref();
        vao = new glow::VertexArrayObject();
        vao->ref();

        program->attach(
                        new glow::Shader(GL_VERTEX_SHADER, vertexShaderSource),
                        new glow::Shader(GL_FRAGMENT_SHADER, fragmentShaderSource)
                        );

        cornerBuffer->setData(std::array<glm::vec2, 4>{ {
            glm::vec2(0, 0),
            glm::vec2(1, 0),
            glm::vec2(0, 1),
            glm::vec2(1, 1)
        } });

        vao->binding(0)->setAttribute(0);
        vao->binding(0)->setBuffer(cornerBuffer, 0, sizeof(glm::vec2));
        vao->binding(0)->setFormat(2, GL_FLOAT);
        vao->enable(0);
    }

    virtual void framebufferResizeEvent(glowwindow::ResizeEvent & event) override
    {
        glViewport(0, 0, event.width(), event.height());
        CheckGlowError();
    }

    virtual void paintEvent(glowwindow::PaintEvent &) override
    {
        glowClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        CheckGlowError();

        program->use();
        vao->drawArrays(GL_TRIANGLE_STRIP, 0, 4);
    }

    virtual void idle(glowwindow::Window & /*window*/) override
    {
        //window.repaint();
    }

private:
    GLuint m_vao;
    GLuint m_cornerBuffer;
    GLuint m_program;
    glow::VertexArrayObject* vao;
    glow::Buffer* cornerBuffer;
    glow::Program* program;
};

int main(int /*argc*/, char* /*argv*/[])
{
    glowwindow::ContextFormat format;
    format.setVersion(3, 0);

    glowwindow::Window window;

    window.setEventHandler(new EventHandler());

    if (window.create(format, "GLBindings Example"))
    {
        window.context()->setSwapInterval(glowwindow::Context::VerticalSyncronization);

        window.show();

        return glowwindow::MainLoop::run();
    }
    else
    {
        return 1;
    }
}
<commit_msg>Remove glow::Program from example code<commit_after>#include <type_traits>

#define GLM_FORCE_RADIANS

#include <glow/VertexArrayObject.h>
#include <glow/Error.h>
#include <glow/StaticStringSource.h>
#include <glow/Program.h>
#include <glow/Buffer.h>
#include <glow/VertexAttributeBinding.h>

#include <glowutils/StringTemplate.h>

#include <glowwindow/Context.h>
#include <glowwindow/ContextFormat.h>
#include <glowwindow/MainLoop.h>
#include <glowwindow/Window.h>
#include <glowwindow/WindowEventHandler.h>
#include <glowwindow/events.h>

#include <GL/glx.h>

namespace {
    const char* vertexShaderCode = R"(
#version 140
#extension GL_ARB_explicit_attrib_location : require

layout (location = 0) in vec2 corner;

out vec4 color;

void main()
{
    gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0);
    color = vec4(corner, 0.0, 1.0);
}

)";
    const char* fragmentShaderCode = R"(
#version 140
#extension GL_ARB_explicit_attrib_location : require

layout (location = 0) out vec4 fragColor;

in vec4 color;

void main()
{
    fragColor = color;
}

)";
}

namespace {
    __GLXextFuncPtr (*glowGetProcAddress) (const GLubyte*) = glXGetProcAddressARB;

    GLenum (*glowGetError) (void);

    inline void CheckGlowError()
    {
        assert(glowGetError() == GL_NO_ERROR);
    }

    template <typename ReturnType, typename... Arguments>
    class GlowFunction
    {
    public:
        using FunctionSignature = ReturnType (*) (Arguments...);

        GlowFunction()
        : m_valid(false)
        {
        }

        GlowFunction(FunctionSignature functionPointer)
        : m_functionPointer(functionPointer)
        , m_valid(true)
        {
        }

        void setFunction(FunctionSignature functionPointer)
        {
            m_valid = true;

            m_functionPointer = functionPointer;
        }

        ReturnType operator()(Arguments... arguments)
        {
            assert(m_valid);

            ReturnType returnValue = m_functionPointer(std::forward<Arguments>(arguments)...);
            CheckGlowError();

            return returnValue;
        }
    protected:
        FunctionSignature m_functionPointer;
        bool m_valid;
    };

    template <typename... Arguments>
    class GlowFunction<void, Arguments...>
    {
    public:
        using FunctionSignature = void (*) (Arguments...);

        GlowFunction()
        : m_valid(false)
        {
        }

        GlowFunction(FunctionSignature functionPointer)
        : m_functionPointer(functionPointer)
        , m_valid(true)
        {
        }

        void setFunction(FunctionSignature functionPointer)
        {
            m_valid = true;

            m_functionPointer = functionPointer;
        }

        void operator()(Arguments... arguments)
        {
            assert(m_valid);

            m_functionPointer(std::forward<Arguments>(arguments)...);
            CheckGlowError();
        }
    protected:
        FunctionSignature m_functionPointer;
        bool m_valid;
    };

    template <typename ReturnType, typename... Arguments>
    void initializeGlowFunction(const char* name, GlowFunction<ReturnType, Arguments...> & functor)
    {
        functor.setFunction(
            reinterpret_cast<typename GlowFunction<ReturnType, Arguments...>::FunctionSignature>(
                glowGetProcAddress(reinterpret_cast<const GLubyte*>(name))
            )
        );
    }

    template <typename FunctionSignature>
    void initializeGlowFunction(const char* name, FunctionSignature & functionPointer)
    {
        functionPointer = reinterpret_cast<FunctionSignature>(glowGetProcAddress(reinterpret_cast<const GLubyte*>(name)));
    }

    GlowFunction<void, GLbitfield> glowClear;
    GlowFunction<void, GLfloat, GLfloat, GLfloat, GLfloat> glowClearColor;
    GlowFunction<void, GLsizei, GLuint*> glowGenBuffers;
    GlowFunction<void, GLsizei, GLuint*> glowDeleteBuffers;
    GlowFunction<void, GLint, GLint, GLsizei, GLsizei> glowViewport;
    GlowFunction<void, GLuint> glowBindVertexArray;
    GlowFunction<void, GLuint> glowUseProgram;
    GlowFunction<void, GLenum, GLint, GLsizei> glowDrawArrays;
    GlowFunction<GLuint> glowCreateProgram;
    GlowFunction<void, GLuint> glowDeleteProgram;
    GlowFunction<void, GLsizei, GLuint*> glowGenVertexArrays;
    GlowFunction<void, GLsizei, GLuint*> glowDeleteVertexArrays;
    GlowFunction<void, GLuint> glowLinkProgram;
    GlowFunction<void, GLuint> glowCompileShader;
    GlowFunction<void, GLuint, GLuint> glowAttachShader;
}

class EventHandler : public glowwindow::WindowEventHandler
{
public:
    EventHandler()
    {
    }

    virtual ~EventHandler()
    {
        glowDeleteBuffers(1, &m_cornerBuffer);
        glowDeleteProgram(m_program);
        glowDeleteVertexArrays(1, &m_vao);
    }

    virtual void initialize(glowwindow::Window &) override
    {
        initializeGlowFunction("glGetError", glowGetError);
        initializeGlowFunction("glClear", glowClear);
        initializeGlowFunction("glClearColor", glowClearColor);
        initializeGlowFunction("glGenBuffers", glowGenBuffers);
        initializeGlowFunction("glDeleteBuffers", glowDeleteBuffers);
        initializeGlowFunction("glViewport", glowViewport);
        initializeGlowFunction("glBindVertexArray", glowBindVertexArray);
        initializeGlowFunction("glUseProgram", glowUseProgram);
        initializeGlowFunction("glDrawArrays", glowDrawArrays);
        initializeGlowFunction("glCreateProgram", glowCreateProgram);
        initializeGlowFunction("glDeleteProgram", glowDeleteProgram);
        initializeGlowFunction("glGenVertexArrays", glowGenVertexArrays);
        initializeGlowFunction("glDeleteVertexArrays", glowDeleteVertexArrays);
        initializeGlowFunction("glLinkProgram", glowLinkProgram);
        initializeGlowFunction("glCompileShader", glowCompileShader);
        initializeGlowFunction("glAttachShader", glowAttachShader);

        glowClearColor(0.2f, 0.3f, 0.4f, 1.f);

        auto vertexShaderSource = new glow::StaticStringSource(vertexShaderCode);
        auto fragmentShaderSource = new glow::StaticStringSource(fragmentShaderCode);

        glowGenBuffers(1, &m_cornerBuffer);
        m_program = glowCreateProgram();
        glowGenVertexArrays(1, &m_vao);

        cornerBuffer = glow::Buffer::fromId(m_cornerBuffer, false);
        cornerBuffer->ref();
        vao = glow::VertexArrayObject::fromId(m_vao, false);
        vao->ref();

        glow::Shader* vertexShader = new glow::Shader(GL_VERTEX_SHADER, vertexShaderSource);
        vertexShader->ref();
        glow::Shader* fragmentShader = new glow::Shader(GL_FRAGMENT_SHADER, fragmentShaderSource);
        fragmentShader->ref();

        m_vertexShader = vertexShader->id();
        m_fragmentShader = fragmentShader->id();

        cornerBuffer->setData(std::array<glm::vec2, 4>{ {
            glm::vec2(0, 0),
            glm::vec2(1, 0),
            glm::vec2(0, 1),
            glm::vec2(1, 1)
        } });

        vao->binding(0)->setAttribute(0);
        vao->binding(0)->setBuffer(cornerBuffer, 0, sizeof(glm::vec2));
        vao->binding(0)->setFormat(2, GL_FLOAT);
        vao->enable(0);

        glowCompileShader(m_vertexShader);
        glowCompileShader(m_fragmentShader);

        glowAttachShader(m_program, m_vertexShader);
        glowAttachShader(m_program, m_fragmentShader);

        glowLinkProgram(m_program);
    }

    virtual void framebufferResizeEvent(glowwindow::ResizeEvent & event) override
    {
        glowViewport(0, 0, event.width(), event.height());
    }

    virtual void paintEvent(glowwindow::PaintEvent &) override
    {
        glowClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glowBindVertexArray(vao->id());
        glowUseProgram(m_program);
        glowDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        glowUseProgram(0);
        glowBindVertexArray(0);
    }

    virtual void idle(glowwindow::Window & /*window*/) override
    {
        //window.repaint();
    }

private:
    GLuint m_vao;
    GLuint m_cornerBuffer;
    GLuint m_program;
    GLuint m_vertexShader;
    GLuint m_fragmentShader;
    glow::VertexArrayObject* vao;
    glow::Buffer* cornerBuffer;
};

int main(int /*argc*/, char* /*argv*/[])
{
    glowwindow::ContextFormat format;
    format.setVersion(3, 0);

    glowwindow::Window window;

    window.setEventHandler(new EventHandler());

    if (window.create(format, "GLBindings Example"))
    {
        window.context()->setSwapInterval(glowwindow::Context::VerticalSyncronization);

        window.show();

        return glowwindow::MainLoop::run();
    }
    else
    {
        return 1;
    }
}
<|endoftext|>


<commit_before>
#include <QSurfaceFormat>
#include <QWidget>

#include "Application.h"

#include "Viewer.h"
#include "Canvas.h"

#include "Painter.h"

int main(int argc, char* argv[])
{
    int result = -1;

    Application app(argc, argv);

    {
        QScopedPointer<Viewer> viewer(new Viewer());

        QSurfaceFormat format;
#ifdef NO_OPENGL_320
        format.setVersion(3, 0);
#else
        format.setVersion(3, 2);
        format.setProfile(QSurfaceFormat::CoreProfile);
#endif
        Canvas * canvas = new Canvas(format);
        canvas->setContinuousRepaint(true, 0);
        canvas->setSwapInterval(Canvas::VerticalSyncronization);

        QObject::connect(canvas, &Canvas::fpsUpdate, viewer.data(), &Viewer::fpsChanged);
        QObject::connect(canvas, &Canvas::objUpdate, viewer.data(), &Viewer::objChanged);
        QObject::connect(canvas, &Canvas::timeUpdate, viewer.data(), &Viewer::timeChanged);
        QObject::connect(canvas, &Canvas::mouseUpdate, viewer.data(), &Viewer::mouseChanged);
        QObject::connect(viewer.data(), &Viewer::toggleSwapInterval, canvas, &Canvas::toggleSwapInterval);

        Painter painter;
        canvas->assignPainter(&painter);

        QWidget * widget = QWidget::createWindowContainer(canvas);
        widget->setMinimumSize(1, 1);
        widget->setAutoFillBackground(false); // Important for overdraw, not occluding the scene.
        widget->setFocusPolicy(Qt::TabFocus);

        viewer->setCentralWidget(widget);
        viewer->show();

        result = app.exec();
        canvas->assignPainter(nullptr);

    }
    return result;
}<commit_msg>Add comment indicating a bug<commit_after>
#include <QSurfaceFormat>
#include <QWidget>

#include "Application.h"
#include "Viewer.h"
#include "Canvas.h"
#include "Painter.h"

int main(int argc, char* argv[])
{
    int result = -1;

    Application app(argc, argv);

    QScopedPointer<Viewer> viewer(new Viewer());

    QSurfaceFormat format;
#ifdef NO_OPENGL_320
    format.setVersion(3, 0);
#else
    format.setVersion(3, 2);
    format.setProfile(QSurfaceFormat::CoreProfile);
#endif
    Canvas* canvas = new Canvas(format);
    canvas->setContinuousRepaint(true, 0);
    canvas->setSwapInterval(Canvas::VerticalSyncronization);

    QObject::connect(canvas, &Canvas::fpsUpdate, viewer.data(), &Viewer::fpsChanged);
    QObject::connect(canvas, &Canvas::objUpdate, viewer.data(), &Viewer::objChanged);
    QObject::connect(canvas, &Canvas::timeUpdate, viewer.data(), &Viewer::timeChanged);
    QObject::connect(canvas, &Canvas::mouseUpdate, viewer.data(), &Viewer::mouseChanged);
    QObject::connect(viewer.data(), &Viewer::toggleSwapInterval, canvas, &Canvas::toggleSwapInterval);

    Painter painter;
    canvas->assignPainter(&painter);

    QWidget * widget = QWidget::createWindowContainer(canvas);
    widget->setMinimumSize(1, 1);
    widget->setAutoFillBackground(false); // Important for overdraw, not occluding the scene.
    widget->setFocusPolicy(Qt::TabFocus);

    viewer->setCentralWidget(widget);
    viewer->show();

    result = app.exec();
    canvas->assignPainter(nullptr);

    return result;
    // QWidget seems to take double ownership of canvas and frees it doubled
}
<|endoftext|>