<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dependency.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:02:28 $
 *
 *  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 _CODEMAKER_DEPENDENCY_HXX_
#define _CODEMAKER_DEPENDENCY_HXX_

#include    <hash_map>

#ifndef _REGISTRY_REGISTRY_HXX_
#include    <registry/registry.hxx>
#endif
#ifndef __REGISTRY_REFLREAD_HXX__
#include    <registry/reflread.hxx>
#endif

#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#include    <codemaker/typemanager.hxx>
#endif
#ifndef _CODEMAKER_GLOBAL_HXX_
#include    <codemaker/global.hxx>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#define TYPEUSE_NORMAL      0x0001
#define TYPEUSE_SUPER       0x0002
#define TYPEUSE_MEMBER      0x0004
#define TYPEUSE_INPARAM     0x0008
#define TYPEUSE_OUTPARAM    0x0010
#define TYPEUSE_INOUTPARAM  0x0020
#define TYPEUSE_RETURN      0x0040
#define TYPEUSE_EXCEPTION   0x0080
#define TYPEUSE_SCOPE       0x0100

/**
 * Flag shows the state of the code generation. If the Flag is set
 * the code for this type is generated.
 */
#define CODEGEN_DEFAULT     0x0001

struct TypeUsing
{
    TypeUsing(const ::rtl::OString& type, sal_uInt16 use)
        : m_type(type)
        , m_use(use)
        {}

    ::rtl::OString  m_type;
    sal_uInt16      m_use;

    sal_Bool operator == (const TypeUsing & typeUsing) const
    {
        OSL_ASSERT(0);
        return m_type == typeUsing.m_type && m_use == typeUsing.m_use;
    }
};

struct LessTypeUsing
{
    sal_Bool operator()(const TypeUsing& tuse1, const TypeUsing& tuse2) const
    {
        return (tuse1.m_type < tuse2.m_type);
    }
};

typedef ::std::set< TypeUsing, LessTypeUsing > TypeUsingSet;

#if (defined( _MSC_VER ) && ( _MSC_VER < 1200 ))
typedef ::std::__hash_map__
<
    ::rtl::OString,
    TypeUsingSet,
    HashString,
    EqualString,
    NewAlloc
> DependencyMap;

typedef ::std::__hash_map__
<
    ::rtl::OString,
    sal_uInt16,
    HashString,
    EqualString,
    NewAlloc
> GenerationMap;
#else
typedef ::std::hash_map
<
    ::rtl::OString,
    TypeUsingSet,
    HashString,
    EqualString
> DependencyMap;

typedef ::std::hash_map
<
    ::rtl::OString,
    sal_uInt16,
    HashString,
    EqualString
> GenerationMap;

#endif

struct TypeDependencyImpl
{
    TypeDependencyImpl()
        : m_refCount(0)
        {}

    sal_Int32       m_refCount;
    DependencyMap   m_dependencies;
    GenerationMap   m_generatedTypes;
};

class TypeDependency
{
public:
    TypeDependency();
    ~TypeDependency();

    TypeDependency( const TypeDependency& value )
        : m_pImpl( value.m_pImpl )
    {
        acquire();
    }

    TypeDependency& operator = ( const TypeDependency& value )
    {
        release();
        m_pImpl = value.m_pImpl;
        acquire();
        return *this;
    }

    sal_Bool        insert(const ::rtl::OString& type, const ::rtl::OString& depend, sal_uInt16);
    TypeUsingSet    getDependencies(const ::rtl::OString& type);
    sal_Bool        lookupDependency(const ::rtl::OString& type, const ::rtl::OString& depend, sal_uInt16);
    sal_Bool        hasDependencies(const ::rtl::OString& type);

    void        setGenerated(const ::rtl::OString& type, sal_uInt16 genFlag=CODEGEN_DEFAULT);
    sal_Bool    isGenerated(const ::rtl::OString& type, sal_uInt16 genFlag=CODEGEN_DEFAULT);

    sal_Int32 getSize() { return m_pImpl->m_generatedTypes.size(); }
protected:
    void acquire();
    void release();

protected:
    TypeDependencyImpl* m_pImpl;
};

sal_Bool checkTypeDependencies(TypeManager& typeMgr, TypeDependency& dependencies, const ::rtl::OString& type, sal_Bool bDepend = sal_False);

#endif // _CODEMAKER_DEPENDENCY_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.4.48); FILE MERGED 2008/04/01 15:22:57 thb 1.4.48.3: #i85898# Stripping all external header guards 2008/04/01 12:32:32 thb 1.4.48.2: #i85898# Stripping all external header guards 2008/03/31 07:25:05 rt 1.4.48.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dependency.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _CODEMAKER_DEPENDENCY_HXX_
#define _CODEMAKER_DEPENDENCY_HXX_

#include    <hash_map>
#include    <registry/registry.hxx>
#ifndef __REGISTRY_REFLREAD_HXX__
#include    <registry/reflread.hxx>
#endif
#include    <codemaker/typemanager.hxx>
#include    <codemaker/global.hxx>
#include <osl/diagnose.h>

#define TYPEUSE_NORMAL      0x0001
#define TYPEUSE_SUPER       0x0002
#define TYPEUSE_MEMBER      0x0004
#define TYPEUSE_INPARAM     0x0008
#define TYPEUSE_OUTPARAM    0x0010
#define TYPEUSE_INOUTPARAM  0x0020
#define TYPEUSE_RETURN      0x0040
#define TYPEUSE_EXCEPTION   0x0080
#define TYPEUSE_SCOPE       0x0100

/**
 * Flag shows the state of the code generation. If the Flag is set
 * the code for this type is generated.
 */
#define CODEGEN_DEFAULT     0x0001

struct TypeUsing
{
    TypeUsing(const ::rtl::OString& type, sal_uInt16 use)
        : m_type(type)
        , m_use(use)
        {}

    ::rtl::OString  m_type;
    sal_uInt16      m_use;

    sal_Bool operator == (const TypeUsing & typeUsing) const
    {
        OSL_ASSERT(0);
        return m_type == typeUsing.m_type && m_use == typeUsing.m_use;
    }
};

struct LessTypeUsing
{
    sal_Bool operator()(const TypeUsing& tuse1, const TypeUsing& tuse2) const
    {
        return (tuse1.m_type < tuse2.m_type);
    }
};

typedef ::std::set< TypeUsing, LessTypeUsing > TypeUsingSet;

#if (defined( _MSC_VER ) && ( _MSC_VER < 1200 ))
typedef ::std::__hash_map__
<
    ::rtl::OString,
    TypeUsingSet,
    HashString,
    EqualString,
    NewAlloc
> DependencyMap;

typedef ::std::__hash_map__
<
    ::rtl::OString,
    sal_uInt16,
    HashString,
    EqualString,
    NewAlloc
> GenerationMap;
#else
typedef ::std::hash_map
<
    ::rtl::OString,
    TypeUsingSet,
    HashString,
    EqualString
> DependencyMap;

typedef ::std::hash_map
<
    ::rtl::OString,
    sal_uInt16,
    HashString,
    EqualString
> GenerationMap;

#endif

struct TypeDependencyImpl
{
    TypeDependencyImpl()
        : m_refCount(0)
        {}

    sal_Int32       m_refCount;
    DependencyMap   m_dependencies;
    GenerationMap   m_generatedTypes;
};

class TypeDependency
{
public:
    TypeDependency();
    ~TypeDependency();

    TypeDependency( const TypeDependency& value )
        : m_pImpl( value.m_pImpl )
    {
        acquire();
    }

    TypeDependency& operator = ( const TypeDependency& value )
    {
        release();
        m_pImpl = value.m_pImpl;
        acquire();
        return *this;
    }

    sal_Bool        insert(const ::rtl::OString& type, const ::rtl::OString& depend, sal_uInt16);
    TypeUsingSet    getDependencies(const ::rtl::OString& type);
    sal_Bool        lookupDependency(const ::rtl::OString& type, const ::rtl::OString& depend, sal_uInt16);
    sal_Bool        hasDependencies(const ::rtl::OString& type);

    void        setGenerated(const ::rtl::OString& type, sal_uInt16 genFlag=CODEGEN_DEFAULT);
    sal_Bool    isGenerated(const ::rtl::OString& type, sal_uInt16 genFlag=CODEGEN_DEFAULT);

    sal_Int32 getSize() { return m_pImpl->m_generatedTypes.size(); }
protected:
    void acquire();
    void release();

protected:
    TypeDependencyImpl* m_pImpl;
};

sal_Bool checkTypeDependencies(TypeManager& typeMgr, TypeDependency& dependencies, const ::rtl::OString& type, sal_Bool bDepend = sal_False);

#endif // _CODEMAKER_DEPENDENCY_HXX_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: rdbmaker.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: tbe $ $Date: 2001-05-11 09:39:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#include <codemaker/typemanager.hxx>
#endif
#ifndef _CODEMAKER_DEPENDENCY_HXX_
#include <codemaker/dependency.hxx>
#endif

#ifndef _RTL_OSTRINGBUFFER_HXX_
#include <rtl/strbuf.hxx>
#endif

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif

#ifdef UNX
#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif

#include "specialtypemanager.hxx"
#include "rdboptions.hxx"
#include "rdbtype.hxx"

#define PATH_DELEMITTER '/'

using namespace rtl;
using namespace osl;

FileStream          listFile;
RegistryKey         rootKey;
RegistryLoader      loader;
Registry            regFile(loader);
sal_Bool            useSpecial;
TypeManager*        pTypeMgr = NULL;
StringList          dirEntries;
StringSet           filterTypes;

OString getFullNameOfApplicatRdb()
{
    OUString bootReg;
    OUString uTmpStr;
    if( osl_getExecutableFile(&uTmpStr.pData) == osl_Process_E_None )
    {
        sal_uInt32  lastIndex = uTmpStr.lastIndexOf(PATH_DELEMITTER);
        OUString    tmpReg;

        if ( lastIndex > 0 )
        {
            tmpReg =uTmpStr.copy(0, lastIndex + 1);
        }

        tmpReg += OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb") );

        FileBase::getSystemPathFromNormalizedPath(tmpReg, bootReg);
    }

    return OUStringToOString(bootReg, RTL_TEXTENCODING_ASCII_US);
}

void initFilterTypes(RdbOptions* pOptions)
{
    if (pOptions->isValid("-FT"))
    {
        OString fOption(pOptions->getOption("-FT"));
        sal_Bool ret = sal_False;
        sal_Int32 nIndex = 0;
        do
        {
            filterTypes.insert( fOption.getToken( 0, ';', nIndex ).replace('.', '/') );
        }
        while ( nIndex >= 0 );
    }
    if (pOptions->isValid("-F"))
    {
        FILE  *f = fopen(pOptions->getOption("-F").getStr(), "r");

        if (f)
        {
            sal_Char buffer[1024+1];
            sal_Char *pBuf = fgets(buffer, 1024, f);
            sal_Char *s = NULL;
            sal_Char *p = NULL;
            while ( pBuf && !feof(f))
            {
                p = pBuf;
                if (*p != '\n' && *p != '\r')
                {
                    while (*p == ' ' && *p =='\t')
                        p++;

                    s = p;
                    while (*p != '\n' && *p != '\r' && *p != ' ' && *p != '\t')
                        p++;

                    *p = '\0';
                    filterTypes.insert( OString(s).replace('.', '/') );
                }

                pBuf = fgets(buffer, 1024, f);
            }

            fclose(f);
        }
    }
}

sal_Bool checkFilterTypes(const OString& type)
{
    StringSet::iterator iter = filterTypes.begin();
    while ( iter != filterTypes.end() )
    {
        if ( type.indexOf( *iter ) == 0 )
        {
            return sal_True;
        }

        iter++;
    }

    return sal_False;
}

void cleanUp( sal_Bool bError)
{
    if ( pTypeMgr )
    {
        delete pTypeMgr;
    }
    if (useSpecial)
    {
        pTypeMgr = new SpecialTypeManager();
    }else
    {
        pTypeMgr = new RegistryTypeManager();
    }

    if ( rootKey.isValid() )
    {
        rootKey.closeKey();
    }
    if ( regFile.isValid() )
    {
        if ( bError )
        {
            regFile.destroy(OUString());
        } else
        {
            regFile.close();
        }
    }
    if ( listFile.isValid() )
    {
        listFile.closeFile();
        unlink(listFile.getName().getStr());
    }

    StringList::reverse_iterator iter = dirEntries.rbegin();
    while ( iter != dirEntries.rend() )
    {
           if (rmdir((char*)(*iter).getStr()) == -1)
        {
            break;
        }

        iter++;
    }
}

OString createFileName(const OString& path)
{
    OString fileName(path);

    sal_Char token;
#ifdef SAL_UNX
    fileName = fileName.replace('\\', '/');
    token = '/';
#else
    fileName = fileName.replace('/', '\\');
    token = '\\';
#endif

    OStringBuffer nameBuffer( path.getLength() );

    sal_Int32 nIndex = 0;
    do
    {
        nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());
        if ( nIndex == -1 ) break;

        if (nameBuffer.getLength() == 0 || OString(".") == nameBuffer.getStr())
        {
            nameBuffer.append(token);
            continue;
        }

#ifdef SAL_UNX
        if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)
#else
           if (mkdir((char*)nameBuffer.getStr()) == -1)
#endif
        {
            if ( errno == ENOENT )
                return OString();
        } else
        {
            dirEntries.push_back(nameBuffer.getStr());
        }

        nameBuffer.append(token);
    }
    while ( nIndex >= 0 );

    return fileName;
}

sal_Bool produceAllTypes(const OString& typeName,
                         TypeManager& typeMgr,
                         TypeDependency& typeDependencies,
                         RdbOptions* pOptions,
                         sal_Bool bFullScope,
                         FileStream& o,
                         RegistryKey& regKey,
                         StringSet& filterTypes)
    throw( CannotDumpException )
{
    if (!produceType(typeName, typeMgr, typeDependencies, pOptions, o, regKey, filterTypes))
    {
        fprintf(stderr, "%s ERROR: %s\n",
                pOptions->getProgramName().getStr(),
                OString("cannot dump Type '" + typeName + "'").getStr());
        cleanUp(sal_True);
        exit(99);
    }

    RegistryKey typeKey = typeMgr.getTypeKey(typeName);
    RegistryKeyNames subKeys;

    if (typeKey.getKeyNames(OUString(), subKeys))
        return sal_False;

    OString tmpName;
    for (sal_uInt32 i=0; i < subKeys.getLength(); i++)
    {
        tmpName = OUStringToOString(subKeys.getElement(i), RTL_TEXTENCODING_UTF8);

        if (pOptions->isValid("-B"))
            tmpName = tmpName.copy(tmpName.indexOf('/', 1) + 1);
        else
            tmpName = tmpName.copy(1);

        if (bFullScope)
        {
            if (!produceAllTypes(tmpName, typeMgr, typeDependencies, pOptions, sal_True,
                                 o, regKey, filterTypes))
                return sal_False;
        } else
        {
            if (!produceType(tmpName, typeMgr, typeDependencies, pOptions, o, regKey, filterTypes))
                return sal_False;
        }
    }

    return sal_True;
}

#if (defined UNX) || (defined OS2)
int main( int argc, char * argv[] )
#else
int _cdecl main( int argc, char * argv[] )
#endif
{
    RdbOptions options;

    try
    {
        if (!options.initOptions(argc, argv))
        {
            cleanUp(sal_True);
            exit(1);
        }
    }
    catch( IllegalArgument& e)
    {
        fprintf(stderr, "Illegal option: %s\n", e.m_message.getStr());
        cleanUp(sal_True);
        exit(99);
    }

    TypeDependency  typeDependencies;

    OString bootReg;

    if ( options.isValid("-R") )
    {
        bootReg = options.getOption("-R");
    } else
    {
        if (options.getInputFiles().empty())
        {
            bootReg = getFullNameOfApplicatRdb();
        }
    }

    if ( bootReg.getLength() )
    {
        pTypeMgr = new SpecialTypeManager();
        useSpecial = sal_True;
    } else
    {
        pTypeMgr = new RegistryTypeManager();
        useSpecial = sal_False;
    }

    TypeManager& typeMgr = *pTypeMgr;

    if ( useSpecial && !typeMgr.init( bootReg ) )
    {
        fprintf(stderr, "%s : init typemanager failed, check your environment for bootstrapping uno.\n", options.getProgramName().getStr());
        cleanUp(sal_True);
        exit(99);
    }
    if ( !useSpecial && !typeMgr.init(!options.isValid("-T"), options.getInputFiles()))
    {
        fprintf(stderr, "%s : init registries failed, check your registry files.\n", options.getProgramName().getStr());
        cleanUp(sal_True);
        exit(99);
    }

    initFilterTypes(&options);

    if (options.isValid("-B"))
    {
        typeMgr.setBase(options.getOption("-B"));
    }

    if ( !options.isValid("-O") )
    {
        fprintf(stderr, "%s ERROR: %s\n",
                options.getProgramName().getStr(),
                "no output file is specified.");
        cleanUp(sal_True);
        exit(99);
    }

    if ( options.generateTypeList() )
    {
        OString fileName = createFileName( options.getOption("-O") );
        listFile.openFile(fileName);

        if ( !listFile.isValid() )
        {
            fprintf(stderr, "%s ERROR: %s\n",
                    options.getProgramName().getStr(),
                    "could not open output file.");
            cleanUp(sal_True);
            exit(99);
        }
    } else
    {
        OUString fileName( OStringToOUString(createFileName( options.getOption("-O") ), RTL_TEXTENCODING_UTF8) );
        if ( regFile.create(fileName) )
        {
            fprintf(stderr, "%s ERROR: %s\n",
                    options.getProgramName().getStr(),
                    "could not create registry output file.");
            cleanUp(sal_True);
            exit(99);
        }

        if (options.isValid("-b"))
        {
            RegistryKey tmpKey;
            regFile.openRootKey(tmpKey);

            tmpKey.createKey( OStringToOUString(options.getOption("-b"), RTL_TEXTENCODING_UTF8), rootKey);
        } else
        {
            regFile.openRootKey(rootKey);
        }
    }

    try
    {
        if (options.isValid("-T"))
        {
            OString tOption(options.getOption("-T"));
            OString typeName, tmpName;
            sal_Bool ret = sal_False;
            sal_Int32 nIndex = 0;
            do
            {
                typeName = tOption.getToken( 0, ';', nIndex);
                sal_Int32 lastIndex = typeName.lastIndexOf('.');
                tmpName = typeName.copy( lastIndex+1 );
                if (tmpName == "*")
                {
                    if (bootReg.getLength())
                    {
                        fprintf(stderr, "%s ERROR: %s\n",
                                options.getProgramName().getStr(),
                                "dumping all types of a scope is not possible if -R option is used.");
                        exit(99);
                    }
                    // produce this type and his scope, but the scope is not recursively  generated.
                    if (typeName.equals("*"))
                    {
                        tmpName = "/";
                    } else
                    {
                        tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '/');
                        if (tmpName.getLength() == 0)
                            tmpName = "/";
                        else
                            tmpName.replace('.', '/');
                    }
                    ret = produceAllTypes(tmpName, typeMgr, typeDependencies, &options, sal_False,
                                          listFile, rootKey, filterTypes);
                } else
                {
                    // produce only this type
                    ret = produceType(typeName.replace('.', '/'), typeMgr, typeDependencies,
                                      &options, listFile, rootKey, filterTypes);
                }
/*
                // produce only this type
                ret = produceType(typeName.replace('.', '/'), typeMgr, typeDependencies,
                                  &options, listFile, rootKey, filterTypes);
*/
                if (!ret)
                {
                    fprintf(stderr, "%s ERROR: %s\n",
                            options.getProgramName().getStr(),
                            OString("cannot dump Type '" + typeName + "'").getStr());
                    cleanUp(sal_True);
                    exit(99);
                }
            }
            while ( nIndex >= 0 );
        } else
        if (options.isValid("-X"))
        {
        } else
        {
            if (!bootReg.getLength())
            {
                // produce all types
                if (!produceAllTypes("/", typeMgr, typeDependencies, &options, sal_True,
                                     listFile, rootKey, filterTypes))
                {
                    fprintf(stderr, "%s ERROR: %s\n",
                            options.getProgramName().getStr(),
                            "an error occurs while dumping all types.");
                    exit(99);
                }
            } else
            {
                fprintf(stderr, "%s ERROR: %s\n",
                        options.getProgramName().getStr(),
                        "dumping all types is not possible if -R option is used.");
                exit(99);
            }
        }
    }
    catch( CannotDumpException& e)
    {
        fprintf(stderr, "%s ERROR: %s\n",
                options.getProgramName().getStr(),
                e.m_message.getStr());
        cleanUp(sal_True);
        exit(99);
    }

    cleanUp(sal_False);
    return 0;
}

<commit_msg>#87132# Merge OSL file api changes from TFU630 to SRC633<commit_after>/*************************************************************************
 *
 *  $RCSfile: rdbmaker.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hro $ $Date: 2001-05-21 15:45:07 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#include <codemaker/typemanager.hxx>
#endif
#ifndef _CODEMAKER_DEPENDENCY_HXX_
#include <codemaker/dependency.hxx>
#endif

#ifndef _RTL_OSTRINGBUFFER_HXX_
#include <rtl/strbuf.hxx>
#endif

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif

#ifdef UNX
#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif

#include "specialtypemanager.hxx"
#include "rdboptions.hxx"
#include "rdbtype.hxx"

#define PATH_DELEMITTER '/'

using namespace rtl;
using namespace osl;

FileStream          listFile;
RegistryKey         rootKey;
RegistryLoader      loader;
Registry            regFile(loader);
sal_Bool            useSpecial;
TypeManager*        pTypeMgr = NULL;
StringList          dirEntries;
StringSet           filterTypes;

OString getFullNameOfApplicatRdb()
{
    OUString bootReg;
    OUString uTmpStr;
    if( osl_getExecutableFile(&uTmpStr.pData) == osl_Process_E_None )
    {
        sal_uInt32  lastIndex = uTmpStr.lastIndexOf(PATH_DELEMITTER);
        OUString    tmpReg;

        if ( lastIndex > 0 )
        {
            tmpReg =uTmpStr.copy(0, lastIndex + 1);
        }

        tmpReg += OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb") );

        FileBase::getSystemPathFromFileURL(tmpReg, bootReg);
    }

    return OUStringToOString(bootReg, RTL_TEXTENCODING_ASCII_US);
}

void initFilterTypes(RdbOptions* pOptions)
{
    if (pOptions->isValid("-FT"))
    {
        OString fOption(pOptions->getOption("-FT"));
        sal_Bool ret = sal_False;
        sal_Int32 nIndex = 0;
        do
        {
            filterTypes.insert( fOption.getToken( 0, ';', nIndex ).replace('.', '/') );
        }
        while ( nIndex >= 0 );
    }
    if (pOptions->isValid("-F"))
    {
        FILE  *f = fopen(pOptions->getOption("-F").getStr(), "r");

        if (f)
        {
            sal_Char buffer[1024+1];
            sal_Char *pBuf = fgets(buffer, 1024, f);
            sal_Char *s = NULL;
            sal_Char *p = NULL;
            while ( pBuf && !feof(f))
            {
                p = pBuf;
                if (*p != '\n' && *p != '\r')
                {
                    while (*p == ' ' && *p =='\t')
                        p++;

                    s = p;
                    while (*p != '\n' && *p != '\r' && *p != ' ' && *p != '\t')
                        p++;

                    *p = '\0';
                    filterTypes.insert( OString(s).replace('.', '/') );
                }

                pBuf = fgets(buffer, 1024, f);
            }

            fclose(f);
        }
    }
}

sal_Bool checkFilterTypes(const OString& type)
{
    StringSet::iterator iter = filterTypes.begin();
    while ( iter != filterTypes.end() )
    {
        if ( type.indexOf( *iter ) == 0 )
        {
            return sal_True;
        }

        iter++;
    }

    return sal_False;
}

void cleanUp( sal_Bool bError)
{
    if ( pTypeMgr )
    {
        delete pTypeMgr;
    }
    if (useSpecial)
    {
        pTypeMgr = new SpecialTypeManager();
    }else
    {
        pTypeMgr = new RegistryTypeManager();
    }

    if ( rootKey.isValid() )
    {
        rootKey.closeKey();
    }
    if ( regFile.isValid() )
    {
        if ( bError )
        {
            regFile.destroy(OUString());
        } else
        {
            regFile.close();
        }
    }
    if ( listFile.isValid() )
    {
        listFile.closeFile();
        unlink(listFile.getName().getStr());
    }

    StringList::reverse_iterator iter = dirEntries.rbegin();
    while ( iter != dirEntries.rend() )
    {
           if (rmdir((char*)(*iter).getStr()) == -1)
        {
            break;
        }

        iter++;
    }
}

OString createFileName(const OString& path)
{
    OString fileName(path);

    sal_Char token;
#ifdef SAL_UNX
    fileName = fileName.replace('\\', '/');
    token = '/';
#else
    fileName = fileName.replace('/', '\\');
    token = '\\';
#endif

    OStringBuffer nameBuffer( path.getLength() );

    sal_Int32 nIndex = 0;
    do
    {
        nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());
        if ( nIndex == -1 ) break;

        if (nameBuffer.getLength() == 0 || OString(".") == nameBuffer.getStr())
        {
            nameBuffer.append(token);
            continue;
        }

#ifdef SAL_UNX
        if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)
#else
           if (mkdir((char*)nameBuffer.getStr()) == -1)
#endif
        {
            if ( errno == ENOENT )
                return OString();
        } else
        {
            dirEntries.push_back(nameBuffer.getStr());
        }

        nameBuffer.append(token);
    }
    while ( nIndex >= 0 );

    return fileName;
}

sal_Bool produceAllTypes(const OString& typeName,
                         TypeManager& typeMgr,
                         TypeDependency& typeDependencies,
                         RdbOptions* pOptions,
                         sal_Bool bFullScope,
                         FileStream& o,
                         RegistryKey& regKey,
                         StringSet& filterTypes)
    throw( CannotDumpException )
{
    if (!produceType(typeName, typeMgr, typeDependencies, pOptions, o, regKey, filterTypes))
    {
        fprintf(stderr, "%s ERROR: %s\n",
                pOptions->getProgramName().getStr(),
                OString("cannot dump Type '" + typeName + "'").getStr());
        cleanUp(sal_True);
        exit(99);
    }

    RegistryKey typeKey = typeMgr.getTypeKey(typeName);
    RegistryKeyNames subKeys;

    if (typeKey.getKeyNames(OUString(), subKeys))
        return sal_False;

    OString tmpName;
    for (sal_uInt32 i=0; i < subKeys.getLength(); i++)
    {
        tmpName = OUStringToOString(subKeys.getElement(i), RTL_TEXTENCODING_UTF8);

        if (pOptions->isValid("-B"))
            tmpName = tmpName.copy(tmpName.indexOf('/', 1) + 1);
        else
            tmpName = tmpName.copy(1);

        if (bFullScope)
        {
            if (!produceAllTypes(tmpName, typeMgr, typeDependencies, pOptions, sal_True,
                                 o, regKey, filterTypes))
                return sal_False;
        } else
        {
            if (!produceType(tmpName, typeMgr, typeDependencies, pOptions, o, regKey, filterTypes))
                return sal_False;
        }
    }

    return sal_True;
}

#if (defined UNX) || (defined OS2)
int main( int argc, char * argv[] )
#else
int _cdecl main( int argc, char * argv[] )
#endif
{
    RdbOptions options;

    try
    {
        if (!options.initOptions(argc, argv))
        {
            cleanUp(sal_True);
            exit(1);
        }
    }
    catch( IllegalArgument& e)
    {
        fprintf(stderr, "Illegal option: %s\n", e.m_message.getStr());
        cleanUp(sal_True);
        exit(99);
    }

    TypeDependency  typeDependencies;

    OString bootReg;

    if ( options.isValid("-R") )
    {
        bootReg = options.getOption("-R");
    } else
    {
        if (options.getInputFiles().empty())
        {
            bootReg = getFullNameOfApplicatRdb();
        }
    }

    if ( bootReg.getLength() )
    {
        pTypeMgr = new SpecialTypeManager();
        useSpecial = sal_True;
    } else
    {
        pTypeMgr = new RegistryTypeManager();
        useSpecial = sal_False;
    }

    TypeManager& typeMgr = *pTypeMgr;

    if ( useSpecial && !typeMgr.init( bootReg ) )
    {
        fprintf(stderr, "%s : init typemanager failed, check your environment for bootstrapping uno.\n", options.getProgramName().getStr());
        cleanUp(sal_True);
        exit(99);
    }
    if ( !useSpecial && !typeMgr.init(!options.isValid("-T"), options.getInputFiles()))
    {
        fprintf(stderr, "%s : init registries failed, check your registry files.\n", options.getProgramName().getStr());
        cleanUp(sal_True);
        exit(99);
    }

    initFilterTypes(&options);

    if (options.isValid("-B"))
    {
        typeMgr.setBase(options.getOption("-B"));
    }

    if ( !options.isValid("-O") )
    {
        fprintf(stderr, "%s ERROR: %s\n",
                options.getProgramName().getStr(),
                "no output file is specified.");
        cleanUp(sal_True);
        exit(99);
    }

    if ( options.generateTypeList() )
    {
        OString fileName = createFileName( options.getOption("-O") );
        listFile.openFile(fileName);

        if ( !listFile.isValid() )
        {
            fprintf(stderr, "%s ERROR: %s\n",
                    options.getProgramName().getStr(),
                    "could not open output file.");
            cleanUp(sal_True);
            exit(99);
        }
    } else
    {
        OUString fileName( OStringToOUString(createFileName( options.getOption("-O") ), RTL_TEXTENCODING_UTF8) );
        if ( regFile.create(fileName) )
        {
            fprintf(stderr, "%s ERROR: %s\n",
                    options.getProgramName().getStr(),
                    "could not create registry output file.");
            cleanUp(sal_True);
            exit(99);
        }

        if (options.isValid("-b"))
        {
            RegistryKey tmpKey;
            regFile.openRootKey(tmpKey);

            tmpKey.createKey( OStringToOUString(options.getOption("-b"), RTL_TEXTENCODING_UTF8), rootKey);
        } else
        {
            regFile.openRootKey(rootKey);
        }
    }

    try
    {
        if (options.isValid("-T"))
        {
            OString tOption(options.getOption("-T"));
            OString typeName, tmpName;
            sal_Bool ret = sal_False;
            sal_Int32 nIndex = 0;
            do
            {
                typeName = tOption.getToken( 0, ';', nIndex);
                sal_Int32 lastIndex = typeName.lastIndexOf('.');
                tmpName = typeName.copy( lastIndex+1 );
                if (tmpName == "*")
                {
                    if (bootReg.getLength())
                    {
                        fprintf(stderr, "%s ERROR: %s\n",
                                options.getProgramName().getStr(),
                                "dumping all types of a scope is not possible if -R option is used.");
                        exit(99);
                    }
                    // produce this type and his scope, but the scope is not recursively  generated.
                    if (typeName.equals("*"))
                    {
                        tmpName = "/";
                    } else
                    {
                        tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '/');
                        if (tmpName.getLength() == 0)
                            tmpName = "/";
                        else
                            tmpName.replace('.', '/');
                    }
                    ret = produceAllTypes(tmpName, typeMgr, typeDependencies, &options, sal_False,
                                          listFile, rootKey, filterTypes);
                } else
                {
                    // produce only this type
                    ret = produceType(typeName.replace('.', '/'), typeMgr, typeDependencies,
                                      &options, listFile, rootKey, filterTypes);
                }
/*
                // produce only this type
                ret = produceType(typeName.replace('.', '/'), typeMgr, typeDependencies,
                                  &options, listFile, rootKey, filterTypes);
*/
                if (!ret)
                {
                    fprintf(stderr, "%s ERROR: %s\n",
                            options.getProgramName().getStr(),
                            OString("cannot dump Type '" + typeName + "'").getStr());
                    cleanUp(sal_True);
                    exit(99);
                }
            }
            while ( nIndex >= 0 );
        } else
        if (options.isValid("-X"))
        {
        } else
        {
            if (!bootReg.getLength())
            {
                // produce all types
                if (!produceAllTypes("/", typeMgr, typeDependencies, &options, sal_True,
                                     listFile, rootKey, filterTypes))
                {
                    fprintf(stderr, "%s ERROR: %s\n",
                            options.getProgramName().getStr(),
                            "an error occurs while dumping all types.");
                    exit(99);
                }
            } else
            {
                fprintf(stderr, "%s ERROR: %s\n",
                        options.getProgramName().getStr(),
                        "dumping all types is not possible if -R option is used.");
                exit(99);
            }
        }
    }
    catch( CannotDumpException& e)
    {
        fprintf(stderr, "%s ERROR: %s\n",
                options.getProgramName().getStr(),
                e.m_message.getStr());
        cleanUp(sal_True);
        exit(99);
    }

    cleanUp(sal_False);
    return 0;
}

<|endoftext|>


<commit_before>/*
	Copyright 2014 Justin White
	See included LICENSE file for details.
*/

#include <iostream>
#include <fstream>

#include <cstdio>
#include <cmath>

using std::string;

#include <SFML/Config.hpp>
#include <SFML/Graphics.hpp>

#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/OstreamAppender.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/PatternLayout.hh"
#include "log4cpp/Priority.hh"

#include "GameSprite.h"

// short names for log4cpp Priorities;
const int DEBUG = log4cpp::Priority::DEBUG;
const int INFO = log4cpp::Priority::INFO;
const int WARN = log4cpp::Priority::WARN;
const int ERROR = log4cpp::Priority::ERROR;

//system data
const int version = 0;
const int revision = 1;
const int width = 1280;
const int height = 720;
const string title = "SpaceFight";
sf::RenderWindow* window;
string fileLogName = title + ".log";
log4cpp::Category& alog = log4cpp::Category::getRoot();
log4cpp::Category& clog = log4cpp::Category::getInstance("cons");
log4cpp::Category& flog = log4cpp::Category::getInstance("file");

// game data
const float deadZone = 15;
const float keySpeed = 75;
GameSprite* logo;

// system functions
void initializeSystem();
void processEvents();
void updateControls();
void updateWorld(sf::Time);
void renderWorld();

void initializeSystem()
{
	window = new sf::RenderWindow(sf::VideoMode(width, height), title, sf::Style::Titlebar | sf::Style::Close);
	if (window->isOpen()) {
		sf::ContextSettings settings = window->getSettings();
		alog.info("Using OpenGL v%d.%d",settings.majorVersion, settings.minorVersion);
		alog.info("Created the main window %dx%d", width, height);
	} else {
		alog.error("Could not create main window");
		exit(EXIT_FAILURE);
	}
	alog.info("Enabling VSync");
	window->setVerticalSyncEnabled(true);

	logo = new GameSprite("cb.bmp");
	logo->setPosition(width / 2, height / 2);
	alog.info("Loaded sprite");
}

void processEvents()
{
	static sf::Event event;

	while(window->pollEvent(event)) {
		switch(event.type) {
		case sf::Event::Closed:
			alog.info("Window closed");
			window->close();
			break;
		case sf::Event::KeyPressed:
			switch(event.key.code) {
			case sf::Keyboard::Escape:
				alog.info("Player exited");
				window->close();
				break;
			default:
				break;
			}
			break;
		case sf::Event::KeyReleased:
			switch(event.key.code) {
			default:
				break;
			}
			break;
		default:
			break;
		}
	}
}

void updateControls()
{
	float x, y = 0;

	float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);
	float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);
	x = abs(joy0_X) < deadZone ? 0 : joy0_X;
	y = abs(joy0_y) < deadZone ? 0 : joy0_y;

	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
		y += -keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
		x += keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
		y += keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
		x += -keySpeed;
	}
	logo->moveBy(x, y);
}

void updateWorld(sf::Time elapsed)
{
	const int millis = elapsed.asMilliseconds();
	logo->update(millis);
}

void renderWorld()
{
	window->clear(sf::Color::Black);
	window->draw(*logo);
	window->display();
}

int main()
{
	log4cpp::Category::setRootPriority(DEBUG);

	// console log: 'time priority message'
	log4cpp::PatternLayout* consLogLayout = new log4cpp::PatternLayout();
	consLogLayout->setConversionPattern("%d{%H:%M:%S,%l} %p %m%n");
	log4cpp::Appender* consLog = new log4cpp::OstreamAppender("cons", &std::clog);
	consLog->setLayout(consLogLayout);
	// show debug priority & above when debugging
#ifdef DO_DEBUG
	consLog->setThreshold(DEBUG);
#else
	// show only info priority & above normally
	consLog->setThreshold(INFO);
#endif

	// file log: 'date time priority message'
	log4cpp::PatternLayout* fileLogLayout = new log4cpp::PatternLayout();
	fileLogLayout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S,%l} %p %m%n");
	log4cpp::Appender* fileLog = new log4cpp::FileAppender("file", fileLogName, false);
	fileLog->setLayout(fileLogLayout);
	// always show debug priority & above
	fileLog->setThreshold(DEBUG);

	alog.addAppender(consLog);
	alog.addAppender(fileLog);

	clog.addAppender(consLog);
	clog.setAdditivity(false);
	flog.addAppender(fileLog);
	flog.setAdditivity(false);

	flog << DEBUG << "Opened logFile " << fileLogName;

	alog.info("Spacefight v%d.%d", version, revision);
	alog.info("Built %s %s", __DATE__, __TIME__);
	alog.info("GCC %s", __VERSION__);
	alog.info("SFML %d.%d", SFML_VERSION_MAJOR, SFML_VERSION_MINOR);
	initializeSystem();
	sf::Clock gameClock;
	sf::Time elapsed;
	alog.info("Running...");
	while(window->isOpen()) {
		elapsed = gameClock.restart();
		processEvents();
		updateControls();
		updateWorld(elapsed);
		renderWorld();
	}
	alog.info("Stopped");

	flog << DEBUG << "Closed logFile " << fileLogName;
	fileLog->close();

	return EXIT_SUCCESS;
}
<commit_msg>Rename logo to player.<commit_after>/*
	Copyright 2014 Justin White
	See included LICENSE file for details.
*/

#include <iostream>
#include <fstream>

#include <cstdio>
#include <cmath>

using std::string;

#include <SFML/Config.hpp>
#include <SFML/Graphics.hpp>

#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/OstreamAppender.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/PatternLayout.hh"
#include "log4cpp/Priority.hh"

#include "GameSprite.h"

// short names for log4cpp Priorities;
const int DEBUG = log4cpp::Priority::DEBUG;
const int INFO = log4cpp::Priority::INFO;
const int WARN = log4cpp::Priority::WARN;
const int ERROR = log4cpp::Priority::ERROR;

//system data
const int version = 0;
const int revision = 1;
const int width = 1280;
const int height = 720;
const string title = "SpaceFight";
sf::RenderWindow* window;
string fileLogName = title + ".log";
log4cpp::Category& alog = log4cpp::Category::getRoot();
log4cpp::Category& clog = log4cpp::Category::getInstance("cons");
log4cpp::Category& flog = log4cpp::Category::getInstance("file");

// game data
const float deadZone = 15;
const float keySpeed = 75;
GameSprite* player;

// system functions
void initializeSystem();
void processEvents();
void updateControls();
void updateWorld(sf::Time);
void renderWorld();

void initializeSystem()
{
	window = new sf::RenderWindow(sf::VideoMode(width, height), title, sf::Style::Titlebar | sf::Style::Close);
	if (window->isOpen()) {
		sf::ContextSettings settings = window->getSettings();
		alog.info("Using OpenGL v%d.%d",settings.majorVersion, settings.minorVersion);
		alog.info("Created the main window %dx%d", width, height);
	} else {
		alog.error("Could not create main window");
		exit(EXIT_FAILURE);
	}
	alog.info("Enabling VSync");
	window->setVerticalSyncEnabled(true);
	window->setPosition(sf::Vector2i(100,100));

	player = new GameSprite(sf::Color::Blue);
	player->setPosition(width / 2, height / 2);
	alog.info("Loaded sprite");
}

void processEvents()
{
	static sf::Event event;

	while(window->pollEvent(event)) {
		switch(event.type) {
		case sf::Event::Closed:
			alog.info("Window closed");
			window->close();
			break;
		case sf::Event::KeyPressed:
			switch(event.key.code) {
			case sf::Keyboard::Escape:
				alog.info("Player exited");
				window->close();
				break;
			default:
				break;
			}
			break;
		case sf::Event::KeyReleased:
			switch(event.key.code) {
			default:
				break;
			}
			break;
		default:
			break;
		}
	}
}

void updateControls()
{
	float x, y = 0;

	float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);
	float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);
	x = abs(joy0_X) < deadZone ? 0 : joy0_X;
	y = abs(joy0_y) < deadZone ? 0 : joy0_y;

	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
		y += -keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
		x += keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
		y += keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
		x += -keySpeed;
	}
	player->moveBy(x, y);
}

void updateWorld(sf::Time elapsed)
{
	const int millis = elapsed.asMilliseconds();
	player->update(millis);
}

void renderWorld()
{
	window->clear(sf::Color::Black);
	window->draw(*player);
	window->display();
}

int main()
{
	log4cpp::Category::setRootPriority(DEBUG);

	// console log: 'time priority message'
	log4cpp::PatternLayout* consLogLayout = new log4cpp::PatternLayout();
	consLogLayout->setConversionPattern("%d{%H:%M:%S,%l} %p %m%n");
	log4cpp::Appender* consLog = new log4cpp::OstreamAppender("cons", &std::clog);
	consLog->setLayout(consLogLayout);
	// show debug priority & above when debugging
#ifdef DO_DEBUG
	consLog->setThreshold(DEBUG);
#else
	// show only info priority & above normally
	consLog->setThreshold(INFO);
#endif

	// file log: 'date time priority message'
	log4cpp::PatternLayout* fileLogLayout = new log4cpp::PatternLayout();
	fileLogLayout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S,%l} %p %m%n");
	log4cpp::Appender* fileLog = new log4cpp::FileAppender("file", fileLogName, false);
	fileLog->setLayout(fileLogLayout);
	// always show debug priority & above
	fileLog->setThreshold(DEBUG);

	alog.addAppender(consLog);
	alog.addAppender(fileLog);

	clog.addAppender(consLog);
	clog.setAdditivity(false);
	flog.addAppender(fileLog);
	flog.setAdditivity(false);

	flog << DEBUG << "Opened logFile " << fileLogName;

	alog.info("Spacefight v%d.%d", version, revision);
	alog.info("Built %s %s", __DATE__, __TIME__);
	alog.info("GCC %s", __VERSION__);
	alog.info("SFML %d.%d", SFML_VERSION_MAJOR, SFML_VERSION_MINOR);
	initializeSystem();
	sf::Clock gameClock;
	sf::Time elapsed;
	alog.info("Running...");
	while(window->isOpen()) {
		elapsed = gameClock.restart();
		processEvents();
		updateControls();
		updateWorld(elapsed);
		renderWorld();
	}
	alog.info("Stopped");

	flog << DEBUG << "Closed logFile " << fileLogName;
	fileLog->close();

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "jitpp/arm/Disassembler.h"
#include "jitpp/arm/ArmTranslatorFactory.h"
#include "jitpp/arm/ArmTranslator.h"
#include "jitpp/ACState.h"
#include "jitpp/CodeCache.h"

#include <os/Board.h>
#include <os/MemoryManager.h>

#include <cstdio>

namespace {

uint64_t *emulation_pml2[4] =
{
	nullptr, nullptr, nullptr, nullptr,
};

uint64_t *emulation_pml3 = nullptr;

void mapArmPhysicalMem()
{
	emulation_pml2[0] = (uint64_t*)os::mm::allocate_page();
	emulation_pml2[1] = (uint64_t*)os::mm::allocate_page();
	emulation_pml2[2] = (uint64_t*)os::mm::allocate_page();
	emulation_pml2[3] = (uint64_t*)os::mm::allocate_page();

	emulation_pml3 = (uint64_t*)os::mm::allocate_page();

	const int NUM_PAGE_TABLE_ENTRIES_PER_PAGE = (4096 / sizeof(uint64_t));

	for( int ii = 0; ii < NUM_PAGE_TABLE_ENTRIES_PER_PAGE; ii++ ) {
		emulation_pml3[ii] = 0;
	}

	for( int ii = 0; ii < NUM_PAGE_TABLE_ENTRIES_PER_PAGE; ii++ ) {
		for( int jj = 0; jj < 4; jj++ ) {
			const uint64_t PHYS_PAGE = ((2 * 1024 * 1024) * ii) +
			                           ((1 * 1024 * 1024 *1024) * jj) +
			                           0x100000000UL;
			emulation_pml2[jj][ii] = PHYS_PAGE | 0x83;
		}
	}

	for( int ii = 0; ii < 4; ii++ ) {
		const uint64_t pml2_phys_addr = ((uint64_t)emulation_pml2[ii]) - 0xFFFFFFFF80000000UL;

		emulation_pml3[ii] = pml2_phys_addr | 1;
	}

	os::mm::set_lower_pml3(emulation_pml3, 0);
}

class VMMCodeCacheRandomStrategy
{
protected:
	static int get_rand_way( int ways ) {
		return os::board::high_performance_timer() % ways;
	}
};

class DeletionEvictionPolicy
{
protected:
	static void on_item_evicted( remu::jitpp::CodePage<4096, remu::jitpp::arm::ArmTranslator> **evicted ) {
		delete *evicted;
	}
};

class NoMmuHostPageSelectionStrategy
{
protected:
	static void* get_host_page( const remu::jitpp::ACFarPointer& ip ) {
		return reinterpret_cast<void*>( ip.program_counter & ~4095 );
	}
};

using Arm11CpuCodeCache = remu::jitpp::CodeCache<4,1024,4096,
                                                 VMMCodeCacheRandomStrategy,
                                                 DeletionEvictionPolicy,
                                                 remu::jitpp::arm::ArmTranslatorFactory,
                                                 remu::jitpp::arm::ArmTranslator,
                                                 NoMmuHostPageSelectionStrategy>;

} /*anonymous namespace*/

void appMain()
{
	mapArmPhysicalMem();

	remu::jitpp::arm::Disassembler dis;
	remu::jitpp::ACState cpu_state;
	Arm11CpuCodeCache *code_cache = new Arm11CpuCodeCache();

	cpu_state.clear();
	cpu_state.ip.program_counter = 0x00008000;

	bool running = true;

	while( running ) {
		auto code_page = code_cache->getPageForFarPointer( cpu_state.ip );
		printf("code_page:  %p (host_page=%p guest_page=%0lx:%lx)\n", code_page, code_page->getHostBase(),
		       cpu_state.ip.code_segment, cpu_state.ip.program_counter );
		running = code_page->execute( cpu_state );
		running = false;
	}

	uint32_t *first_instr = reinterpret_cast<uint32_t*>(cpu_state.ip.program_counter);

	char buffer[64];

	for( int ii = 0; ii < 75; ii++ ) {
		const uint64_t cur_addr = 0x8000 + (sizeof(uint32_t) * ii);
		const uint32_t instr = first_instr[ii];

		dis.disassemble(instr, cur_addr, buffer, 64);

		printf("%08lx : %08x : %s\n", cur_addr, instr, buffer);
	}

	char* ptr1 = new char[1 * 1024 * 1024];
	printf("ptr1 = %p\n", ptr1);
	char* ptr2 = new char[1 * 1024 * 1024];
	printf("ptr2 = %p\n", ptr2);
	delete ptr1;
	printf("free(ptr1)\n");
	ptr1 = new char[10];
	printf("ptr1 = %p\n", ptr1);
}

<commit_msg>Remove test print code from vmm app main<commit_after>#include "jitpp/arm/ArmTranslatorFactory.h"
#include "jitpp/arm/ArmTranslator.h"
#include "jitpp/ACState.h"
#include "jitpp/CodeCache.h"

#include <os/Board.h>
#include <os/MemoryManager.h>

#include <cstdio>

namespace {

uint64_t *emulation_pml2[4] =
{
	nullptr, nullptr, nullptr, nullptr,
};

uint64_t *emulation_pml3 = nullptr;

void mapArmPhysicalMem()
{
	emulation_pml2[0] = (uint64_t*)os::mm::allocate_page();
	emulation_pml2[1] = (uint64_t*)os::mm::allocate_page();
	emulation_pml2[2] = (uint64_t*)os::mm::allocate_page();
	emulation_pml2[3] = (uint64_t*)os::mm::allocate_page();

	emulation_pml3 = (uint64_t*)os::mm::allocate_page();

	const int NUM_PAGE_TABLE_ENTRIES_PER_PAGE = (4096 / sizeof(uint64_t));

	for( int ii = 0; ii < NUM_PAGE_TABLE_ENTRIES_PER_PAGE; ii++ ) {
		emulation_pml3[ii] = 0;
	}

	for( int ii = 0; ii < NUM_PAGE_TABLE_ENTRIES_PER_PAGE; ii++ ) {
		for( int jj = 0; jj < 4; jj++ ) {
			const uint64_t PHYS_PAGE = ((2 * 1024 * 1024) * ii) +
			                           ((1 * 1024 * 1024 *1024) * jj) +
			                           0x100000000UL;
			emulation_pml2[jj][ii] = PHYS_PAGE | 0x83;
		}
	}

	for( int ii = 0; ii < 4; ii++ ) {
		const uint64_t pml2_phys_addr = ((uint64_t)emulation_pml2[ii]) - 0xFFFFFFFF80000000UL;

		emulation_pml3[ii] = pml2_phys_addr | 1;
	}

	os::mm::set_lower_pml3(emulation_pml3, 0);
}

class VMMCodeCacheRandomStrategy
{
protected:
	static int get_rand_way( int ways ) {
		return os::board::high_performance_timer() % ways;
	}
};

class DeletionEvictionPolicy
{
protected:
	static void on_item_evicted( remu::jitpp::CodePage<4096, remu::jitpp::arm::ArmTranslator> **evicted ) {
		delete *evicted;
	}
};

class NoMmuHostPageSelectionStrategy
{
protected:
	static void* get_host_page( const remu::jitpp::ACFarPointer& ip ) {
		return reinterpret_cast<void*>( ip.program_counter & ~4095 );
	}
};

using Arm11CpuCodeCache = remu::jitpp::CodeCache<4,1024,4096,
                                                 VMMCodeCacheRandomStrategy,
                                                 DeletionEvictionPolicy,
                                                 remu::jitpp::arm::ArmTranslatorFactory,
                                                 remu::jitpp::arm::ArmTranslator,
                                                 NoMmuHostPageSelectionStrategy>;

} /*anonymous namespace*/

void appMain()
{
	mapArmPhysicalMem();

	remu::jitpp::ACState cpu_state;
	Arm11CpuCodeCache *code_cache = new Arm11CpuCodeCache();

	cpu_state.clear();
	cpu_state.ip.program_counter = 0x00008000;

	bool running = true;

	while( running ) {
		auto code_page = code_cache->getPageForFarPointer( cpu_state.ip );
		printf("code_page:  %p (host_page=%p guest_page=%0lx:%lx)\n", code_page, code_page->getHostBase(),
		       cpu_state.ip.code_segment, cpu_state.ip.program_counter );
		running = code_page->execute( cpu_state );
		running = false;
	}
}

<|endoftext|>


<commit_before>
#include "diff_system.h"
#include "libmesh_logging.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"

NewtonSolver::NewtonSolver (sys_type& s)
  : Parent(s),
    linear_solver(LinearSolver<Number>::build())
{
}

NewtonSolver::~NewtonSolver ()
{
}

void NewtonSolver::reinit()
{
  Parent::reinit();

  linear_solver->clear();
}

void NewtonSolver::solve()
{
  START_LOG("solve()", "NewtonSolver");

// Reduce Newton step length to keep residual from increasing?
const bool require_residual_reduction = false;
// Maximum amount by which to reduce Newton steps
const Real minsteplength = 0.1;
// Amount by which nonlinear residual should exceed linear solver
// tolerance
const Real relative_tolerance = 1.e-3;

  NumericVector<Number> &solution = *(_system.solution);
  NumericVector<Number> &newton_iterate =
    _system.get_vector("_nonlinear_solution");
  NumericVector<Number> &rhs = *(_system.rhs);

  SparseMatrix<Number> &matrix = *(_system.matrix);

  // Prepare to take incomplete steps
  Real last_residual=0.;

  // Set starting linear tolerance
  Real current_linear_tolerance = initial_linear_tolerance;

  // Now we begin the nonlinear loop
  for (unsigned int l=0; l<max_nonlinear_iterations; ++l)
    {
      PAUSE_LOG("solve()", "NewtonSolver");
      _system.assembly(true, true);
      RESTART_LOG("solve()", "NewtonSolver");
      rhs.close();
      Real current_residual = rhs.l2_norm();
      last_residual = current_residual;

      max_residual_norm = std::max (current_residual,
                                    max_residual_norm);

      if (!quiet)
        std::cout << "Nonlinear Residual: "
                  << current_residual << std::endl;

      // Make sure our linear tolerance is low enough
      if (current_linear_tolerance > current_residual * relative_tolerance)
        {
          current_linear_tolerance = current_residual * relative_tolerance;
        }

      // But don't let it be zero
      if (current_linear_tolerance < TOLERANCE * TOLERANCE)
        {
          current_linear_tolerance = TOLERANCE * TOLERANCE;
        }

      // At this point newton_iterate is the current guess, and
      // solution is now about to become the NEGATIVE of the next
      // Newton step.

      // Our best initial guess for the solution is zero!
      solution.zero();

      if (!quiet)
        std::cout << "Linear solve starting" << std::endl;

      PAUSE_LOG("solve()", "NewtonSolver");
      // Solve the linear system.  Two cases:
      const std::pair<unsigned int, Real> rval =
        (_system.have_matrix("Preconditioner")) ?
      // 1.) User-supplied preconditioner
        linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
                              solution, rhs, current_linear_tolerance,
                              max_linear_iterations) :
      // 2.) Use system matrix for the preconditioner
        linear_solver->solve (matrix, solution, rhs,
                              current_linear_tolerance,
                              max_linear_iterations);
      // We may need to localize a parallel solution
      _system.update ();
      RESTART_LOG("solve()", "NewtonSolver");

      if (!quiet)
        std::cout << "Linear solve finished, step " << rval.first
                  << ", residual " << rval.second
                  << ", tolerance " << current_linear_tolerance
                  << std::endl;

      // Compute the l2 norm of the nonlinear update
      Real norm_delta = solution.l2_norm();

      if (!quiet)
        std::cout << "Trying full Newton step" << std::endl;
      // Take a full Newton step
      newton_iterate.add (-1., solution);
      newton_iterate.close();

      // Check residual with full Newton step
      Real steplength = 1.;
      PAUSE_LOG("solve()", "NewtonSolver");
      _system.assembly(true, false);
      RESTART_LOG("solve()", "NewtonSolver");

      rhs.close();
      current_residual = rhs.l2_norm();

      // backtrack if necessary
      if (require_residual_reduction)
        {
          while (current_residual > last_residual)
            {
              // Reduce step size to 1/2, 1/4, etc.
              steplength /= 2.;
              norm_delta /= 2.;
              if (!quiet)
                std::cout << "Shrinking Newton step to "
                          << steplength << std::endl;
              newton_iterate.add (steplength, solution);
              newton_iterate.close();

              // Check residual with fractional Newton step
              PAUSE_LOG("solve()", "NewtonSolver");
              _system.assembly (true, false);
              RESTART_LOG("solve()", "NewtonSolver");
              current_residual = rhs.l2_norm();
              if (!quiet)
                std::cout << "Current Residual: "
                          << current_residual << std::endl;

              if (steplength/2. < minsteplength &&
                  current_residual > last_residual)
                {
                  if (!quiet)
                    std::cout << "Inexact Newton step FAILED at step "
                              << l << std::endl;

                  error();
                }
            }
        }

      // Compute the l2 norm of the whole solution
      const Real norm_total = newton_iterate.l2_norm();

      max_solution_norm = std::max(max_solution_norm, norm_total);

      // Print out information for the
      // nonlinear iterations.
      if (!quiet)
        std::cout << "    Nonlinear step: |du|/|u| = "
                  << norm_delta / norm_total
                  << ", |du| = " << norm_delta
                  << std::endl;

      // We haven't converged unless we pass a convergence test
      bool has_converged = false;

      // Is our absolute residual low enough?
      if (current_residual < absolute_residual_tolerance)
        {
          if (!quiet)
	    std::cout << "  Nonlinear solver converged, step " << l
                      << ", residual " << current_residual
                      << std::endl;
          has_converged = true;
        }
      else if (absolute_residual_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver current_residual "
                      << current_residual << " > "
		      << (absolute_residual_tolerance) << std::endl;
        }

      // Is our relative residual low enough?
      if ((current_residual / max_residual_norm) <
          relative_residual_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver converged, step " << l
                      << ", residual reduction "
                      << current_residual / max_residual_norm
                      << " < " << relative_residual_tolerance
                      << std::endl;
          has_converged = true;
        }
      else if (relative_residual_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver relative residual "
                      << (current_residual / max_residual_norm)
                      << " > " << relative_residual_tolerance
                      << std::endl;
        }

      // Is our absolute Newton step size small enough?
      if (norm_delta / steplength < absolute_step_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver converged, step " << l
                      << ", absolute step size "
                      << norm_delta / steplength
                      << " < " << absolute_step_tolerance
                      << std::endl;
          has_converged = true;
        }
      else if (absolute_step_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver absolute step size "
                      << (norm_delta / steplength)
                      << " > " << absolute_step_tolerance
                      << std::endl;
        }

      // Is our relative Newton step size small enough?
      if (norm_delta / steplength / max_solution_norm <
          relative_step_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver converged, step " << l
                      << ", relative step size "
                      << (norm_delta / steplength / max_solution_norm)
                      << " < " << relative_step_tolerance
                      << std::endl;
          has_converged = true;
        }
      else if (relative_step_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver relative step size "
                      << (norm_delta / steplength / max_solution_norm)
                      << " > " << relative_step_tolerance
                      << std::endl;
        }

      // Terminate the solution iteration if the difference between
      // this iteration and the last is sufficiently small.
      if (has_converged)
        {
          break;
        }
      if (l >= max_nonlinear_iterations - 1)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver DIVERGED at step " << l
                      << std::endl;
          error();
          continue;
        }
    } // end nonlinear loop

  // Copy the final nonlinear iterate into the current_solution,
  // for other libMesh functions that expect it

  solution = newton_iterate;
  solution.close();

  STOP_LOG("solve()", "NewtonSolver");
}
<commit_msg>Make sure current_local_solution is up to date<commit_after>
#include "diff_system.h"
#include "libmesh_logging.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"

NewtonSolver::NewtonSolver (sys_type& s)
  : Parent(s),
    linear_solver(LinearSolver<Number>::build())
{
}

NewtonSolver::~NewtonSolver ()
{
}

void NewtonSolver::reinit()
{
  Parent::reinit();

  linear_solver->clear();
}

void NewtonSolver::solve()
{
  START_LOG("solve()", "NewtonSolver");

// Reduce Newton step length to keep residual from increasing?
const bool require_residual_reduction = false;
// Maximum amount by which to reduce Newton steps
const Real minsteplength = 0.1;
// Amount by which nonlinear residual should exceed linear solver
// tolerance
const Real relative_tolerance = 1.e-3;

  NumericVector<Number> &solution = *(_system.solution);
  NumericVector<Number> &newton_iterate =
    _system.get_vector("_nonlinear_solution");
  NumericVector<Number> &rhs = *(_system.rhs);

  SparseMatrix<Number> &matrix = *(_system.matrix);

  // Prepare to take incomplete steps
  Real last_residual=0.;

  // Set starting linear tolerance
  Real current_linear_tolerance = initial_linear_tolerance;

  // Now we begin the nonlinear loop
  for (unsigned int l=0; l<max_nonlinear_iterations; ++l)
    {
      PAUSE_LOG("solve()", "NewtonSolver");
      _system.assembly(true, true);
      RESTART_LOG("solve()", "NewtonSolver");
      rhs.close();
      Real current_residual = rhs.l2_norm();
      last_residual = current_residual;

      max_residual_norm = std::max (current_residual,
                                    max_residual_norm);

      if (!quiet)
        std::cout << "Nonlinear Residual: "
                  << current_residual << std::endl;

      // Make sure our linear tolerance is low enough
      if (current_linear_tolerance > current_residual * relative_tolerance)
        {
          current_linear_tolerance = current_residual * relative_tolerance;
        }

      // But don't let it be zero
      if (current_linear_tolerance < TOLERANCE * TOLERANCE)
        {
          current_linear_tolerance = TOLERANCE * TOLERANCE;
        }

      // At this point newton_iterate is the current guess, and
      // solution is now about to become the NEGATIVE of the next
      // Newton step.

      // Our best initial guess for the solution is zero!
      solution.zero();

      if (!quiet)
        std::cout << "Linear solve starting" << std::endl;

      PAUSE_LOG("solve()", "NewtonSolver");
      // Solve the linear system.  Two cases:
      const std::pair<unsigned int, Real> rval =
        (_system.have_matrix("Preconditioner")) ?
      // 1.) User-supplied preconditioner
        linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
                              solution, rhs, current_linear_tolerance,
                              max_linear_iterations) :
      // 2.) Use system matrix for the preconditioner
        linear_solver->solve (matrix, solution, rhs,
                              current_linear_tolerance,
                              max_linear_iterations);
      // We may need to localize a parallel solution
      _system.update ();
      RESTART_LOG("solve()", "NewtonSolver");

      if (!quiet)
        std::cout << "Linear solve finished, step " << rval.first
                  << ", residual " << rval.second
                  << ", tolerance " << current_linear_tolerance
                  << std::endl;

      // Compute the l2 norm of the nonlinear update
      Real norm_delta = solution.l2_norm();

      if (!quiet)
        std::cout << "Trying full Newton step" << std::endl;
      // Take a full Newton step
      newton_iterate.add (-1., solution);
      newton_iterate.close();

      // Check residual with full Newton step
      Real steplength = 1.;
      PAUSE_LOG("solve()", "NewtonSolver");
      _system.assembly(true, false);
      RESTART_LOG("solve()", "NewtonSolver");

      rhs.close();
      current_residual = rhs.l2_norm();

      // backtrack if necessary
      if (require_residual_reduction)
        {
          while (current_residual > last_residual)
            {
              // Reduce step size to 1/2, 1/4, etc.
              steplength /= 2.;
              norm_delta /= 2.;
              if (!quiet)
                std::cout << "Shrinking Newton step to "
                          << steplength << std::endl;
              newton_iterate.add (steplength, solution);
              newton_iterate.close();

              // Check residual with fractional Newton step
              PAUSE_LOG("solve()", "NewtonSolver");
              _system.assembly (true, false);
              RESTART_LOG("solve()", "NewtonSolver");
              current_residual = rhs.l2_norm();
              if (!quiet)
                std::cout << "Current Residual: "
                          << current_residual << std::endl;

              if (steplength/2. < minsteplength &&
                  current_residual > last_residual)
                {
                  if (!quiet)
                    std::cout << "Inexact Newton step FAILED at step "
                              << l << std::endl;

                  error();
                }
            }
        }

      // Compute the l2 norm of the whole solution
      const Real norm_total = newton_iterate.l2_norm();

      max_solution_norm = std::max(max_solution_norm, norm_total);

      // Print out information for the
      // nonlinear iterations.
      if (!quiet)
        std::cout << "    Nonlinear step: |du|/|u| = "
                  << norm_delta / norm_total
                  << ", |du| = " << norm_delta
                  << std::endl;

      // We haven't converged unless we pass a convergence test
      bool has_converged = false;

      // Is our absolute residual low enough?
      if (current_residual < absolute_residual_tolerance)
        {
          if (!quiet)
	    std::cout << "  Nonlinear solver converged, step " << l
                      << ", residual " << current_residual
                      << std::endl;
          has_converged = true;
        }
      else if (absolute_residual_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver current_residual "
                      << current_residual << " > "
		      << (absolute_residual_tolerance) << std::endl;
        }

      // Is our relative residual low enough?
      if ((current_residual / max_residual_norm) <
          relative_residual_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver converged, step " << l
                      << ", residual reduction "
                      << current_residual / max_residual_norm
                      << " < " << relative_residual_tolerance
                      << std::endl;
          has_converged = true;
        }
      else if (relative_residual_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver relative residual "
                      << (current_residual / max_residual_norm)
                      << " > " << relative_residual_tolerance
                      << std::endl;
        }

      // Is our absolute Newton step size small enough?
      if (norm_delta / steplength < absolute_step_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver converged, step " << l
                      << ", absolute step size "
                      << norm_delta / steplength
                      << " < " << absolute_step_tolerance
                      << std::endl;
          has_converged = true;
        }
      else if (absolute_step_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver absolute step size "
                      << (norm_delta / steplength)
                      << " > " << absolute_step_tolerance
                      << std::endl;
        }

      // Is our relative Newton step size small enough?
      if (norm_delta / steplength / max_solution_norm <
          relative_step_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver converged, step " << l
                      << ", relative step size "
                      << (norm_delta / steplength / max_solution_norm)
                      << " < " << relative_step_tolerance
                      << std::endl;
          has_converged = true;
        }
      else if (relative_step_tolerance)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver relative step size "
                      << (norm_delta / steplength / max_solution_norm)
                      << " > " << relative_step_tolerance
                      << std::endl;
        }

      // Terminate the solution iteration if the difference between
      // this iteration and the last is sufficiently small.
      if (has_converged)
        {
          break;
        }
      if (l >= max_nonlinear_iterations - 1)
        {
          if (!quiet)
            std::cout << "  Nonlinear solver DIVERGED at step " << l
                      << std::endl;
          error();
          continue;
        }
    } // end nonlinear loop

  // Copy the final nonlinear iterate into the current_solution,
  // for other libMesh functions that expect it

  solution = newton_iterate;
  solution.close();

  // We may need to localize a parallel solution
  _system.update ();

  STOP_LOG("solve()", "NewtonSolver");
}
<|endoftext|>