<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sqlparse.hxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-13 15:12:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#define _CONNECTIVITY_SQLPARSE_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _OSL_MUTEX_HXX_ //autogen wg. Mutex
#include <osl/mutex.hxx>
#endif
#ifndef _CONNECTIVITY_SQLNODE_HXX
#include <connectivity/sqlnode.hxx>
#endif
#ifndef YYBISON
#ifndef FLEX_SCANNER
#ifndef BISON_INCLUDED
#define BISON_INCLUDED
#include <sqlbison.hxx>
#endif
#endif
#endif
#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XLOCALEDATA_HPP_
#include <com/sun/star/i18n/XLocaleData.hpp>
#endif
#ifndef CONNECTIVITY_IPARSECONTEXT_HXX
#include "connectivity/IParseContext.hxx"
#endif

#include <map>

// forward declarations
namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace beans
            {
                class XPropertySet;
            }
            namespace util
            {
                class XNumberFormatter;
            }
            namespace lang
            {
                struct Locale;
            }
        }
    }
}
namespace connectivity
{
    class OSQLScanner;

    //==========================================================================
    //= OParseContext
    //==========================================================================
    class OParseContext : public IParseContext
    {
    public:
        OParseContext();

        virtual ~OParseContext();
        // retrieves language specific error messages
        virtual ::rtl::OUString getErrorMessage(ErrorCode _eCodes) const;

        // retrieves language specific keyword strings (only ASCII allowed)
        virtual ::rtl::OString getIntlKeywordAscii(InternationalKeyCode _eKey) const;

        // finds out, if we have an international keyword (only ASCII allowed)
        virtual InternationalKeyCode getIntlKeyCode(const ::rtl::OString& rToken) const;

        // determines the default international setting
        static const ::com::sun::star::lang::Locale& getDefaultLocale();

        /** set's the default locale which should be used when analyzing strings

If no locale is set, and any method which needs a locale is called, a default
            (en-US) is used.

If, while parsing, the locale can be obtained from other sources (such as the number format
            set for a table column), the preferred locale is ignored.

        */
        static void setDefaultLocale( const ::com::sun::star::lang::Locale& _rLocale );

        /** get's a locale instance which should be used when parsing in the context specified by this instance

if this is not overridden by derived classes, it returns the static default locale.

        */
        virtual ::com::sun::star::lang::Locale getPreferredLocale( ) const;
    };

    //==========================================================================
    //= OSQLParser
    //==========================================================================
    /** Parser for SQL92
    */
    class OSQLParser
    {
        friend class OSQLParseNode;
        friend class OSQLInternalNode;
        friend struct SQLParseNodeParameter;

    private:
        typedef ::std::map< sal_uInt32, OSQLParseNode::Rule >   RuleIDMap;
    //  static parts for parsers
        static sal_uInt32           s_nRuleIDs[OSQLParseNode::rule_count + 1];
        static RuleIDMap            s_aReverseRuleIDLookup;
        static OParseContext        s_aDefaultContext;

    //  parts controled by mutex
        //  static ::osl::Mutex         s_aMutex;
        static OSQLScanner*         s_pScanner;
        static OSQLParseNodes*      s_pGarbageCollector;
        static sal_Int32            s_nRefCount;

    // informations on the current parse action
        const IParseContext*        m_pContext;
        OSQLParseNode*              m_pParseTree;   // result from parsing
        ::com::sun::star::lang::Locale* m_pLocale;      // current locale settings for parsing
        ::rtl::OUString                     m_sFieldName;   // current field name for a predicate
        ::rtl::OUString                     m_sErrorMessage;// current error msg

        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                                    m_xField;       // current field
        ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >
                                    m_xFormatter;   // current number formatter
        sal_Int32                   m_nFormatKey;   // numberformat, which should be used
        sal_Int32                   m_nDateFormatKey;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >    m_xServiceFactory;
        ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XCharacterClassification> m_xCharClass;
        static ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData>       s_xLocaleData;
        ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData>      xDummy; // can be deleted after 627

        // convert a string into double trim it to scale of _nscale and than transform it back to string
        ::rtl::OUString stringToDouble(const ::rtl::OUString& _rValue,sal_Int16 _nScale);
        OSQLParseNode*  buildDate(sal_Int32 _nType,OSQLParseNode*& pLiteral);
        bool            extractDate(OSQLParseNode* pLiteral,double& _rfValue);
        void            killThousandSeparator(OSQLParseNode* pLiteral);
        OSQLParseNode*  convertNode(sal_Int32 nType,OSQLParseNode*& pLiteral);
        // makes a string out of a number, pLiteral will be deleted
        OSQLParseNode*  buildNode_STR_NUM(OSQLParseNode*& pLiteral);
        OSQLParseNode*  buildNode_Date(const double& fValue, sal_Int32 nType);

        static ::osl::Mutex& getMutex();

    public:
        // if NULL, a default context will be used
        // the context must live as long as the parser
        OSQLParser(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xServiceFactory,const IParseContext* _pContext = NULL);
        ~OSQLParser();

        // Parsing an SQLStatement
        OSQLParseNode* parseTree(::rtl::OUString& rErrorMessage,
                       const ::rtl::OUString& rStatement,
                       sal_Bool bInternational = sal_False);

        // Check a Predicate
        OSQLParseNode* predicateTree(::rtl::OUString& rErrorMessage, const ::rtl::OUString& rStatement,
                       const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > & xFormatter,
                       const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & xField);

        // Access to the context
        const IParseContext& getContext() const {return *m_pContext;}

        // TokenIDToStr: Token-Name zu einer Token-Nr.
        static ::rtl::OString TokenIDToStr(sal_uInt32 nTokenID, const IParseContext* pContext = NULL);

        // StrToTokenID: Token-Nr. zu einem Token-Namen.
        // static sal_uInt32 StrToTokenID(const ::rtl::OString & rName);

        // RuleIDToStr gibt den zu einer RuleID gehoerenden ::rtl::OUString zurueck
        // (Leerstring, falls nicht gefunden)
        static ::rtl::OUString RuleIDToStr(sal_uInt32 nRuleID);

        // StrToRuleID berechnet zu einem ::rtl::OUString die RuleID (d.h. ::com::sun::star::sdbcx::Index in yytname)
        // (0, falls nicht gefunden). Die Suche nach der ID aufgrund eines Strings ist
        // extrem ineffizient (sequentielle Suche nach ::rtl::OUString)!
        static sal_uInt32 StrToRuleID(const ::rtl::OString & rValue);

        static OSQLParseNode::Rule RuleIDToRule( sal_uInt32 _nRule );

        // RuleId mit enum, wesentlich effizienter
        static sal_uInt32 RuleID(OSQLParseNode::Rule eRule);
        // compares the _sFunctionName with all known function names and return the DataType of the return value
        static sal_Int32 getFunctionReturnType(const ::rtl::OUString& _sFunctionName, const IParseContext* pContext = NULL);

        void error(sal_Char *fmt);
        int SQLlex();
#ifdef YYBISON
        void setParseTree(OSQLParseNode * pNewParseTree);

        // Is the parse in a special mode?
        // Predicate chack is used to check a condition for a field
        sal_Bool inPredicateCheck() const {return m_xField.is();}
        const ::rtl::OUString& getFieldName() const {return m_sFieldName;}

        void reduceLiteral(OSQLParseNode*& pLiteral, sal_Bool bAppendBlank);
         // does not change the pLiteral argument
        sal_Int16 buildNode(OSQLParseNode*& pAppend,OSQLParseNode* pCompare,OSQLParseNode* pLiteral,OSQLParseNode* pLiteral2);

        sal_Int16 buildComparsionRule(OSQLParseNode*& pAppend,OSQLParseNode* pLiteral);
        // pCompre will be deleted if it is not used
        sal_Int16 buildPredicateRule(OSQLParseNode*& pAppend,OSQLParseNode* pLiteral,OSQLParseNode*& pCompare,OSQLParseNode* pLiteral2 = NULL);

        sal_Int16 buildLikeRule(OSQLParseNode*& pAppend,OSQLParseNode*& pLiteral,const OSQLParseNode* pEscape);
        sal_Int16 buildStringNodes(OSQLParseNode*& pLiteral);
#else
#endif
    };
}

#endif //_CONNECTIVITY_SQLPARSE_HXX
<commit_msg>INTEGRATION: CWS hedaburemove01 (1.20.98); FILE MERGED 2007/02/09 16:04:43 vg 1.20.98.1: #72503# get rid of hedabu procedure: Moving headers to connectivity/inc/connectivity and correspondent necessary changes<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sqlparse.hxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 12:35:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#define _CONNECTIVITY_SQLPARSE_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _OSL_MUTEX_HXX_ //autogen wg. Mutex
#include <osl/mutex.hxx>
#endif
#ifndef _CONNECTIVITY_SQLNODE_HXX
#include <connectivity/sqlnode.hxx>
#endif
#ifndef YYBISON
#ifndef FLEX_SCANNER
#ifndef BISON_INCLUDED
#define BISON_INCLUDED
#include "sqlbison.hxx"
#endif
#endif
#endif
#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XLOCALEDATA_HPP_
#include <com/sun/star/i18n/XLocaleData.hpp>
#endif
#ifndef CONNECTIVITY_IPARSECONTEXT_HXX
#include "connectivity/IParseContext.hxx"
#endif

#include <map>

// forward declarations
namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace beans
            {
                class XPropertySet;
            }
            namespace util
            {
                class XNumberFormatter;
            }
            namespace lang
            {
                struct Locale;
            }
        }
    }
}
namespace connectivity
{
    class OSQLScanner;

    //==========================================================================
    //= OParseContext
    //==========================================================================
    class OParseContext : public IParseContext
    {
    public:
        OParseContext();

        virtual ~OParseContext();
        // retrieves language specific error messages
        virtual ::rtl::OUString getErrorMessage(ErrorCode _eCodes) const;

        // retrieves language specific keyword strings (only ASCII allowed)
        virtual ::rtl::OString getIntlKeywordAscii(InternationalKeyCode _eKey) const;

        // finds out, if we have an international keyword (only ASCII allowed)
        virtual InternationalKeyCode getIntlKeyCode(const ::rtl::OString& rToken) const;

        // determines the default international setting
        static const ::com::sun::star::lang::Locale& getDefaultLocale();

        /** set's the default locale which should be used when analyzing strings

If no locale is set, and any method which needs a locale is called, a default
            (en-US) is used.

If, while parsing, the locale can be obtained from other sources (such as the number format
            set for a table column), the preferred locale is ignored.

        */
        static void setDefaultLocale( const ::com::sun::star::lang::Locale& _rLocale );

        /** get's a locale instance which should be used when parsing in the context specified by this instance

if this is not overridden by derived classes, it returns the static default locale.

        */
        virtual ::com::sun::star::lang::Locale getPreferredLocale( ) const;
    };

    //==========================================================================
    //= OSQLParser
    //==========================================================================
    /** Parser for SQL92
    */
    class OSQLParser
    {
        friend class OSQLParseNode;
        friend class OSQLInternalNode;
        friend struct SQLParseNodeParameter;

    private:
        typedef ::std::map< sal_uInt32, OSQLParseNode::Rule >   RuleIDMap;
    //  static parts for parsers
        static sal_uInt32           s_nRuleIDs[OSQLParseNode::rule_count + 1];
        static RuleIDMap            s_aReverseRuleIDLookup;
        static OParseContext        s_aDefaultContext;

    //  parts controled by mutex
        //  static ::osl::Mutex         s_aMutex;
        static OSQLScanner*         s_pScanner;
        static OSQLParseNodes*      s_pGarbageCollector;
        static sal_Int32            s_nRefCount;

    // informations on the current parse action
        const IParseContext*        m_pContext;
        OSQLParseNode*              m_pParseTree;   // result from parsing
        ::com::sun::star::lang::Locale* m_pLocale;      // current locale settings for parsing
        ::rtl::OUString                     m_sFieldName;   // current field name for a predicate
        ::rtl::OUString                     m_sErrorMessage;// current error msg

        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                                    m_xField;       // current field
        ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >
                                    m_xFormatter;   // current number formatter
        sal_Int32                   m_nFormatKey;   // numberformat, which should be used
        sal_Int32                   m_nDateFormatKey;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >    m_xServiceFactory;
        ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XCharacterClassification> m_xCharClass;
        static ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData>       s_xLocaleData;
        ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData>      xDummy; // can be deleted after 627

        // convert a string into double trim it to scale of _nscale and than transform it back to string
        ::rtl::OUString stringToDouble(const ::rtl::OUString& _rValue,sal_Int16 _nScale);
        OSQLParseNode*  buildDate(sal_Int32 _nType,OSQLParseNode*& pLiteral);
        bool            extractDate(OSQLParseNode* pLiteral,double& _rfValue);
        void            killThousandSeparator(OSQLParseNode* pLiteral);
        OSQLParseNode*  convertNode(sal_Int32 nType,OSQLParseNode*& pLiteral);
        // makes a string out of a number, pLiteral will be deleted
        OSQLParseNode*  buildNode_STR_NUM(OSQLParseNode*& pLiteral);
        OSQLParseNode*  buildNode_Date(const double& fValue, sal_Int32 nType);

        static ::osl::Mutex& getMutex();

    public:
        // if NULL, a default context will be used
        // the context must live as long as the parser
        OSQLParser(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xServiceFactory,const IParseContext* _pContext = NULL);
        ~OSQLParser();

        // Parsing an SQLStatement
        OSQLParseNode* parseTree(::rtl::OUString& rErrorMessage,
                       const ::rtl::OUString& rStatement,
                       sal_Bool bInternational = sal_False);

        // Check a Predicate
        OSQLParseNode* predicateTree(::rtl::OUString& rErrorMessage, const ::rtl::OUString& rStatement,
                       const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > & xFormatter,
                       const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & xField);

        // Access to the context
        const IParseContext& getContext() const {return *m_pContext;}

        // TokenIDToStr: Token-Name zu einer Token-Nr.
        static ::rtl::OString TokenIDToStr(sal_uInt32 nTokenID, const IParseContext* pContext = NULL);

        // StrToTokenID: Token-Nr. zu einem Token-Namen.
        // static sal_uInt32 StrToTokenID(const ::rtl::OString & rName);

        // RuleIDToStr gibt den zu einer RuleID gehoerenden ::rtl::OUString zurueck
        // (Leerstring, falls nicht gefunden)
        static ::rtl::OUString RuleIDToStr(sal_uInt32 nRuleID);

        // StrToRuleID berechnet zu einem ::rtl::OUString die RuleID (d.h. ::com::sun::star::sdbcx::Index in yytname)
        // (0, falls nicht gefunden). Die Suche nach der ID aufgrund eines Strings ist
        // extrem ineffizient (sequentielle Suche nach ::rtl::OUString)!
        static sal_uInt32 StrToRuleID(const ::rtl::OString & rValue);

        static OSQLParseNode::Rule RuleIDToRule( sal_uInt32 _nRule );

        // RuleId mit enum, wesentlich effizienter
        static sal_uInt32 RuleID(OSQLParseNode::Rule eRule);
        // compares the _sFunctionName with all known function names and return the DataType of the return value
        static sal_Int32 getFunctionReturnType(const ::rtl::OUString& _sFunctionName, const IParseContext* pContext = NULL);

        void error(sal_Char *fmt);
        int SQLlex();
#ifdef YYBISON
        void setParseTree(OSQLParseNode * pNewParseTree);

        // Is the parse in a special mode?
        // Predicate chack is used to check a condition for a field
        sal_Bool inPredicateCheck() const {return m_xField.is();}
        const ::rtl::OUString& getFieldName() const {return m_sFieldName;}

        void reduceLiteral(OSQLParseNode*& pLiteral, sal_Bool bAppendBlank);
         // does not change the pLiteral argument
        sal_Int16 buildNode(OSQLParseNode*& pAppend,OSQLParseNode* pCompare,OSQLParseNode* pLiteral,OSQLParseNode* pLiteral2);

        sal_Int16 buildComparsionRule(OSQLParseNode*& pAppend,OSQLParseNode* pLiteral);
        // pCompre will be deleted if it is not used
        sal_Int16 buildPredicateRule(OSQLParseNode*& pAppend,OSQLParseNode* pLiteral,OSQLParseNode*& pCompare,OSQLParseNode* pLiteral2 = NULL);

        sal_Int16 buildLikeRule(OSQLParseNode*& pAppend,OSQLParseNode*& pLiteral,const OSQLParseNode* pEscape);
        sal_Int16 buildStringNodes(OSQLParseNode*& pLiteral);
#else
#endif
    };
}

#endif //_CONNECTIVITY_SQLPARSE_HXX
<|endoftext|>


<commit_before>#include "UnrealEnginePythonPrivatePCH.h"
#include "PyCommandlet.h"

#include "Regex.h"

UPyCommandlet::UPyCommandlet(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	LogToConsole = 1;
}

int32 UPyCommandlet::Main(const FString& CommandLine)
{
	TArray<FString> Tokens, Switches;
	TMap<FString, FString> Params;
	ParseCommandLine(*CommandLine, Tokens, Switches, Params);

	FString Filepath = Tokens[0];
	if (!FPaths::FileExists(*Filepath))
	{
		UE_LOG(LogPython, Error, TEXT("Python file could not be found: %s"), *Filepath);
		return -1;
	}

	FString RegexString = FString::Printf(TEXT("(?<=%s).*"), *(Filepath.Replace(TEXT("\\"), TEXT("\\\\"))));
	const FRegexPattern myPattern(RegexString);
	FRegexMatcher myMatcher(myPattern, *CommandLine);
	myMatcher.FindNext();
	FString PyCommandLine = myMatcher.GetCaptureGroup(0).Trim().TrimTrailing();

	TArray<FString> PyArgv = {FString()};
	bool escaped = false;
	for (int i = 0; i < PyCommandLine.Len(); i++)
	{
		if(PyCommandLine[i] == ' ')
		{
			PyArgv.Add(FString());
			continue;
		}
		else if(PyCommandLine[i] == '\"' && !escaped)
		{
			i++;
			while(i < PyCommandLine.Len() && !(PyCommandLine[i] == '"'))
			{
				PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]);
				i++;
				if (i == PyCommandLine.Len())
				{
					PyArgv[PyArgv.Num() - 1].InsertAt(0, "\"");
				}
			}
		}
		else
		{
			if (PyCommandLine[i] == '\\')
				escaped = true;
			else
				escaped = false;
			PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]);
		}
	}
	PyArgv.Insert(Filepath, 0);

#if PY_MAJOR_VERSION >= 3
	wchar_t **argv = (wchar_t **)malloc(PyArgv.Num() * sizeof(void*));
#else
	char **argv = (char **)malloc(PyArgv.Num() * sizeof(void*));
#endif

	for (int i=0; i<PyArgv.Num(); i++)
	{
#if PY_MAJOR_VERSION >= 3
		argv[i] = (wchar_t*)malloc(PyArgv[i].Len()+1);
		wcscpy_s(argv[i], PyArgv[i].Len()+1, *PyArgv[i].ReplaceEscapedCharWithChar());
#else
		argv[i] = (char*)malloc(PyArgv[i].Len() + 1);
		strcpy_s(argv[i], PyArgv[i].Len()+1, TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar()));
#endif
	}

	PySys_SetArgv(PyArgv.Num(), argv);

	FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython");
	PythonModule.RunFile(TCHAR_TO_UTF8(*Filepath));
	return 0;
}
<commit_msg>Use wcsncpy instead of wcscpy_s<commit_after>#include "UnrealEnginePythonPrivatePCH.h"
#include "PyCommandlet.h"

#include "Regex.h"

UPyCommandlet::UPyCommandlet(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	LogToConsole = 1;
}

int32 UPyCommandlet::Main(const FString& CommandLine)
{
	TArray<FString> Tokens, Switches;
	TMap<FString, FString> Params;
	ParseCommandLine(*CommandLine, Tokens, Switches, Params);

	FString Filepath = Tokens[0];
	if (!FPaths::FileExists(*Filepath))
	{
		UE_LOG(LogPython, Error, TEXT("Python file could not be found: %s"), *Filepath);
		return -1;
	}

	FString RegexString = FString::Printf(TEXT("(?<=%s).*"), *(Filepath.Replace(TEXT("\\"), TEXT("\\\\"))));
	const FRegexPattern myPattern(RegexString);
	FRegexMatcher myMatcher(myPattern, *CommandLine);
	myMatcher.FindNext();
	FString PyCommandLine = myMatcher.GetCaptureGroup(0).Trim().TrimTrailing();

	TArray<FString> PyArgv = {FString()};
	bool escaped = false;
	for (int i = 0; i < PyCommandLine.Len(); i++)
	{
		if(PyCommandLine[i] == ' ')
		{
			PyArgv.Add(FString());
			continue;
		}
		else if(PyCommandLine[i] == '\"' && !escaped)
		{
			i++;
			while(i < PyCommandLine.Len() && !(PyCommandLine[i] == '"'))
			{
				PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]);
				i++;
				if (i == PyCommandLine.Len())
				{
					PyArgv[PyArgv.Num() - 1].InsertAt(0, "\"");
				}
			}
		}
		else
		{
			if (PyCommandLine[i] == '\\')
				escaped = true;
			else
				escaped = false;
			PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]);
		}
	}
	PyArgv.Insert(Filepath, 0);

#if PY_MAJOR_VERSION >= 3
	wchar_t **argv = (wchar_t **)malloc(PyArgv.Num() * sizeof(void*));
#else
	char **argv = (char **)malloc(PyArgv.Num() * sizeof(void*));
#endif

	for (int i=0; i<PyArgv.Num(); i++)
	{
#if PY_MAJOR_VERSION >= 3
		argv[i] = (wchar_t*)malloc(PyArgv[i].Len()+1);
    wcsncpy(argv[i], *PyArgv[i].ReplaceEscapedCharWithChar(), PyArgv[i].Len()+1);
#else
		argv[i] = (char*)malloc(PyArgv[i].Len() + 1);
		strcpy_s(argv[i], PyArgv[i].Len()+1, TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar()));
#endif
	}

	PySys_SetArgv(PyArgv.Num(), argv);

	FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython");
	PythonModule.RunFile(TCHAR_TO_UTF8(*Filepath));
	return 0;
}
<|endoftext|>


<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2016 Michael Fink
//
/// \file WindowPlacement.hpp window placement
//
#pragma once

class WindowPlacement : public WINDOWPLACEMENT
{
public:
   /// ctor
   WindowPlacement()
   {
      ZeroMemory((WINDOWPLACEMENT*)this, sizeof(WINDOWPLACEMENT));
      length = sizeof(WINDOWPLACEMENT);
   }

   /// sets window placement for window
   void Set(HWND hWnd) throw()
   {
      ::SetWindowPlacement(hWnd, (WINDOWPLACEMENT*)this);
   }

   /// gets window placement from window
   void Get(HWND hWnd) const throw()
   {
      ::GetWindowPlacement(hWnd, (WINDOWPLACEMENT*)this);
   }

   /// stores window placement in registy key, with given prefix
   void Store(CRegKey& regRoot, LPCTSTR pszPrefix) const
   {
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_Flags"), flags);
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_ShowCmd"), showCmd);
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_MinPositionX"), ptMinPosition.x);
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_MinPositionY"), ptMinPosition.y);
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_MaxPositionX"), ptMaxPosition.x);
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_MaxPositionY"), ptMaxPosition.y);
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_NormalPositionLeft"), rcNormalPosition.left);
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_NormalPositionTop"), rcNormalPosition.top);
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_NormalPositionRight"), rcNormalPosition.right);
      regRoot.SetDWORDValue(CString(pszPrefix) + _T("_NormalPositionBottom"), rcNormalPosition.bottom);
   }

   /// loads window placement from registy key, with given prefix
   void Load(CRegKey& regRoot, LPCTSTR pszPrefix)
   {
      showCmd = 0; // default value, to decide if load was successful

      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_Flags"), flags);
      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_ShowCmd"), showCmd);
      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_MinPositionX"), ptMinPosition.x);
      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_MinPositionY"), ptMinPosition.y);
      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_MaxPositionX"), ptMaxPosition.x);
      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_MaxPositionY"), ptMaxPosition.y);
      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_NormalPositionLeft"), rcNormalPosition.left);
      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_NormalPositionTop"), rcNormalPosition.top);
      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_NormalPositionRight"), rcNormalPosition.right);
      ReadIntegerValue(regRoot, CString(pszPrefix) + _T("_NormalPositionBottom"), rcNormalPosition.bottom);
   }

private:
   /// reads integer value from registry
   template <typename T>
   void ReadIntegerValue(CRegKey& regKey, LPCTSTR pszName, T& value)
   {
      DWORD dwordValue;
      if (ERROR_SUCCESS == regKey.QueryDWORDValue(pszName, dwordValue))
         value = static_cast<T>(dwordValue);
   }
};
<commit_msg>changed prefix parameter of Store() and Load() methods<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2016 Michael Fink
//
/// \file WindowPlacement.hpp window placement
//
#pragma once

/// \brief window placement class
/// \details stores window coordinates and maximized state for storing and
/// restoring.
class WindowPlacement : public WINDOWPLACEMENT
{
public:
   /// ctor
   WindowPlacement()
   {
      ZeroMemory((WINDOWPLACEMENT*)this, sizeof(WINDOWPLACEMENT));
      length = sizeof(WINDOWPLACEMENT);
   }

   /// sets window placement for window
   void Set(HWND hWnd) throw()
   {
      ::SetWindowPlacement(hWnd, (WINDOWPLACEMENT*)this);
   }

   /// gets window placement from window
   void Get(HWND hWnd) const throw()
   {
      ::GetWindowPlacement(hWnd, (WINDOWPLACEMENT*)this);
   }

   /// stores window placement in registy key, with given prefix
   void Store(CRegKey& regRoot, const CString& cszPrefix) const
   {
      regRoot.SetDWORDValue(cszPrefix + _T("_Flags"), flags);
      regRoot.SetDWORDValue(cszPrefix + _T("_ShowCmd"), showCmd);
      regRoot.SetDWORDValue(cszPrefix + _T("_MinPositionX"), ptMinPosition.x);
      regRoot.SetDWORDValue(cszPrefix + _T("_MinPositionY"), ptMinPosition.y);
      regRoot.SetDWORDValue(cszPrefix + _T("_MaxPositionX"), ptMaxPosition.x);
      regRoot.SetDWORDValue(cszPrefix + _T("_MaxPositionY"), ptMaxPosition.y);
      regRoot.SetDWORDValue(cszPrefix + _T("_NormalPositionLeft"), rcNormalPosition.left);
      regRoot.SetDWORDValue(cszPrefix + _T("_NormalPositionTop"), rcNormalPosition.top);
      regRoot.SetDWORDValue(cszPrefix + _T("_NormalPositionRight"), rcNormalPosition.right);
      regRoot.SetDWORDValue(cszPrefix + _T("_NormalPositionBottom"), rcNormalPosition.bottom);
   }

   /// loads window placement from registy key, with given prefix
   void Load(CRegKey& regRoot, const CString& cszPrefix)
   {
      showCmd = 0; // default value, to decide if load was successful

      ReadIntegerValue(regRoot, cszPrefix + _T("_Flags"), flags);
      ReadIntegerValue(regRoot, cszPrefix + _T("_ShowCmd"), showCmd);
      ReadIntegerValue(regRoot, cszPrefix + _T("_MinPositionX"), ptMinPosition.x);
      ReadIntegerValue(regRoot, cszPrefix + _T("_MinPositionY"), ptMinPosition.y);
      ReadIntegerValue(regRoot, cszPrefix + _T("_MaxPositionX"), ptMaxPosition.x);
      ReadIntegerValue(regRoot, cszPrefix + _T("_MaxPositionY"), ptMaxPosition.y);
      ReadIntegerValue(regRoot, cszPrefix + _T("_NormalPositionLeft"), rcNormalPosition.left);
      ReadIntegerValue(regRoot, cszPrefix + _T("_NormalPositionTop"), rcNormalPosition.top);
      ReadIntegerValue(regRoot, cszPrefix + _T("_NormalPositionRight"), rcNormalPosition.right);
      ReadIntegerValue(regRoot, cszPrefix + _T("_NormalPositionBottom"), rcNormalPosition.bottom);
   }

private:
   /// reads integer value from registry
   template <typename T>
   void ReadIntegerValue(CRegKey& regKey, LPCTSTR pszName, T& value)
   {
      DWORD dwordValue;
      if (ERROR_SUCCESS == regKey.QueryDWORDValue(pszName, dwordValue))
         value = static_cast<T>(dwordValue);
   }
};
<|endoftext|>


<commit_before><commit_msg>Allow a pasted-in crash URL to work.<commit_after><|endoftext|>


<commit_before>// Copyright 2014 Vladimir Alyamkin. All Rights Reserved.

#include "VaRestPluginPrivatePCH.h"
#include "CoreMisc.h"

template <class T> void FVaRestLatentAction<T>::Cancel()
{
	UObject *Obj = Request.Get();
	if (Obj != nullptr)
	{
		((UVaRestRequestJSON*)Obj)->Cancel();
	}
}

UVaRestRequestJSON::UVaRestRequestJSON(const class FObjectInitializer& PCIP)
  : Super(PCIP),
    BinaryContentType(TEXT("application/octet-stream"))
{
	RequestVerb = ERequestVerb::GET;
	RequestContentType = ERequestContentType::x_www_form_urlencoded_url;

	ResetData();
}

UVaRestRequestJSON* UVaRestRequestJSON::ConstructRequest(UObject* WorldContextObject)
{
	return NewObject<UVaRestRequestJSON>();
}

UVaRestRequestJSON* UVaRestRequestJSON::ConstructRequestExt(
	UObject* WorldContextObject,
	ERequestVerb Verb,
	ERequestContentType ContentType)
{
	UVaRestRequestJSON* Request = ConstructRequest(WorldContextObject);

	Request->SetVerb(Verb);
	Request->SetContentType(ContentType);

	return Request;
}

void UVaRestRequestJSON::SetVerb(ERequestVerb Verb)
{
	RequestVerb = Verb;
}

void UVaRestRequestJSON::SetCustomVerb(FString Verb)
{
	CustomVerb = Verb;
}

void UVaRestRequestJSON::SetContentType(ERequestContentType ContentType)
{
	RequestContentType = ContentType;
}

void UVaRestRequestJSON::SetBinaryContentType(const FString &ContentType)
{
	BinaryContentType = ContentType;
}

void UVaRestRequestJSON::SetBinaryRequestContent(const TArray<uint8> &Bytes)
{
	RequestBytes = Bytes;
}

void UVaRestRequestJSON::SetHeader(const FString& HeaderName, const FString& HeaderValue)
{
	RequestHeaders.Add(HeaderName, HeaderValue);
}

//////////////////////////////////////////////////////////////////////////
// Destruction and reset

void UVaRestRequestJSON::ResetData()
{
	ResetRequestData();
	ResetResponseData();
}

void UVaRestRequestJSON::ResetRequestData()
{
	if (RequestJsonObj != nullptr)
	{
		RequestJsonObj->Reset();
	}
	else
	{
		RequestJsonObj = NewObject<UVaRestJsonObject>();
	}

	HttpRequest = FHttpModule::Get().CreateRequest();
}

void UVaRestRequestJSON::ResetResponseData()
{
	if (ResponseJsonObj != nullptr)
	{
		ResponseJsonObj->Reset();
	}
	else
	{
		ResponseJsonObj = NewObject<UVaRestJsonObject>();
	}

	ResponseHeaders.Empty();
	ResponseCode = -1;

	bIsValidJsonResponse = false;
}

void UVaRestRequestJSON::Cancel()
{
	ContinueAction = nullptr;

	ResetResponseData();
}

//////////////////////////////////////////////////////////////////////////
// JSON data accessors

UVaRestJsonObject* UVaRestRequestJSON::GetRequestObject()
{
	return RequestJsonObj;
}

void UVaRestRequestJSON::SetRequestObject(UVaRestJsonObject* JsonObject)
{
	RequestJsonObj = JsonObject;
}

UVaRestJsonObject* UVaRestRequestJSON::GetResponseObject()
{
	return ResponseJsonObj;
}

void UVaRestRequestJSON::SetResponseObject(UVaRestJsonObject* JsonObject)
{
	ResponseJsonObj = JsonObject;
}

///////////////////////////////////////////////////////////////////////////
// Response data access

FString UVaRestRequestJSON::GetURL()
{
	return HttpRequest->GetURL();
}

ERequestStatus UVaRestRequestJSON::GetStatus()
{
	return ERequestStatus((uint8)HttpRequest->GetStatus());
}

int32 UVaRestRequestJSON::GetResponseCode()
{
	return ResponseCode;
}

FString UVaRestRequestJSON::GetResponseHeader(const FString HeaderName)
{
	FString Result;

	FString* Header = ResponseHeaders.Find(HeaderName);
	if (Header != nullptr)
	{
		Result = *Header;
	}

	return Result;
}

TArray<FString> UVaRestRequestJSON::GetAllResponseHeaders()
{
	TArray<FString> Result;
	for (TMap<FString, FString>::TConstIterator It(ResponseHeaders); It; ++It)
	{
		Result.Add(It.Key() + TEXT(": ") + It.Value());
	}
	return Result;
}

//////////////////////////////////////////////////////////////////////////
// URL processing

void UVaRestRequestJSON::ProcessURL(const FString& Url)
{
	HttpRequest->SetURL(Url);

	ProcessRequest();
}

void UVaRestRequestJSON::ApplyURL(const FString& Url, UVaRestJsonObject *&Result, UObject* WorldContextObject, FLatentActionInfo LatentInfo)
{
	HttpRequest->SetURL(Url);

	// Prepare latent action
	if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject))
	{
		FLatentActionManager& LatentActionManager = World->GetLatentActionManager();
		FVaRestLatentAction<UVaRestJsonObject*> *Kont = LatentActionManager.FindExistingAction<FVaRestLatentAction<UVaRestJsonObject*>>(LatentInfo.CallbackTarget, LatentInfo.UUID);

		if (Kont != nullptr)
		{
			Kont->Cancel();
			LatentActionManager.RemoveActionsForObject(LatentInfo.CallbackTarget);
		}

		LatentActionManager.AddNewAction(LatentInfo.CallbackTarget, LatentInfo.UUID, ContinueAction = new FVaRestLatentAction<UVaRestJsonObject*>(this, Result, LatentInfo));
	}

	ProcessRequest();
}

void UVaRestRequestJSON::ProcessRequest()
{
	// Set verb
	switch (RequestVerb)
	{
	case ERequestVerb::GET:
		HttpRequest->SetVerb(TEXT("GET"));
		break;

	case ERequestVerb::POST:
		HttpRequest->SetVerb(TEXT("POST"));
		break;

	case ERequestVerb::PUT:
		HttpRequest->SetVerb(TEXT("PUT"));
		break;

	case ERequestVerb::DEL:
		HttpRequest->SetVerb(TEXT("DELETE"));
		break;

	case ERequestVerb::CUSTOM:
		HttpRequest->SetVerb(CustomVerb);
		break;

	default:
		break;
	}

	// Set content-type
	switch (RequestContentType)
	{
	case ERequestContentType::x_www_form_urlencoded_url:
	{
		HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/x-www-form-urlencoded"));

		FString UrlParams = "";
		uint16 ParamIdx = 0;

		// Loop through all the values and prepare additional url part
		for (auto RequestIt = RequestJsonObj->GetRootObject()->Values.CreateIterator(); RequestIt; ++RequestIt)
		{
			FString Key = RequestIt.Key();
			FString Value = RequestIt.Value().Get()->AsString();

			if (!Key.IsEmpty() && !Value.IsEmpty())
			{
				UrlParams += ParamIdx == 0 ? "?" : "&";
				UrlParams += UVaRestLibrary::PercentEncode(Key) + "=" + UVaRestLibrary::PercentEncode(Value);
			}

			ParamIdx++;
		}

		// Apply params
		HttpRequest->SetURL(HttpRequest->GetURL() + UrlParams);

		UE_LOG(LogVaRest, Log, TEXT("Request (urlencoded): %s %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL(), *UrlParams);

		break;
	}
	case ERequestContentType::x_www_form_urlencoded_body:
	{
		HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/x-www-form-urlencoded"));

		FString UrlParams = "";
		uint16 ParamIdx = 0;

		// Loop through all the values and prepare additional url part
		for (auto RequestIt = RequestJsonObj->GetRootObject()->Values.CreateIterator(); RequestIt; ++RequestIt)
		{
			FString Key = RequestIt.Key();
			FString Value = RequestIt.Value().Get()->AsString();

			if (!Key.IsEmpty() && !Value.IsEmpty())
			{
				UrlParams += ParamIdx == 0 ? "" : "&";
				UrlParams += UVaRestLibrary::PercentEncode(Key) + "=" + UVaRestLibrary::PercentEncode(Value);
			}

			ParamIdx++;
		}

		// Apply params
		HttpRequest->SetContentAsString(UrlParams);

		UE_LOG(LogVaRest, Log, TEXT("Request (url body): %s %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL(), *UrlParams);

		break;
	}
	case ERequestContentType::binary:
	{
		HttpRequest->SetHeader(TEXT("Content-Type"), BinaryContentType);
		HttpRequest->SetContent(RequestBytes);

		UE_LOG(LogVaRest, Log, TEXT("Request (binary): %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL());

		break;
	}
	case ERequestContentType::json:
	{
		HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json"));

		// Serialize data to json string
		FString OutputString;
		TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString);
		FJsonSerializer::Serialize(RequestJsonObj->GetRootObject().ToSharedRef(), Writer);

		// Set Json content
		HttpRequest->SetContentAsString(OutputString);

		UE_LOG(LogVaRest, Log, TEXT("Request (json): %s %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL(), *OutputString);

		break;
	}

	default:
		break;
	}

	// Apply additional headers
	for (TMap<FString, FString>::TConstIterator It(RequestHeaders); It; ++It)
	{
		HttpRequest->SetHeader(It.Key(), It.Value());
	}

	// Bind event
	HttpRequest->OnProcessRequestComplete().BindUObject(this, &UVaRestRequestJSON::OnProcessRequestComplete);

	// Execute the request
	HttpRequest->ProcessRequest();
}

//////////////////////////////////////////////////////////////////////////
// Request callbacks

void UVaRestRequestJSON::OnProcessRequestComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
	// Be sure that we have no data from previous response
	ResetResponseData();

	// Check we have a response and save response code as int32
	if(Response.IsValid())
	{
		ResponseCode = Response->GetResponseCode();
	}

	// Check we have result to process futher
	if (!bWasSuccessful || !Response.IsValid())
	{
		UE_LOG(LogVaRest, Error, TEXT("Request failed (%d): %s"), ResponseCode, *Request->GetURL());

		// Broadcast the result event
		OnRequestFail.Broadcast(this);
		OnStaticRequestFail.Broadcast(this);

		return;
	}

	// Save response data as a string
	ResponseContent = Response->GetContentAsString();

	// Log response state
	UE_LOG(LogVaRest, Log, TEXT("Response (%d): %s"), ResponseCode, *ResponseContent);

	// Process response headers
	TArray<FString> Headers = Response->GetAllHeaders();
	for (FString Header : Headers)
	{
		FString Key;
		FString Value;
		if (Header.Split(TEXT(": "), &Key, &Value))
		{
			ResponseHeaders.Add(Key, Value);
		}
	}

	// Try to deserialize data to JSON
	TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(ResponseContent);
	FJsonSerializer::Deserialize(JsonReader, ResponseJsonObj->GetRootObject());

	// Decide whether the request was successful
	bIsValidJsonResponse = bWasSuccessful && ResponseJsonObj->GetRootObject().IsValid();

	// Log errors
	if (!bIsValidJsonResponse)
	{
		if (!ResponseJsonObj->GetRootObject().IsValid())
		{
			// As we assume it's recommended way to use current class, but not the only one,
			// it will be the warning instead of error
			UE_LOG(LogVaRest, Warning, TEXT("JSON could not be decoded!"));
		}
	}

	// Broadcast the result event
	OnRequestComplete.Broadcast(this);
	OnStaticRequestComplete.Broadcast(this);

	// Finish the latent action
	if (ContinueAction)
	{
          FVaRestLatentAction<UVaRestJsonObject*> *K = ContinueAction;
          ContinueAction = nullptr;

          K->Call(ResponseJsonObj);
	}
}

//////////////////////////////////////////////////////////////////////////
// Tags

void UVaRestRequestJSON::AddTag(FName Tag)
{
	if (Tag != NAME_None)
	{
		Tags.AddUnique(Tag);
	}
}

int32 UVaRestRequestJSON::RemoveTag(FName Tag)
{
	return Tags.Remove(Tag);
}

bool UVaRestRequestJSON::HasTag(FName Tag) const
{
	return (Tag != NAME_None) && Tags.Contains(Tag);
}
<commit_msg>Special formatting for JSON requests<commit_after>// Copyright 2014 Vladimir Alyamkin. All Rights Reserved.

#include "VaRestPluginPrivatePCH.h"
#include "CoreMisc.h"

template <class T> void FVaRestLatentAction<T>::Cancel()
{
	UObject *Obj = Request.Get();
	if (Obj != nullptr)
	{
		((UVaRestRequestJSON*)Obj)->Cancel();
	}
}

UVaRestRequestJSON::UVaRestRequestJSON(const class FObjectInitializer& PCIP)
  : Super(PCIP),
    BinaryContentType(TEXT("application/octet-stream"))
{
	RequestVerb = ERequestVerb::GET;
	RequestContentType = ERequestContentType::x_www_form_urlencoded_url;

	ResetData();
}

UVaRestRequestJSON* UVaRestRequestJSON::ConstructRequest(UObject* WorldContextObject)
{
	return NewObject<UVaRestRequestJSON>();
}

UVaRestRequestJSON* UVaRestRequestJSON::ConstructRequestExt(
	UObject* WorldContextObject,
	ERequestVerb Verb,
	ERequestContentType ContentType)
{
	UVaRestRequestJSON* Request = ConstructRequest(WorldContextObject);

	Request->SetVerb(Verb);
	Request->SetContentType(ContentType);

	return Request;
}

void UVaRestRequestJSON::SetVerb(ERequestVerb Verb)
{
	RequestVerb = Verb;
}

void UVaRestRequestJSON::SetCustomVerb(FString Verb)
{
	CustomVerb = Verb;
}

void UVaRestRequestJSON::SetContentType(ERequestContentType ContentType)
{
	RequestContentType = ContentType;
}

void UVaRestRequestJSON::SetBinaryContentType(const FString &ContentType)
{
	BinaryContentType = ContentType;
}

void UVaRestRequestJSON::SetBinaryRequestContent(const TArray<uint8> &Bytes)
{
	RequestBytes = Bytes;
}

void UVaRestRequestJSON::SetHeader(const FString& HeaderName, const FString& HeaderValue)
{
	RequestHeaders.Add(HeaderName, HeaderValue);
}

//////////////////////////////////////////////////////////////////////////
// Destruction and reset

void UVaRestRequestJSON::ResetData()
{
	ResetRequestData();
	ResetResponseData();
}

void UVaRestRequestJSON::ResetRequestData()
{
	if (RequestJsonObj != nullptr)
	{
		RequestJsonObj->Reset();
	}
	else
	{
		RequestJsonObj = NewObject<UVaRestJsonObject>();
	}

	HttpRequest = FHttpModule::Get().CreateRequest();
}

void UVaRestRequestJSON::ResetResponseData()
{
	if (ResponseJsonObj != nullptr)
	{
		ResponseJsonObj->Reset();
	}
	else
	{
		ResponseJsonObj = NewObject<UVaRestJsonObject>();
	}

	ResponseHeaders.Empty();
	ResponseCode = -1;

	bIsValidJsonResponse = false;
}

void UVaRestRequestJSON::Cancel()
{
	ContinueAction = nullptr;

	ResetResponseData();
}

//////////////////////////////////////////////////////////////////////////
// JSON data accessors

UVaRestJsonObject* UVaRestRequestJSON::GetRequestObject()
{
	return RequestJsonObj;
}

void UVaRestRequestJSON::SetRequestObject(UVaRestJsonObject* JsonObject)
{
	RequestJsonObj = JsonObject;
}

UVaRestJsonObject* UVaRestRequestJSON::GetResponseObject()
{
	return ResponseJsonObj;
}

void UVaRestRequestJSON::SetResponseObject(UVaRestJsonObject* JsonObject)
{
	ResponseJsonObj = JsonObject;
}

///////////////////////////////////////////////////////////////////////////
// Response data access

FString UVaRestRequestJSON::GetURL()
{
	return HttpRequest->GetURL();
}

ERequestStatus UVaRestRequestJSON::GetStatus()
{
	return ERequestStatus((uint8)HttpRequest->GetStatus());
}

int32 UVaRestRequestJSON::GetResponseCode()
{
	return ResponseCode;
}

FString UVaRestRequestJSON::GetResponseHeader(const FString HeaderName)
{
	FString Result;

	FString* Header = ResponseHeaders.Find(HeaderName);
	if (Header != nullptr)
	{
		Result = *Header;
	}

	return Result;
}

TArray<FString> UVaRestRequestJSON::GetAllResponseHeaders()
{
	TArray<FString> Result;
	for (TMap<FString, FString>::TConstIterator It(ResponseHeaders); It; ++It)
	{
		Result.Add(It.Key() + TEXT(": ") + It.Value());
	}
	return Result;
}

//////////////////////////////////////////////////////////////////////////
// URL processing

void UVaRestRequestJSON::ProcessURL(const FString& Url)
{
	HttpRequest->SetURL(Url);

	ProcessRequest();
}

void UVaRestRequestJSON::ApplyURL(const FString& Url, UVaRestJsonObject *&Result, UObject* WorldContextObject, FLatentActionInfo LatentInfo)
{
	HttpRequest->SetURL(Url);

	// Prepare latent action
	if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject))
	{
		FLatentActionManager& LatentActionManager = World->GetLatentActionManager();
		FVaRestLatentAction<UVaRestJsonObject*> *Kont = LatentActionManager.FindExistingAction<FVaRestLatentAction<UVaRestJsonObject*>>(LatentInfo.CallbackTarget, LatentInfo.UUID);

		if (Kont != nullptr)
		{
			Kont->Cancel();
			LatentActionManager.RemoveActionsForObject(LatentInfo.CallbackTarget);
		}

		LatentActionManager.AddNewAction(LatentInfo.CallbackTarget, LatentInfo.UUID, ContinueAction = new FVaRestLatentAction<UVaRestJsonObject*>(this, Result, LatentInfo));
	}

	ProcessRequest();
}

void UVaRestRequestJSON::ProcessRequest()
{
	// Set verb
	switch (RequestVerb)
	{
	case ERequestVerb::GET:
		HttpRequest->SetVerb(TEXT("GET"));
		break;

	case ERequestVerb::POST:
		HttpRequest->SetVerb(TEXT("POST"));
		break;

	case ERequestVerb::PUT:
		HttpRequest->SetVerb(TEXT("PUT"));
		break;

	case ERequestVerb::DEL:
		HttpRequest->SetVerb(TEXT("DELETE"));
		break;

	case ERequestVerb::CUSTOM:
		HttpRequest->SetVerb(CustomVerb);
		break;

	default:
		break;
	}

	// Set content-type
	switch (RequestContentType)
	{
	case ERequestContentType::x_www_form_urlencoded_url:
	{
		HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/x-www-form-urlencoded"));

		FString UrlParams = "";
		uint16 ParamIdx = 0;

		// Loop through all the values and prepare additional url part
		for (auto RequestIt = RequestJsonObj->GetRootObject()->Values.CreateIterator(); RequestIt; ++RequestIt)
		{
			FString Key = RequestIt.Key();
			FString Value = RequestIt.Value().Get()->AsString();

			if (!Key.IsEmpty() && !Value.IsEmpty())
			{
				UrlParams += ParamIdx == 0 ? "?" : "&";
				UrlParams += UVaRestLibrary::PercentEncode(Key) + "=" + UVaRestLibrary::PercentEncode(Value);
			}

			ParamIdx++;
		}

		// Apply params
		HttpRequest->SetURL(HttpRequest->GetURL() + UrlParams);

		UE_LOG(LogVaRest, Log, TEXT("Request (urlencoded): %s %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL(), *UrlParams);

		break;
	}
	case ERequestContentType::x_www_form_urlencoded_body:
	{
		HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/x-www-form-urlencoded"));

		FString UrlParams = "";
		uint16 ParamIdx = 0;

		// Loop through all the values and prepare additional url part
		for (auto RequestIt = RequestJsonObj->GetRootObject()->Values.CreateIterator(); RequestIt; ++RequestIt)
		{
			FString Key = RequestIt.Key();
			FString Value = RequestIt.Value().Get()->AsString();

			if (!Key.IsEmpty() && !Value.IsEmpty())
			{
				UrlParams += ParamIdx == 0 ? "" : "&";
				UrlParams += UVaRestLibrary::PercentEncode(Key) + "=" + UVaRestLibrary::PercentEncode(Value);
			}

			ParamIdx++;
		}

		// Apply params
		HttpRequest->SetContentAsString(UrlParams);

		UE_LOG(LogVaRest, Log, TEXT("Request (url body): %s %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL(), *UrlParams);

		break;
	}
	case ERequestContentType::binary:
	{
		HttpRequest->SetHeader(TEXT("Content-Type"), BinaryContentType);
		HttpRequest->SetContent(RequestBytes);

		UE_LOG(LogVaRest, Log, TEXT("Request (binary): %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL());

		break;
	}
	case ERequestContentType::json:
	{
		HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json"));

		// Serialize data to json string
		FString OutputString;
		TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString);
		FJsonSerializer::Serialize(RequestJsonObj->GetRootObject().ToSharedRef(), Writer);

		// Set Json content
		HttpRequest->SetContentAsString(OutputString);

		UE_LOG(LogVaRest, Log, TEXT("Request (json): %s %s %sJSON(%s%s%s)JSON"), *HttpRequest->GetVerb(), *HttpRequest->GetURL(), LINE_TERMINATOR, LINE_TERMINATOR, *OutputString, LINE_TERMINATOR);

		break;
	}

	default:
		break;
	}

	// Apply additional headers
	for (TMap<FString, FString>::TConstIterator It(RequestHeaders); It; ++It)
	{
		HttpRequest->SetHeader(It.Key(), It.Value());
	}

	// Bind event
	HttpRequest->OnProcessRequestComplete().BindUObject(this, &UVaRestRequestJSON::OnProcessRequestComplete);

	// Execute the request
	HttpRequest->ProcessRequest();
}

//////////////////////////////////////////////////////////////////////////
// Request callbacks

void UVaRestRequestJSON::OnProcessRequestComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
	// Be sure that we have no data from previous response
	ResetResponseData();

	// Check we have a response and save response code as int32
	if(Response.IsValid())
	{
		ResponseCode = Response->GetResponseCode();
	}

	// Check we have result to process futher
	if (!bWasSuccessful || !Response.IsValid())
	{
		UE_LOG(LogVaRest, Error, TEXT("Request failed (%d): %s"), ResponseCode, *Request->GetURL());

		// Broadcast the result event
		OnRequestFail.Broadcast(this);
		OnStaticRequestFail.Broadcast(this);

		return;
	}

	// Save response data as a string
	ResponseContent = Response->GetContentAsString();

	// Log response state
	UE_LOG(LogVaRest, Log, TEXT("Response (%d): %sJSON(%s%s%s)JSON"), ResponseCode, LINE_TERMINATOR, LINE_TERMINATOR, *ResponseContent, LINE_TERMINATOR);

	// Process response headers
	TArray<FString> Headers = Response->GetAllHeaders();
	for (FString Header : Headers)
	{
		FString Key;
		FString Value;
		if (Header.Split(TEXT(": "), &Key, &Value))
		{
			ResponseHeaders.Add(Key, Value);
		}
	}

	// Try to deserialize data to JSON
	TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(ResponseContent);
	FJsonSerializer::Deserialize(JsonReader, ResponseJsonObj->GetRootObject());

	// Decide whether the request was successful
	bIsValidJsonResponse = bWasSuccessful && ResponseJsonObj->GetRootObject().IsValid();

	// Log errors
	if (!bIsValidJsonResponse)
	{
		if (!ResponseJsonObj->GetRootObject().IsValid())
		{
			// As we assume it's recommended way to use current class, but not the only one,
			// it will be the warning instead of error
			UE_LOG(LogVaRest, Warning, TEXT("JSON could not be decoded!"));
		}
	}

	// Broadcast the result event
	OnRequestComplete.Broadcast(this);
	OnStaticRequestComplete.Broadcast(this);

	// Finish the latent action
	if (ContinueAction)
	{
          FVaRestLatentAction<UVaRestJsonObject*> *K = ContinueAction;
          ContinueAction = nullptr;

          K->Call(ResponseJsonObj);
	}
}

//////////////////////////////////////////////////////////////////////////
// Tags

void UVaRestRequestJSON::AddTag(FName Tag)
{
	if (Tag != NAME_None)
	{
		Tags.AddUnique(Tag);
	}
}

int32 UVaRestRequestJSON::RemoveTag(FName Tag)
{
	return Tags.Remove(Tag);
}

bool UVaRestRequestJSON::HasTag(FName Tag) const
{
	return (Tag != NAME_None) && Tags.Contains(Tag);
}
<|endoftext|>


<commit_before>#include "VRenderGroup.h"
#include "VGlobal.h"

///A regular VSprite that allows instant updates of the texture.
class VRenderSprite : public VSprite
{
public:
	VRenderSprite(float x, float y) : VSprite(x, y) {}
	VRenderSprite(sf::Vector2f position) : VSprite(position) {}

	void SetTexture(const sf::Texture& texture)
	{
		RenderState.texture = &texture;
		FrameSize = texture.getSize();

		vertexArray[0].position = sf::Vector2f();
		vertexArray[1].position = sf::Vector2f((float)FrameSize.x, 0.0f);
		vertexArray[2].position = sf::Vector2f((float)FrameSize.x, (float)FrameSize.y);
		vertexArray[3].position = sf::Vector2f(0.0f, (float)FrameSize.y);

		vertexArray[0].texCoords = vertexArray[0].position;
		vertexArray[1].texCoords = vertexArray[1].position;
		vertexArray[2].texCoords = vertexArray[2].position;
		vertexArray[3].texCoords = vertexArray[3].position;

		disposible = true;
	}
};

VRenderGroup::VRenderGroup(unsigned int maxSize) : VGroup(maxSize)
{
	Sprite = std::make_unique<VRenderSprite>(0.0f, 0.0f);
	type = RENDERGROUP;
}

VRenderGroup::VRenderGroup(float x, float y, unsigned int width, unsigned int height, unsigned int maxSize) : VGroup(maxSize)
{
	Sprite = std::make_unique<VRenderSprite>(x, y);
	Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
	Sprite->Radius = Sprite->Size.x < Sprite->Size.y ? Sprite->Size.x / 2 : Sprite->Size.y / 2;

	renderTex.create(width, height);

	type = RENDERGROUP;
}

VRenderGroup::VRenderGroup(sf::Vector2f position, sf::Vector2u size, unsigned int maxSize) : VGroup(maxSize)
{
	Sprite = std::make_unique<VRenderSprite>(position);
	Sprite->Size = sf::Vector2f(size);
	Sprite->Radius = Sprite->Size.x < Sprite->Size.y ? Sprite->Size.x / 2 : Sprite->Size.y / 2;

	renderTex.create(size.x, size.y);

	type = RENDERGROUP;
}

void VRenderGroup::updateTransform()
{
	sf::View NewView = renderTex.getDefaultView();

	if (RenderViewTransform)
	{
		NewView.move(Sprite->Position + Sprite->Origin - Sprite->Offset);
		NewView.rotate(Sprite->Angle);
		NewView.setSize(sf::Vector2f(Sprite->Size.x * Sprite->Scale.x, Sprite->Size.y * Sprite->Scale.y));
	}

	renderTex.setView(NewView);
}

void VRenderGroup::updateTexture(const sf::Texture& texture)
{
	VRenderSprite* render = dynamic_cast<VRenderSprite*>(Sprite.get());
	render->SetTexture(texture);
}

void VRenderGroup::Resize(int width, int height)
{
	postProcessTex.create(width, height);
	renderTex.create(width, height);
	Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}

void VRenderGroup::Kill()
{
	VSUPERCLASS::Kill();
	Sprite->Kill();
}

void VRenderGroup::Revive()
{
	VSUPERCLASS::Revive();
	Sprite->Revive();
}

void VRenderGroup::Destroy()
{
	VSUPERCLASS::Destroy();

	Sprite = nullptr;
	PostEffect = nullptr;
}

const sf::Texture& VRenderGroup::GetTexture()
{
	renderTex.clear(sf::Color::Transparent);
	VSUPERCLASS::Draw(renderTex);
	renderTex.display();

	return renderTex.getTexture();
}

void VRenderGroup::Update(float dt)
{
	VSUPERCLASS::Update(dt);
	updateTransform();
	Sprite->Update(dt);

	if (PostEffect != nullptr)
	{
		PostEffect->Update(dt);
	}
}

void VRenderGroup::Draw(sf::RenderTarget& RenderTarget)
{
#ifdef _DEBUG
	bool drawDebug = VGlobal::p()->DrawDebug;
	VGlobal::p()->DrawDebug = false;
#endif

	renderTex.clear(BackgroundTint);
	VSUPERCLASS::Draw(renderTex);
	renderTex.display();

	if (RenderOutside) VSUPERCLASS::Draw(RenderTarget);

	if (PostEffect != nullptr && VPostEffectBase::isSupported())
	{
		if (postProcessTex.getSize().x == 0 || postProcessTex.getSize().y == 0)
		{
			postProcessTex.create(renderTex.getSize().x, renderTex.getSize().y);
		}

		postProcessTex.clear(sf::Color::Transparent);
		PostEffect->Apply(renderTex.getTexture(), postProcessTex);
		postProcessTex.display();

		updateTexture(postProcessTex.getTexture());
	}
	else
	{
		updateTexture(renderTex.getTexture());
	}

#ifdef _DEBUG
	VGlobal::p()->DrawDebug = drawDebug;
#endif

	Sprite->Draw(RenderTarget);
}<commit_msg>Fix from KALQL8TR: Rendering elemented of the group outside the render texture occurs after rendering the processed sprite. (Should change to make user choose between pre/post render).<commit_after>#include "VRenderGroup.h"
#include "VGlobal.h"

///A regular VSprite that allows instant updates of the texture.
class VRenderSprite : public VSprite
{
public:
	VRenderSprite(float x, float y) : VSprite(x, y) {}
	VRenderSprite(sf::Vector2f position) : VSprite(position) {}

	void SetTexture(const sf::Texture& texture)
	{
		RenderState.texture = &texture;
		FrameSize = texture.getSize();

		vertexArray[0].position = sf::Vector2f();
		vertexArray[1].position = sf::Vector2f((float)FrameSize.x, 0.0f);
		vertexArray[2].position = sf::Vector2f((float)FrameSize.x, (float)FrameSize.y);
		vertexArray[3].position = sf::Vector2f(0.0f, (float)FrameSize.y);

		vertexArray[0].texCoords = vertexArray[0].position;
		vertexArray[1].texCoords = vertexArray[1].position;
		vertexArray[2].texCoords = vertexArray[2].position;
		vertexArray[3].texCoords = vertexArray[3].position;

		disposible = true;
	}
};

VRenderGroup::VRenderGroup(unsigned int maxSize) : VGroup(maxSize)
{
	Sprite = std::make_unique<VRenderSprite>(0.0f, 0.0f);
	type = RENDERGROUP;
}

VRenderGroup::VRenderGroup(float x, float y, unsigned int width, unsigned int height, unsigned int maxSize) : VGroup(maxSize)
{
	Sprite = std::make_unique<VRenderSprite>(x, y);
	Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
	Sprite->Radius = Sprite->Size.x < Sprite->Size.y ? Sprite->Size.x / 2 : Sprite->Size.y / 2;

	renderTex.create(width, height);

	type = RENDERGROUP;
}

VRenderGroup::VRenderGroup(sf::Vector2f position, sf::Vector2u size, unsigned int maxSize) : VGroup(maxSize)
{
	Sprite = std::make_unique<VRenderSprite>(position);
	Sprite->Size = sf::Vector2f(size);
	Sprite->Radius = Sprite->Size.x < Sprite->Size.y ? Sprite->Size.x / 2 : Sprite->Size.y / 2;

	renderTex.create(size.x, size.y);

	type = RENDERGROUP;
}

void VRenderGroup::updateTransform()
{
	sf::View NewView = renderTex.getDefaultView();

	if (RenderViewTransform)
	{
		NewView.move(Sprite->Position + Sprite->Origin - Sprite->Offset);
		NewView.rotate(Sprite->Angle);
		NewView.setSize(sf::Vector2f(Sprite->Size.x * Sprite->Scale.x, Sprite->Size.y * Sprite->Scale.y));
	}

	renderTex.setView(NewView);
}

void VRenderGroup::updateTexture(const sf::Texture& texture)
{
	VRenderSprite* render = dynamic_cast<VRenderSprite*>(Sprite.get());
	render->SetTexture(texture);
}

void VRenderGroup::Resize(int width, int height)
{
	postProcessTex.create(width, height);
	renderTex.create(width, height);
	Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}

void VRenderGroup::Kill()
{
	VSUPERCLASS::Kill();
	Sprite->Kill();
}

void VRenderGroup::Revive()
{
	VSUPERCLASS::Revive();
	Sprite->Revive();
}

void VRenderGroup::Destroy()
{
	VSUPERCLASS::Destroy();

	Sprite = nullptr;
	PostEffect = nullptr;
}

const sf::Texture& VRenderGroup::GetTexture()
{
	renderTex.clear(sf::Color::Transparent);
	VSUPERCLASS::Draw(renderTex);
	renderTex.display();

	return renderTex.getTexture();
}

void VRenderGroup::Update(float dt)
{
	VSUPERCLASS::Update(dt);
	updateTransform();
	Sprite->Update(dt);

	if (PostEffect != nullptr)
	{
		PostEffect->Update(dt);
	}
}

void VRenderGroup::Draw(sf::RenderTarget& RenderTarget)
{
#ifdef _DEBUG
	bool drawDebug = VGlobal::p()->DrawDebug;
	VGlobal::p()->DrawDebug = false;
#endif

	renderTex.clear(BackgroundTint);
	VSUPERCLASS::Draw(renderTex);
	renderTex.display();

	if (PostEffect != nullptr && VPostEffectBase::isSupported())
	{
		if (postProcessTex.getSize().x == 0 || postProcessTex.getSize().y == 0)
		{
			postProcessTex.create(renderTex.getSize().x, renderTex.getSize().y);
		}

		postProcessTex.clear(sf::Color::Transparent);
		PostEffect->Apply(renderTex.getTexture(), postProcessTex);
		postProcessTex.display();

		updateTexture(postProcessTex.getTexture());
	}
	else
	{
		updateTexture(renderTex.getTexture());
	}

#ifdef _DEBUG
	VGlobal::p()->DrawDebug = drawDebug;
#endif

	Sprite->Draw(RenderTarget);

	if (RenderOutside) VSUPERCLASS::Draw(RenderTarget);
}<|endoftext|>


<commit_before>// Validator.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <vector>
#include <unordered_set>
#include <string>
#include <fstream>
#include <functional>
#include "Option.h"
#include "Scorer.h"
#include "../common/Graph.h"
#include "../common/Motif.h"
#include "../common/SubjectInfo.h"
#include <boost/filesystem.hpp>

using namespace std;

Graph loadGraph(istream& is) {
	Graph res;
	res.readFromStream(is);
	return res;
}

vector<vector<Graph> > loadData(const string& pre, const int n, const int m) {
	vector<vector<Graph> > res;
	res.reserve(n);
	for(int i = 0; i < n; ++i) {
		vector<Graph> temp;
		temp.reserve(m);
		for(int j = 0; j < m; ++j) {
			ifstream fin(pre + to_string(i) + "-" + to_string(j) + ".txt");
			temp.push_back(loadGraph(fin));
		}
		res.push_back(move(temp));
	}
	return res;
}

vector<vector<Graph> > loadData(
	const string& folder, const vector<int>& types, const int nSub, const int nSnap, const int nSkip = 0)
{
	boost::filesystem::path root(folder);
	if(!exists(root)) {
		cerr << "cannot open graph folder: " << folder << endl;
		throw invalid_argument("cannot open graph folder: " + folder);
	}
	size_t limitSub = nSub >= 0 ? nSub : numeric_limits<size_t>::max();
	size_t limitSnp = nSnap > 0 ? nSnap : numeric_limits<size_t>::max();
	unordered_set<int> validType(types.begin(), types.end());

	// sort up the file list (ensure the file order)
	map<decltype(SubjectInfo::id), vector<string>> id2fn;
	for(auto it = boost::filesystem::directory_iterator(root);
		it != boost::filesystem::directory_iterator(); ++it)
	{
		SubjectInfo sub;
		string fn = it->path().filename().string();
		if(boost::filesystem::is_regular_file(it->status()) && sub.parseFromFilename(fn)) {
			// check type
			if(validType.find(sub.type) == validType.end())
				continue;
			id2fn[sub.id].push_back(move(fn));
		}
	}
	// load data
	vector<vector<Graph> > res(min(limitSub, id2fn.size()));
	int cntSub = 0;
	size_t pres = 0;
	for(auto& sfp : id2fn) {
		if(++cntSub <= nSkip)
			continue;
		else if(pres >= limitSub)
			break;
		//		cout <<"rank: "<<rank<< " type: " << types[0] << " id: " << sfp.first << endl;
		// sort the snapshot files
		if(sfp.second.size() <= limitSnp) {
			sort(sfp.second.begin(), sfp.second.end());
		} else {
			auto it = sfp.second.begin() + limitSnp;
			partial_sort(sfp.second.begin(), it, sfp.second.end());
		}
		vector<Graph>& vec = res[pres++];
		size_t cntSnp = 0;
		for(auto& fn : sfp.second) {
			if(++cntSnp > limitSnp)
				break;
			ifstream fin(folder + fn);
			if(!fin) {
				cerr << "cannot open file: " << fn << endl;
			}
			vec.push_back(loadGraph(fin));
		}
	}
	return res;
}

Motif parseMotif(const std::string& line) {
	size_t plast = line.find('\t') + 1;
	size_t p = line.find('\t', plast);
	int nEdge = stoi(line.substr(plast, p - plast));
	plast = p + 2;
	Motif m;
	while(nEdge--) {
		size_t pmid = line.find(',', plast);
		int s = stoi(line.substr(plast, pmid - plast));
		pmid++;
		p = line.find(')', pmid);
		int d = stoi(line.substr(pmid, p - pmid));
		m.addEdge(s, d);
		plast = p + 3;
	}
	return m;
}

bool existOnSub(const std::vector<Graph>& gs, const Motif& m, const double theta)
{
	int cnt = 0;
	int limit = static_cast<int>(ceil(gs.size()*theta));
	for(auto& g : gs) {
		if(g.testMotif(m)) {
			if(++cnt >= limit)
				return true;
		}
	}
	return false;
}

double probOnGS(const vector<vector<Graph>>& gs, const Motif& m, const double theta)
{
	int cnt = 0;
	for(auto& l : gs)
		if(existOnSub(l, m, theta))
			++cnt;
	return static_cast<double>(cnt) / gs.size();
}

template<typename T>
ostream& operator<<(ostream& os, const vector<T>& param) {
	for(auto& p : param)
		os << p << " ";
	return os;
}

int main(int argc, char* argv[])
{
	Option opt;
	if(!opt.parseInput(argc, argv)) {
		return 1;
	}

	function<double(const double, const double)> objFun;
	if(opt.funName == "diff") {
		objFun = bind(&Scorer::diff, placeholders::_1, placeholders::_2, opt.alpha);
	} else if(opt.funName == "ratio") {
		objFun = Scorer::ratio;
	}

	int nPosSub = opt.nPosInd, nPosSkip = 0;
	int nNegSub = opt.nNegInd, nNegSkip = 0;
	cout << "Loading graphs on rank..." << endl;
	vector<vector<Graph> > gPos = loadData(opt.graphFolder, opt.typePos, nPosSub, opt.nSnapshot, nPosSkip);
	cout << "  # positive subjects: " << gPos.size() << endl;
	vector<vector<Graph> > gNeg = loadData(opt.graphFolder, opt.typeNeg, nNegSub, opt.nSnapshot, nNegSkip);
	cout << "  # negative subjects: " << gNeg.size() << endl;

	string line;
	cout << "Format:\n"
		"sth	nEdge	(a,b) (c,d) (...)"
		"Waiting for input (one per line): "<< endl;
	while(getline(cin, line)) {
		Motif m;
		try {
			m = parseMotif(line);
		} catch(...) {
			cout << "cannot parse given motif." << endl;
			continue;
		}
		double fPos = probOnGS(gPos, m, opt.theta);
		double fNeg = probOnGS(gNeg, m, opt.theta);
		double score = objFun(fPos, fNeg);
		cout << "fPos=" << fPos << ", fNeg=" << fNeg << ", score=" << score << endl;
	}
	return 0;
}

<commit_msg>display fix<commit_after>// Validator.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <vector>
#include <unordered_set>
#include <string>
#include <fstream>
#include <functional>
#include "Option.h"
#include "Scorer.h"
#include "../common/Graph.h"
#include "../common/Motif.h"
#include "../common/SubjectInfo.h"
#include <boost/filesystem.hpp>

using namespace std;

Graph loadGraph(istream& is) {
	Graph res;
	res.readFromStream(is);
	return res;
}

vector<vector<Graph> > loadData(const string& pre, const int n, const int m) {
	vector<vector<Graph> > res;
	res.reserve(n);
	for(int i = 0; i < n; ++i) {
		vector<Graph> temp;
		temp.reserve(m);
		for(int j = 0; j < m; ++j) {
			ifstream fin(pre + to_string(i) + "-" + to_string(j) + ".txt");
			temp.push_back(loadGraph(fin));
		}
		res.push_back(move(temp));
	}
	return res;
}

vector<vector<Graph> > loadData(
	const string& folder, const vector<int>& types, const int nSub, const int nSnap, const int nSkip = 0)
{
	boost::filesystem::path root(folder);
	if(!exists(root)) {
		cerr << "cannot open graph folder: " << folder << endl;
		throw invalid_argument("cannot open graph folder: " + folder);
	}
	size_t limitSub = nSub >= 0 ? nSub : numeric_limits<size_t>::max();
	size_t limitSnp = nSnap > 0 ? nSnap : numeric_limits<size_t>::max();
	unordered_set<int> validType(types.begin(), types.end());

	// sort up the file list (ensure the file order)
	map<decltype(SubjectInfo::id), vector<string>> id2fn;
	for(auto it = boost::filesystem::directory_iterator(root);
		it != boost::filesystem::directory_iterator(); ++it)
	{
		SubjectInfo sub;
		string fn = it->path().filename().string();
		if(boost::filesystem::is_regular_file(it->status()) && sub.parseFromFilename(fn)) {
			// check type
			if(validType.find(sub.type) == validType.end())
				continue;
			id2fn[sub.id].push_back(move(fn));
		}
	}
	// load data
	vector<vector<Graph> > res(min(limitSub, id2fn.size()));
	int cntSub = 0;
	size_t pres = 0;
	for(auto& sfp : id2fn) {
		if(++cntSub <= nSkip)
			continue;
		else if(pres >= limitSub)
			break;
		//		cout <<"rank: "<<rank<< " type: " << types[0] << " id: " << sfp.first << endl;
		// sort the snapshot files
		if(sfp.second.size() <= limitSnp) {
			sort(sfp.second.begin(), sfp.second.end());
		} else {
			auto it = sfp.second.begin() + limitSnp;
			partial_sort(sfp.second.begin(), it, sfp.second.end());
		}
		vector<Graph>& vec = res[pres++];
		size_t cntSnp = 0;
		for(auto& fn : sfp.second) {
			if(++cntSnp > limitSnp)
				break;
			ifstream fin(folder + fn);
			if(!fin) {
				cerr << "cannot open file: " << fn << endl;
			}
			vec.push_back(loadGraph(fin));
		}
	}
	return res;
}

Motif parseMotif(const std::string& line) {
	size_t plast = line.find('\t') + 1;
	size_t p = line.find('\t', plast);
	int nEdge = stoi(line.substr(plast, p - plast));
	plast = p + 2;
	Motif m;
	while(nEdge--) {
		size_t pmid = line.find(',', plast);
		int s = stoi(line.substr(plast, pmid - plast));
		pmid++;
		p = line.find(')', pmid);
		int d = stoi(line.substr(pmid, p - pmid));
		m.addEdge(s, d);
		plast = p + 3;
	}
	return m;
}

bool existOnSub(const std::vector<Graph>& gs, const Motif& m, const double theta)
{
	int cnt = 0;
	int limit = static_cast<int>(ceil(gs.size()*theta));
	for(auto& g : gs) {
		if(g.testMotif(m)) {
			if(++cnt >= limit)
				return true;
		}
	}
	return false;
}

double probOnGS(const vector<vector<Graph>>& gs, const Motif& m, const double theta)
{
	int cnt = 0;
	for(auto& l : gs)
		if(existOnSub(l, m, theta))
			++cnt;
	return static_cast<double>(cnt) / gs.size();
}

template<typename T>
ostream& operator<<(ostream& os, const vector<T>& param) {
	for(auto& p : param)
		os << p << " ";
	return os;
}

int main(int argc, char* argv[])
{
	Option opt;
	if(!opt.parseInput(argc, argv)) {
		return 1;
	}

	function<double(const double, const double)> objFun;
	if(opt.funName == "diff") {
		objFun = bind(&Scorer::diff, placeholders::_1, placeholders::_2, opt.alpha);
	} else if(opt.funName == "ratio") {
		objFun = Scorer::ratio;
	}

	int nPosSub = opt.nPosInd, nPosSkip = 0;
	int nNegSub = opt.nNegInd, nNegSkip = 0;
	cout << "Loading graphs on rank..." << endl;
	vector<vector<Graph> > gPos = loadData(opt.graphFolder, opt.typePos, nPosSub, opt.nSnapshot, nPosSkip);
	cout << "  # positive subjects: " << gPos.size() << endl;
	vector<vector<Graph> > gNeg = loadData(opt.graphFolder, opt.typeNeg, nNegSub, opt.nSnapshot, nNegSkip);
	cout << "  # negative subjects: " << gNeg.size() << endl;

	string line;
	cout << "Format:\n"
		"XXX	nEdge	(a,b) (c,d) (...)\n"
		"Waiting for input (one per line): "<< endl;
	while(getline(cin, line)) {
		Motif m;
		try {
			m = parseMotif(line);
		} catch(...) {
			cout << "cannot parse given motif." << endl;
			continue;
		}
		double fPos = probOnGS(gPos, m, opt.theta);
		double fNeg = probOnGS(gNeg, m, opt.theta);
		double score = objFun(fPos, fNeg);
		cout << "fPos=" << fPos << ", fNeg=" << fNeg << ", score=" << score << endl;
	}
	return 0;
}

<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <iostream>
#include <QCloseEvent>
#include <chrono>
#include <thread>
#include "icononbuttonhandler.h"
#include "inputwindow.h"

using namespace std;
using namespace cv;

/**
 * @brief MainWindow::MainWindow
 * Constructor
 * @param parent a QWidget variable
 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow){
    ui->setupUi(this);
    video_slider = findChild<QSlider*>("videoSlider");
    iconOnButtonHandler = new IconOnButtonHandler();
    iconOnButtonHandler->set_pictures_to_buttons(ui);

    fileHandler = new FileHandler();
    setShortcuts();

    mvideo_player = new video_player();
    QObject::connect(mvideo_player, SIGNAL(processedImage(QImage)),
                                  this, SLOT(update_video(QImage)));
    QObject::connect(mvideo_player, SIGNAL(currentFrame(int)),
                                  this, SLOT(set_video_slider_pos(int)));

    //Used for rescaling the source image for video playback
    mvideo_player->set_frame_height(ui->videoFrame->height());
    mvideo_player->set_frame_width(ui->videoFrame->width());
}

/**
 * @brief MainWindow::~MainWindow
 * Destructor
 */

MainWindow::~MainWindow() {

    delete iconOnButtonHandler;
    delete fileHandler;
    delete mvideo_player;
    delete ui;
}

/**
 * @brief MainWindow::setShortcuts
 * Function to set shortcuts on actions
 */
void MainWindow::setShortcuts(){
    ui->actionExit->setShortcut(tr("Ctrl+e"));
}

/**
 * @brief MainWindow::setStatusBar
 * @param status text to show in the statusbar
 * @param timer time to show it in the bar in ms, 750ms is standard
 */
void MainWindow::setStatusBar(string status, int timer = 750){
    ui->statusBar->showMessage(QString::fromStdString(status), timer);
}

/**
 * @brief MainWindow::on_fastBackwardButton_clicked
 * The button supposed to play the video slower
 *
 */
void MainWindow::on_fastBackwardButton_clicked(){

}

/**
 * @brief MainWindow::on_playPauseButton_clicked
 * The button supposed to play and pause the video
 */
void MainWindow::on_playPauseButton_clicked() {
    if (mvideo_player->is_paused() || mvideo_player->is_stopped()) {
        iconOnButtonHandler->setIcon("pause", ui->playPauseButton);//changes the icon on the play button to a pause-icon
        mvideo_player->start();
    } else {
        setStatusBar("Playing");
        iconOnButtonHandler->setIcon("play", ui->playPauseButton);
        mvideo_player->play_pause();
        mvideo_player->wait();
    }
}

/**
 * @brief MainWindow::on_fastForwardButton_clicked
 * The button supposed to play the video faster
 */
void MainWindow::on_fastForwardButton_clicked(){

}

/**
 * @brief MainWindow::on_stopButton_clicked
 * The button supposed to stop the video
 */
void MainWindow::on_stopButton_clicked() {
    setStatusBar("Stopped");
    if (!mvideo_player->is_paused()) {
        iconOnButtonHandler->setIcon("play", ui->playPauseButton);
    }

    mvideo_player->stop_video();
}

/**
 * @brief MainWindow::on_nextFrameButton_clicked
 * The button supposed to play the next frame of the video
 */
void MainWindow::on_nextFrameButton_clicked() {
    if (mvideo_player->is_paused()) {
        mvideo_player->next_frame();
    }
}

/**
 * @brief MainWindow::on_nextFrameButton_clicked
 * The button supposed to play the previous frame of the video
 */
void MainWindow::on_previousFrameButton_clicked() {
    if (mvideo_player->is_paused()) {
        mvideo_player->previous_frame();
    }
}

/**
 * @brief MainWindow::update_video
 * Sets the videoFrame pixmap to the current frame from video
 * @param frame
 */
void MainWindow::update_video(QImage frame) {

    ui->videoFrame->setPixmap(QPixmap::fromImage(frame));
}

/**
 * @brief MainWindow::set_video_slider_pos
 * Sets the position of slider in video to position pos
 * @param pos
 */
void MainWindow::set_video_slider_pos(int pos) {
    if (pos <= video_slider->maximum()) {
        video_slider->setSliderPosition(pos);
    }
}

/**
 * @brief MainWindow::resizeEvent
 * Used for rescaling the source image for video playback
 * @param event
 */
void MainWindow::resizeEvent(QResizeEvent* event) {
   QMainWindow::resizeEvent(event);
   mvideo_player->set_frame_height(ui->videoFrame->height());
   mvideo_player->set_frame_width(ui->videoFrame->width());
}

/**
 * @brief MainWindow::on_videoSlider_valueChanged
 * Update the slider to where the mouse is
 * @param newPos current position of the slider
 */
void MainWindow::on_videoSlider_valueChanged(int newPos){
    // Make slider to follow the mouse directly and not by pageStep steps
    Qt::MouseButtons btns = QApplication::mouseButtons();
    QPoint localMousePos = ui->videoSlider->mapFromGlobal(QCursor::pos());
    bool clickOnSlider = (btns & Qt::LeftButton) &&
                         (localMousePos.x() >= 0 && localMousePos.y() >= 0 &&
                          localMousePos.x() < ui->videoSlider->size().width() &&
                          localMousePos.y() < ui->videoSlider->size().height());
    if (clickOnSlider)
    {
        // Attention! The following works only for Horizontal, Left-to-right sliders
        float posRatio = localMousePos.x() / (float )ui->videoSlider->size().width();
        int sliderRange = ui->videoSlider->maximum() - ui->videoSlider->minimum();
        int sliderPosUnderMouse = ui->videoSlider->minimum() + sliderRange * posRatio;
        if (sliderPosUnderMouse != newPos)
        {
            ui->videoSlider->setValue(sliderPosUnderMouse);
            return;
        }
    }
}
/**
 * @brief MainWindow::closeEvent
 * asks if you are sure you want to quit.
 * @param event closing
 */
void MainWindow::closeEvent (QCloseEvent *event){
    QMessageBox::StandardButton resBtn = QMessageBox::question( this, "Exit",
                                                                tr("Are you sure you want to quit?\n"),
                                                                QMessageBox::No | QMessageBox::Yes,
                                                                QMessageBox::No);

    if (resBtn != QMessageBox::Yes) {
        event->ignore();
    } else {
        event->accept();
    }
}
/**
 * @brief MainWindow::on_actionExit_triggered
 * sends a closeEvent when you press exit
 */
void MainWindow::on_actionExit_triggered(){
    this->close();
}

/**
 * @brief MainWindow::on_bookmarkButton_clicked
 * the button supposed to add a bookmark
 */
void MainWindow::on_bookmarkButton_clicked(){
    // The code here is only temporary and should be moved/removed
    // once a proper video selector is added
    mvideo_player->load_video("seq_01.mp4");
    iconOnButtonHandler->setIcon("pause", ui->playPauseButton);
    video_slider->setMaximum(mvideo_player->get_num_frames());
    mvideo_player->set_playback_frame(700);
}

/**
 * @brief MainWindow::on_actionAddProject_triggered
 */
void MainWindow::on_actionAddProject_triggered() {
    ACTION action = ADD_PROJECT;
    inputWindow = new inputwindow(this, action, "Project name:");
    inputWindow->show();
}

/**
 * @brief MainWindow::inputSwitchCase
 * @param input the input from the user
 * @param action the action that was triggered earlier
 */
void MainWindow::inputSwitchCase(ACTION action, QString qInput) {
    std::string input = qInput.toStdString();
    switch(action){
        case ADD_PROJECT:{
            fileHandler->createProject(input);
            QTreeWidgetItem *projectInTree = new QTreeWidgetItem();
            projectInTree->setText(0, qInput);
            ui->ProjectTree->addTopLevelItem(projectInTree);
            break;
        }
        case CANCELL:
            break;
        default:
            break;

    }
    delete inputWindow;
}

void MainWindow::on_ProjectTree_itemClicked(QTreeWidgetItem *item, int column) {

}
<commit_msg>One more comment<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <iostream>
#include <QCloseEvent>
#include <chrono>
#include <thread>
#include "icononbuttonhandler.h"
#include "inputwindow.h"

using namespace std;
using namespace cv;

/**
 * @brief MainWindow::MainWindow
 * Constructor
 * @param parent a QWidget variable
 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow){
    ui->setupUi(this);
    video_slider = findChild<QSlider*>("videoSlider");
    iconOnButtonHandler = new IconOnButtonHandler();
    iconOnButtonHandler->set_pictures_to_buttons(ui);

    fileHandler = new FileHandler();
    setShortcuts();

    mvideo_player = new video_player();
    QObject::connect(mvideo_player, SIGNAL(processedImage(QImage)),
                                  this, SLOT(update_video(QImage)));
    QObject::connect(mvideo_player, SIGNAL(currentFrame(int)),
                                  this, SLOT(set_video_slider_pos(int)));

    //Used for rescaling the source image for video playback
    mvideo_player->set_frame_height(ui->videoFrame->height());
    mvideo_player->set_frame_width(ui->videoFrame->width());
}

/**
 * @brief MainWindow::~MainWindow
 * Destructor
 */

MainWindow::~MainWindow() {

    delete iconOnButtonHandler;
    delete fileHandler;
    delete mvideo_player;
    delete ui;
}

/**
 * @brief MainWindow::setShortcuts
 * Function to set shortcuts on actions
 */
void MainWindow::setShortcuts(){
    ui->actionExit->setShortcut(tr("Ctrl+e"));
}

/**
 * @brief MainWindow::setStatusBar
 * @param status text to show in the statusbar
 * @param timer time to show it in the bar in ms, 750ms is standard
 */
void MainWindow::setStatusBar(string status, int timer = 750){
    ui->statusBar->showMessage(QString::fromStdString(status), timer);
}

/**
 * @brief MainWindow::on_fastBackwardButton_clicked
 * The button supposed to play the video slower
 *
 */
void MainWindow::on_fastBackwardButton_clicked(){

}

/**
 * @brief MainWindow::on_playPauseButton_clicked
 * The button supposed to play and pause the video
 */
void MainWindow::on_playPauseButton_clicked() {
    if (mvideo_player->is_paused() || mvideo_player->is_stopped()) {
        iconOnButtonHandler->setIcon("pause", ui->playPauseButton);//changes the icon on the play button to a pause-icon
        mvideo_player->start();
    } else {
        setStatusBar("Playing");
        iconOnButtonHandler->setIcon("play", ui->playPauseButton);
        mvideo_player->play_pause();
        mvideo_player->wait();
    }
}

/**
 * @brief MainWindow::on_fastForwardButton_clicked
 * The button supposed to play the video faster
 */
void MainWindow::on_fastForwardButton_clicked(){

}

/**
 * @brief MainWindow::on_stopButton_clicked
 * The button supposed to stop the video
 */
void MainWindow::on_stopButton_clicked() {
    setStatusBar("Stopped");
    if (!mvideo_player->is_paused()) {
        iconOnButtonHandler->setIcon("play", ui->playPauseButton);
    }

    mvideo_player->stop_video();
}

/**
 * @brief MainWindow::on_nextFrameButton_clicked
 * The button supposed to play the next frame of the video
 */
void MainWindow::on_nextFrameButton_clicked() {
    if (mvideo_player->is_paused()) {
        mvideo_player->next_frame();
    }
}

/**
 * @brief MainWindow::on_nextFrameButton_clicked
 * The button supposed to play the previous frame of the video
 */
void MainWindow::on_previousFrameButton_clicked() {
    if (mvideo_player->is_paused()) {
        mvideo_player->previous_frame();
    }
}

/**
 * @brief MainWindow::update_video
 * Sets the videoFrame pixmap to the current frame from video
 * @param frame
 */
void MainWindow::update_video(QImage frame) {

    ui->videoFrame->setPixmap(QPixmap::fromImage(frame));
}

/**
 * @brief MainWindow::set_video_slider_pos
 * Sets the position of slider in video to position pos
 * @param pos
 */
void MainWindow::set_video_slider_pos(int pos) {
    if (pos <= video_slider->maximum()) {
        video_slider->setSliderPosition(pos);
    }
}

/**
 * @brief MainWindow::resizeEvent
 * Used for rescaling the source image for video playback
 * @param event
 */
void MainWindow::resizeEvent(QResizeEvent* event) {
   QMainWindow::resizeEvent(event);
   mvideo_player->set_frame_height(ui->videoFrame->height());
   mvideo_player->set_frame_width(ui->videoFrame->width());
}

/**
 * @brief MainWindow::on_videoSlider_valueChanged
 * Update the slider to where the mouse is
 * @param newPos current position of the slider
 */
void MainWindow::on_videoSlider_valueChanged(int newPos){
    // Make slider to follow the mouse directly and not by pageStep steps
    Qt::MouseButtons btns = QApplication::mouseButtons();
    QPoint localMousePos = ui->videoSlider->mapFromGlobal(QCursor::pos());
    bool clickOnSlider = (btns & Qt::LeftButton) &&
                         (localMousePos.x() >= 0 && localMousePos.y() >= 0 &&
                          localMousePos.x() < ui->videoSlider->size().width() &&
                          localMousePos.y() < ui->videoSlider->size().height());
    if (clickOnSlider)
    {
        // Attention! The following works only for Horizontal, Left-to-right sliders
        float posRatio = localMousePos.x() / (float )ui->videoSlider->size().width();
        int sliderRange = ui->videoSlider->maximum() - ui->videoSlider->minimum();
        int sliderPosUnderMouse = ui->videoSlider->minimum() + sliderRange * posRatio;
        if (sliderPosUnderMouse != newPos)
        {
            ui->videoSlider->setValue(sliderPosUnderMouse);
            return;
        }
    }
}
/**
 * @brief MainWindow::closeEvent
 * asks if you are sure you want to quit.
 * @param event closing
 */
void MainWindow::closeEvent (QCloseEvent *event){
    QMessageBox::StandardButton resBtn = QMessageBox::question( this, "Exit",
                                                                tr("Are you sure you want to quit?\n"),
                                                                QMessageBox::No | QMessageBox::Yes,
                                                                QMessageBox::No);

    if (resBtn != QMessageBox::Yes) {
        event->ignore();
    } else {
        event->accept();
    }
}
/**
 * @brief MainWindow::on_actionExit_triggered
 * sends a closeEvent when you press exit
 */
void MainWindow::on_actionExit_triggered(){
    this->close();
}

/**
 * @brief MainWindow::on_bookmarkButton_clicked
 * the button supposed to add a bookmark
 */
void MainWindow::on_bookmarkButton_clicked(){
    // The code here is only temporary and should be moved/removed
    // once a proper video selector is added
    mvideo_player->load_video("seq_01.mp4");
    iconOnButtonHandler->setIcon("pause", ui->playPauseButton);
    video_slider->setMaximum(mvideo_player->get_num_frames());
    mvideo_player->set_playback_frame(700);
}

/**
 * @brief MainWindow::on_actionAddProject_triggered
 */
void MainWindow::on_actionAddProject_triggered() {
    ACTION action = ADD_PROJECT;
    inputWindow = new inputwindow(this, action, "Project name:");
    inputWindow->show();
}

/**
 * @brief MainWindow::inputSwitchCase
 * @param input the input from the user
 * @param action the action that was triggered earlier
 */
void MainWindow::inputSwitchCase(ACTION action, QString qInput) {
    std::string input = qInput.toStdString();
    switch(action){
        case ADD_PROJECT:{
            fileHandler->createProject(input);
            QTreeWidgetItem *projectInTree = new QTreeWidgetItem();
            projectInTree->setText(0, qInput);
            ui->ProjectTree->addTopLevelItem(projectInTree);
            break;
        }
        case CANCELL:
            break;
        default:
            break;

    }
    delete inputWindow;
}
/**
 * @brief MainWindow::on_ProjectTree_itemClicked
 * @param item the item in the projectTree that was clicked
 * @param column the column in the tree
 */
void MainWindow::on_ProjectTree_itemClicked(QTreeWidgetItem *item, int column) {

}
<|endoftext|>