<commit_before>/*
** Copyright 1986, 1987, 1988, 1989, 1990, 1991 by the Condor Design Team
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the Condor Design Team not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission.  The University of Wisconsin and the Condor
** Design Team make no representations about the suitability of this
** software for any purpose.  It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE CONDOR DESIGN TEAM DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE CONDOR DESIGN TEAM BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Authors:  Allan Bricker and Michael J. Litzkow,
** 	         University of Wisconsin, Computer Sciences Dept.
**
** Modified by : Dhaval N. Shah
**               University of Wisconsin, Computer Sciences Dept.
** Uses <IP:PORT> rather than hostnames
**
*/

#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"

static char *_FileName_ = __FILE__;		/* Used by EXCEPT */

#if !defined(WIN32)
#include "condor_fdset.h"
#endif

#include "sched.h"
#include "clib.h"
#include "exit.h"

#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "condor_qmgr.h"
#include "scheduler.h"
#include "condor_adtypes.h"
#include "condor_uid.h"

#if defined(BSD43) || defined(DYNIX)
#	define WEXITSTATUS(x) ((x).w_retcode)
#	define WTERMSIG(x) ((x).w_termsig)
#endif

extern "C"
{
	int		ReadLog(char*);
}
extern	void	mark_jobs_idle();

// global variables to control the daemon's running and logging
char*		Spool;							// spool directory
char*		mySubSystem = "SCHEDD";

// global objects
Scheduler	scheduler;
char		Name[MAXHOSTNAMELEN];
int			ScheddName = 0;

void Init();

void usage(char* name)
{
	dprintf( D_ALWAYS, "Usage: %s [-f] [-t] [-n schedd_name]", name);
	exit( 1 );
}

int
main_init(int argc, char* argv[])
{
	char**		ptr;
	char		job_queue_name[_POSIX_PATH_MAX];

	for(ptr = argv + 1; *ptr; ptr++)
	{
		if(ptr[0][0] != '-')
		{
			usage(argv[0]);
		}
		switch(ptr[0][1])
		{
		  case 'n':
			strcpy(Name, *(++ptr));
			ScheddName++;
			break;
		  default:
			usage(argv[0]);
		}
	}

	ClassAd *ScheddClassad = new ClassAd();
	config( ScheddClassad, mySubSystem );

	Init();

	// if a name if not specified, assume the name of the machine
	if(!ScheddName)
	{
		gethostname(Name, MAXHOSTNAMELEN);
	}

	ScheddClassad->SetMyTypeName(SCHEDD_ADTYPE);
	ScheddClassad->SetTargetTypeName("");

	// throw the name into the machine ad
	{
		char	expr[200];

		sprintf(expr, "Name = \"%s\"", Name);
		ScheddClassad->Insert(expr);
	}

	sprintf(job_queue_name, "%s/job_queue.log", Spool);
	InitJobQueue(job_queue_name);
	mark_jobs_idle();

	// initialize all the modules
	scheduler.SetClassAd(ScheddClassad);
	scheduler.Init();
	scheduler.Register(daemonCore);
	scheduler.SetCommandPort(daemonCore->InfoCommandPort());

	scheduler.timeout();

	return 0;
}

void Init()
{
	Spool = param("SPOOL");
	if(!Spool)
	{
		EXCEPT("No spool directory specified");
	}
}

int
main_config()
{
	scheduler.reconfig();
	return 0;
}

int
main_shutdown_fast()
{
	scheduler.shutdown_fast();
	return 0;
}

int
main_shutdown_graceful()
{
	scheduler.shutdown_graceful();
	return 0;
}

<commit_msg>no longer need to pass daemonCore to Register function<commit_after>/*
** Copyright 1986, 1987, 1988, 1989, 1990, 1991 by the Condor Design Team
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the Condor Design Team not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission.  The University of Wisconsin and the Condor
** Design Team make no representations about the suitability of this
** software for any purpose.  It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE CONDOR DESIGN TEAM DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE CONDOR DESIGN TEAM BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Authors:  Allan Bricker and Michael J. Litzkow,
** 	         University of Wisconsin, Computer Sciences Dept.
**
** Modified by : Dhaval N. Shah
**               University of Wisconsin, Computer Sciences Dept.
** Uses <IP:PORT> rather than hostnames
**
*/

#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"

static char *_FileName_ = __FILE__;		/* Used by EXCEPT */

#if !defined(WIN32)
#include "condor_fdset.h"
#endif

#include "sched.h"
#include "clib.h"
#include "exit.h"

#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "condor_qmgr.h"
#include "scheduler.h"
#include "condor_adtypes.h"
#include "condor_uid.h"

#if defined(BSD43) || defined(DYNIX)
#	define WEXITSTATUS(x) ((x).w_retcode)
#	define WTERMSIG(x) ((x).w_termsig)
#endif

extern "C"
{
	int		ReadLog(char*);
}
extern	void	mark_jobs_idle();

// global variables to control the daemon's running and logging
char*		Spool;							// spool directory
char*		mySubSystem = "SCHEDD";

// global objects
Scheduler	scheduler;
char		Name[MAXHOSTNAMELEN];
int			ScheddName = 0;

void Init();

void usage(char* name)
{
	dprintf( D_ALWAYS, "Usage: %s [-f] [-t] [-n schedd_name]", name);
	exit( 1 );
}

int
main_init(int argc, char* argv[])
{
	char**		ptr;
	char		job_queue_name[_POSIX_PATH_MAX];

	for(ptr = argv + 1; *ptr; ptr++)
	{
		if(ptr[0][0] != '-')
		{
			usage(argv[0]);
		}
		switch(ptr[0][1])
		{
		  case 'n':
			strcpy(Name, *(++ptr));
			ScheddName++;
			break;
		  default:
			usage(argv[0]);
		}
	}

	ClassAd *ScheddClassad = new ClassAd();
	config( ScheddClassad, mySubSystem );

	Init();

	// if a name if not specified, assume the name of the machine
	if(!ScheddName)
	{
		gethostname(Name, MAXHOSTNAMELEN);
	}

	ScheddClassad->SetMyTypeName(SCHEDD_ADTYPE);
	ScheddClassad->SetTargetTypeName("");

	// throw the name into the machine ad
	{
		char	expr[200];

		sprintf(expr, "Name = \"%s\"", Name);
		ScheddClassad->Insert(expr);
	}

	sprintf(job_queue_name, "%s/job_queue.log", Spool);
	InitJobQueue(job_queue_name);
	mark_jobs_idle();

	// initialize all the modules
	scheduler.SetClassAd(ScheddClassad);
	scheduler.Init();
	scheduler.Register();
	scheduler.SetCommandPort(daemonCore->InfoCommandPort());

	scheduler.timeout();

	return 0;
}

void Init()
{
	Spool = param("SPOOL");
	if(!Spool)
	{
		EXCEPT("No spool directory specified");
	}
}

int
main_config()
{
	scheduler.reconfig();
	return 0;
}

int
main_shutdown_fast()
{
	scheduler.shutdown_fast();
	return 0;
}

int
main_shutdown_graceful()
{
	scheduler.shutdown_graceful();
	return 0;
}

<|endoftext|>


<commit_before>/*
 * GenerativeConn.cpp
 *
 *  Created on: Oct 27, 2010
 *      Author: pschultz
 */

#include "GenerativeConn.hpp"

namespace PV {

GenerativeConn::GenerativeConn() {
    initialize_base();
}  // end of GenerativeConn::GenerativeConn()

GenerativeConn::GenerativeConn(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, ChannelType channel) {
       initialize_base();
       initialize(name, hc, pre, post, channel);
}  // end of GenerativeConn::GenerativeConn(const char *, HyPerCol *,
   //   HyPerLayer *, HyPerLayer *, int)

GenerativeConn::GenerativeConn(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, ChannelType channel,
        const char * filename) {
       initialize_base();
       initialize(name, hc, pre, post, channel, filename);
}  // end of GenerativeConn::GenerativeConn(const char *, HyPerCol *,
   //   HyPerLayer *, HyPerLayer *, int, const char *)

int GenerativeConn::initialize_base() {
    relaxation = 1.0;
    nonnegConstraintFlag = false;
    normalizeMethod = 0;
    return PV_SUCCESS;
    // KernelConn constructor calls KernelConn::initialize_base()
    // and the similarly for HyPerConn constructor, so I don't need to.
}

int GenerativeConn::initialize(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, ChannelType channel) {
    return initialize(name, hc, pre, post, channel, NULL);
}

int GenerativeConn::initialize(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, ChannelType channel,
        const char * filename) {
    PVParams * params = hc->parameters();
    relaxation = params->value(name, "relaxation", 1.0f);
    nonnegConstraintFlag = (bool) params->value(name, "nonnegConstraintFlag", 0.f); // default is not to constrain nonnegative.
    normalizeMethod = (int) params->value(name, "normalizeMethod", 0.f); // default is not to constrain kernelwise to spheres.
    if( normalizeMethod ) {
       normalizeConstant = params->value(name, "normalizeConstant", 1.0f);
    }
    PeriodicUpdateConn::initialize(name, hc, pre, post, channel, filename);
    return PV_SUCCESS;
}

int GenerativeConn::updateWeights(int axonID) {
    printf("updateWeights for GenerativeConn %s\n", name);

    int nPre = preSynapticLayer()->getNumNeurons();
    int nx = preSynapticLayer()->getLayerLoc()->nx;
    int ny = preSynapticLayer()->getLayerLoc()->ny;
    int nf = preSynapticLayer()->getLayerLoc()->nf;
    int pad = preSynapticLayer()->getLayerLoc()->nb;
    for(int kPre=0; kPre<nPre;kPre++) {
        int kExt = kIndexExtended(kPre, nx, ny, nf, pad);

        PVAxonalArbor * arbor = axonalArbor(kPre, 0);
        size_t offset = arbor->offset;
        pvdata_t preact = preSynapticLayer()->getCLayer()->activity->data[kExt];
        pvdata_t a = relaxation*preact;
        int nyp = arbor->weights->ny;
        int nk = arbor->weights->nx * arbor->weights->nf;
        pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);
        int sya = arbor->data->sy;
        pvdata_t * wtpatch = arbor->weights->data;
        int syw = arbor->weights->sy;
        for( int y=0; y<nyp; y++ ) {
            int lineoffsetw = 0;
            int lineoffseta = 0;
            for( int k=0; k<nk; k++ ) {
               float w = wtpatch[lineoffsetw + k] + a*postactRef[lineoffseta + k];
               if( nonnegConstraintFlag && w < 0) w = 0;
               wtpatch[lineoffsetw + k] = w;
            }
            lineoffsetw += syw;
            lineoffseta += sya;
        }
    }
    normalizeWeights( kernelPatches, numDataPatches(0) );

    return PV_SUCCESS;
}  // end of GenerativeConn::updateWeights(int);

PVPatch ** GenerativeConn::normalizeWeights(PVPatch ** patches, int numPatches) {
   int neuronsperpatch;
   switch( normalizeMethod ) {
   case 0:
      break;
   case 1:
      patches = KernelConn::normalizeWeights(patches, numPatches);
      break;
   case 2:
      neuronsperpatch = (patches[0]->nx)*(patches[0]->ny)*(patches[0]->nf);
      for( int n=0; n<neuronsperpatch; n++ ) {
         pvdata_t s = 0;
         for( int k=0; k<numPatches; k++ ) {
            pvdata_t d = patches[k]->data[n];
            s += d*d;
         }
         for( int k=0; k<numPatches; k++ ) {
            patches[k]->data[n] *= normalizeConstant/sqrt(s);
         }
      }
      break;
   default:
      fprintf(stderr,"Connection \"%s\": Unrecognized normalizeMethod %d.  Using HyPerConn::normalize().", this->getName(), normalizeMethod);
      break;
   }
   return patches;
}  // end of GenerativeConn::normalizeWeights

}  // end of namespace PV block
<commit_msg>Added normalization method to constrain sum of squares over features to a constant.<commit_after>/*
 * GenerativeConn.cpp
 *
 *  Created on: Oct 27, 2010
 *      Author: pschultz
 */

#include "GenerativeConn.hpp"

namespace PV {

GenerativeConn::GenerativeConn() {
    initialize_base();
}  // end of GenerativeConn::GenerativeConn()

GenerativeConn::GenerativeConn(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, ChannelType channel) {
       initialize_base();
       initialize(name, hc, pre, post, channel);
}  // end of GenerativeConn::GenerativeConn(const char *, HyPerCol *,
   //   HyPerLayer *, HyPerLayer *, int)

GenerativeConn::GenerativeConn(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, ChannelType channel,
        const char * filename) {
       initialize_base();
       initialize(name, hc, pre, post, channel, filename);
}  // end of GenerativeConn::GenerativeConn(const char *, HyPerCol *,
   //   HyPerLayer *, HyPerLayer *, int, const char *)

int GenerativeConn::initialize_base() {
    relaxation = 1.0;
    nonnegConstraintFlag = false;
    normalizeMethod = 0;
    return PV_SUCCESS;
    // KernelConn constructor calls KernelConn::initialize_base()
    // and the similarly for HyPerConn constructor, so I don't need to.
}

int GenerativeConn::initialize(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, ChannelType channel) {
    return initialize(name, hc, pre, post, channel, NULL);
}

int GenerativeConn::initialize(const char * name, HyPerCol * hc,
        HyPerLayer * pre, HyPerLayer * post, ChannelType channel,
        const char * filename) {
    PVParams * params = hc->parameters();
    relaxation = params->value(name, "relaxation", 1.0f);
    nonnegConstraintFlag = (bool) params->value(name, "nonnegConstraintFlag", 0.f); // default is not to constrain nonnegative.
    normalizeMethod = (int) params->value(name, "normalizeMethod", 0.f); // default is not to constrain kernelwise to spheres.
    if( normalizeMethod ) {
       normalizeConstant = params->value(name, "normalizeConstant", 1.0f);
    }
    PeriodicUpdateConn::initialize(name, hc, pre, post, channel, filename);
    return PV_SUCCESS;
}

int GenerativeConn::updateWeights(int axonID) {
    int nPre = preSynapticLayer()->getNumNeurons();
    int nx = preSynapticLayer()->getLayerLoc()->nx;
    int ny = preSynapticLayer()->getLayerLoc()->ny;
    int nf = preSynapticLayer()->getLayerLoc()->nf;
    int pad = preSynapticLayer()->getLayerLoc()->nb;
    for(int kPre=0; kPre<nPre;kPre++) {
        int kExt = kIndexExtended(kPre, nx, ny, nf, pad);

        PVAxonalArbor * arbor = axonalArbor(kPre, 0);
        size_t offset = arbor->offset;
        pvdata_t preact = preSynapticLayer()->getCLayer()->activity->data[kExt];
        pvdata_t a = relaxation*preact;
        int nyp = arbor->weights->ny;
        int nk = arbor->weights->nx * arbor->weights->nf;
        pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);
        int sya = arbor->data->sy;
        pvdata_t * wtpatch = arbor->weights->data;
        int syw = arbor->weights->sy;
        for( int y=0; y<nyp; y++ ) {
            int lineoffsetw = 0;
            int lineoffseta = 0;
            for( int k=0; k<nk; k++ ) {
               float w = wtpatch[lineoffsetw + k] + a*postactRef[lineoffseta + k];
               if( nonnegConstraintFlag && w < 0) w = 0;
               wtpatch[lineoffsetw + k] = w;
            }
            lineoffsetw += syw;
            lineoffseta += sya;
        }
    }
    normalizeWeights( kernelPatches, numDataPatches(0) );

    return PV_SUCCESS;
}  // end of GenerativeConn::updateWeights(int);

PVPatch ** GenerativeConn::normalizeWeights(PVPatch ** patches, int numPatches) {
   int neuronsperpatch;
   switch( normalizeMethod ) {
   case 0:
      break;
   case 1:
      patches = KernelConn::normalizeWeights(patches, numPatches);
      break;
   case 2:
      neuronsperpatch = (patches[0]->nx)*(patches[0]->ny)*(patches[0]->nf);
      for( int n=0; n<neuronsperpatch; n++ ) {
         pvdata_t s = 0;
         for( int k=0; k<numPatches; k++ ) {
            pvdata_t d = patches[k]->data[n];
            s += d*d;
         }
         for( int k=0; k<numPatches; k++ ) {
            patches[k]->data[n] *= normalizeConstant/sqrt(s);
         }
      }
      break;
   case 3:
      neuronsperpatch = (patches[0]->nx)*(patches[0]->ny)*(patches[0]->nf);
      for( int k=0; k<numPatches; k++ ) {
         PVPatch * curpatch = patches[k];
         pvdata_t s = 0;
         for( int n=0; n<neuronsperpatch; n++ ) {
            pvdata_t d = curpatch->data[n];
            s += d*d;
         }
         for( int n=0; n<neuronsperpatch; n++ ) {
            curpatch->data[n] *= normalizeConstant/sqrt(s);
         }
      }
      break;
   default:
      fprintf(stderr,"Connection \"%s\": Unrecognized normalizeMethod %d.  Using HyPerConn::normalize().\n", this->getName(), normalizeMethod);
      break;
   }
   return patches;
}  // end of GenerativeConn::normalizeWeights

}  // end of namespace PV block
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xbmread.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:42:44 $
 *
 *  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
 *
 ************************************************************************/

#define XBMMINREAD 512

#define _XBMPRIVATE
#include <ctype.h>
#include "xbmread.hxx"

// -------------
// - XBMReader -
// -------------

XBMReader::XBMReader( SvStream& rStm, void* pCallData ) :
            rIStm           ( rStm ),
            pAcc1           ( NULL ),
            nLastPos        ( rStm.Tell() ),
            nWidth          ( 0 ),
            nHeight         ( 0 ),
            bStatus         ( TRUE )
{
    pHexTable = new short[ 256 ];
    maUpperName = String::CreateFromAscii( "SVIXBM", 6 );
    InitTable();
}

// ------------------------------------------------------------------------

XBMReader::~XBMReader()
{
    delete[] pHexTable;

    if( pAcc1 )
        aBmp1.ReleaseAccess( pAcc1 );
}

// ------------------------------------------------------------------------

void XBMReader::InitTable()
{
    memset( pHexTable, 0, sizeof( short ) );

    pHexTable['0'] = 0;
    pHexTable['1'] = 1;
    pHexTable['2'] = 2;
    pHexTable['3'] = 3;
    pHexTable['4'] = 4;
    pHexTable['5'] = 5;
    pHexTable['6'] = 6;
    pHexTable['7'] = 7;
    pHexTable['8'] = 8;
    pHexTable['9'] = 9;
    pHexTable['A'] = 10;
    pHexTable['B'] = 11;
    pHexTable['C'] = 12;
    pHexTable['D'] = 13;
    pHexTable['E'] = 14;
    pHexTable['F'] = 15;
    pHexTable['X'] = 0;
    pHexTable['a'] = 10;
    pHexTable['b'] = 11;
    pHexTable['c'] = 12;
    pHexTable['d'] = 13;
    pHexTable['e'] = 14;
    pHexTable['f'] = 15;
    pHexTable['x'] = 0;
    pHexTable[' '] =     -1;
    pHexTable[','] = -1;
    pHexTable['}'] = -1;
    pHexTable['\n'] = -1;
    pHexTable['\t'] = -1;
    pHexTable['\0'] = -1;
}

// ------------------------------------------------------------------------

ByteString XBMReader::FindTokenLine( SvStream* pInStm, const char* pTok1,
                                 const char* pTok2, const char* pTok3 )
{
    ByteString  aRet;
    long        nPos1;
    long        nPos2;
    long        nPos3;

    bStatus = FALSE;

    do
    {
        if( !pInStm->ReadLine( aRet ) )
            break;

        if( pTok1 )
        {
            if( ( nPos1 = aRet.Search( pTok1 ) ) != STRING_NOTFOUND )
            {
                bStatus = TRUE;

                if( pTok2 )
                {
                    bStatus = FALSE;

                    if( ( ( nPos2 = aRet.Search( pTok2 ) ) != STRING_NOTFOUND ) &&
                         ( nPos2 > nPos1 ) )
                    {
                        bStatus = TRUE;

                        if( pTok3 )
                        {
                            bStatus = FALSE;

                            if( ( ( nPos3 = aRet.Search( pTok3 ) ) != STRING_NOTFOUND ) && ( nPos3 > nPos2 ) )
                                bStatus = TRUE;
                        }
                    }
                }
            }
        }
    }
    while( !bStatus );

    return aRet;
}

// ------------------------------------------------------------------------

long XBMReader::ParseDefine( const sal_Char* pDefine )
{
    long    nRet = 0;
    char*   pTmp = (char*) pDefine;
    char    cTmp;

    // bis zum Ende gehen
    pTmp += ( strlen( pDefine ) - 1 );
    cTmp = *pTmp--;

    // letzte Ziffer suchen
    while( pHexTable[ cTmp ] == -1 )
        cTmp = *pTmp--;

    // bis vor die Zahl laufen
    while( pHexTable[ cTmp ] != -1 )
        cTmp = *pTmp--;

    // auf Anfang der Zahl gehen
    pTmp += 2;

    // Hex lesen
    if( ( pTmp[0] == '0' ) && ( ( pTmp[1] == 'X' ) || ( pTmp[1] == 'x' ) ) )
    {
        pTmp += 2;
        cTmp = *pTmp++;

        while ( pHexTable[ cTmp ] != -1 )
        {
            nRet = ( nRet << 4 ) + pHexTable[ cTmp ];
            cTmp = *pTmp++;
        }
    }
    // Dezimal lesen
    else
    {
        cTmp = *pTmp++;
        while( ( cTmp >= '0' ) && ( cTmp <= '9' ) )
        {
            nRet = nRet * 10 + ( cTmp - '0' );
            cTmp = *pTmp++;
        }
    }

    return nRet;
}

// ------------------------------------------------------------------------

BOOL XBMReader::ParseData( SvStream* pInStm, const ByteString& aLastLine, XBMFormat eFormat )
{
    ByteString      aLine;
    long            nRow = 0;
    long            nCol = 0;
    long            nBits = ( eFormat == XBM10 ) ? 16 : 8;
    long            nBit;
    USHORT          nValue;
    USHORT          nDigits;
    BOOL            bFirstLine = TRUE;

    while( nRow < nHeight )
    {
        if( bFirstLine )
        {
            long nPos;

            // einfuehrende geschweifte Klammer loeschen
            if( (nPos = ( aLine = aLastLine ).Search( '{' ) ) != STRING_NOTFOUND )
                aLine.Erase( 0, nPos + 1 );

            bFirstLine = FALSE;
        }
        else if( !pInStm->ReadLine( aLine ) )
            break;

        if( aLine.Len() )
        {
            const USHORT nCount = aLine.GetTokenCount( ',' );

            for( USHORT i = 0; ( i < nCount ) && ( nRow < nHeight ); i++ )
            {
                const ByteString    aToken( aLine.GetToken( i, ',' ) );
                const ULONG         nLen = aToken.Len();
                BOOL                bProcessed = FALSE;

                nBit = nDigits = nValue = 0;

                for( ULONG n = 0UL; n < nLen; n++ )
                {
                    const unsigned char cChar = aToken.GetChar( n );
                    const short         nTable = pHexTable[ cChar ];

                    if( isxdigit( cChar ) || !nTable )
                    {
                        nValue = ( nValue << 4 ) + nTable;
                        nDigits++;
                        bProcessed = TRUE;
                    }
                    else if( ( nTable < 0 ) && nDigits )
                    {
                        bProcessed = TRUE;
                        break;
                    }
                }

                if( bProcessed )
                {
                    while( ( nCol < nWidth ) && ( nBit < nBits ) )
                        pAcc1->SetPixel( nRow, nCol++, ( nValue & ( 1 << nBit++ ) ) ? aBlack : aWhite );

                    if( nCol == nWidth )
                        nCol = 0, nRow++;
                }
            }
        }
    }

    return TRUE;
}

// ------------------------------------------------------------------------

ReadState XBMReader::ReadXBM( Graphic& rGraphic )
{
    ReadState   eReadState;
    BYTE        cDummy;

    // sehen, ob wir _alles_ lesen koennen
    rIStm.Seek( STREAM_SEEK_TO_END );
    rIStm >> cDummy;

    // falls wir nicht alles lesen koennen
    // kehren wir zurueck und warten auf neue Daten
    if ( rIStm.GetError() != ERRCODE_IO_PENDING )
    {
        ByteString  aLine;
        int         nValue;

        rIStm.Seek( nLastPos );
        bStatus = FALSE;
        aLine = FindTokenLine( &rIStm, "#define", "_width" );

        if ( bStatus )
        {
            if ( ( nValue = (int) ParseDefine( aLine.GetBuffer() ) ) > 0 )
            {
                nWidth = nValue;
                aLine = FindTokenLine( &rIStm, "#define", "_height" );

                // Falls die Hoehe nicht folgt, suchen wir noch
                // einmal vom Anfang der Datei an
                if ( !bStatus )
                {
                    rIStm.Seek( nLastPos );
                    aLine = FindTokenLine( &rIStm, "#define", "_height" );
                }
            }
            else
                bStatus = FALSE;

            if ( bStatus )
            {
                if ( ( nValue = (int) ParseDefine( aLine.GetBuffer() ) ) > 0 )
                {
                    nHeight = nValue;
                    aLine = FindTokenLine( &rIStm, "static", "_bits" );

                    if ( bStatus )
                    {
                        XBMFormat eFormat = XBM10;

                        if ( aLine.Search( "short" ) != STRING_NOTFOUND )
                            eFormat = XBM10;
                        else if ( aLine.Search( "char" ) != STRING_NOTFOUND )
                            eFormat = XBM11;
                        else
                            bStatus = FALSE;

                        if ( bStatus && nWidth && nHeight )
                        {
                            aBmp1 = Bitmap( Size( nWidth, nHeight ), 1 );
                            pAcc1 = aBmp1.AcquireWriteAccess();

                            if( pAcc1 )
                            {
                                aWhite = pAcc1->GetBestMatchingColor( Color( COL_WHITE ) );
                                aBlack = pAcc1->GetBestMatchingColor( Color( COL_BLACK ) );
                                bStatus = ParseData( &rIStm, aLine, eFormat );
                            }
                            else
                                bStatus = FALSE;
                        }
                    }
                }
            }
        }

        if( bStatus )
        {
            Bitmap aBlackBmp( Size( pAcc1->Width(), pAcc1->Height() ), 1 );

            aBmp1.ReleaseAccess( pAcc1 ), pAcc1 = NULL;
            aBlackBmp.Erase( Color( COL_BLACK ) );
            rGraphic = BitmapEx( aBlackBmp, aBmp1 );
            eReadState = XBMREAD_OK;
        }
        else
            eReadState = XBMREAD_ERROR;
    }
    else
    {
        rIStm.ResetError();
        eReadState = XBMREAD_NEED_MORE;
    }

    return eReadState;
}

// -------------
// - ImportXBM -
// -------------

BOOL ImportXBM( SvStream& rStm, Graphic& rGraphic, void* pCallerData )
{
    XBMReader*  pXBMReader = (XBMReader*) rGraphic.GetContext();
    ReadState   eReadState;
    BOOL        bRet = TRUE;

    if( !pXBMReader )
        pXBMReader = new XBMReader( rStm, pCallerData );

    rGraphic.SetContext( NULL );
    eReadState = pXBMReader->ReadXBM( rGraphic );

    if( eReadState == XBMREAD_ERROR )
    {
        bRet = FALSE;
        delete pXBMReader;
    }
    else if( eReadState == XBMREAD_OK )
        delete pXBMReader;
    else
        rGraphic.SetContext( pXBMReader );

    return bRet;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.3.60); FILE MERGED 2005/11/15 17:54:36 pl 1.3.60.1: #i55991# removed warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xbmread.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 21:06: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
 *
 ************************************************************************/

#define XBMMINREAD 512

#define _XBMPRIVATE
#include <ctype.h>
#include "xbmread.hxx"

// -------------
// - XBMReader -
// -------------

XBMReader::XBMReader( SvStream& rStm, void* ) :
            rIStm           ( rStm ),
            pAcc1           ( NULL ),
            nLastPos        ( rStm.Tell() ),
            nWidth          ( 0 ),
            nHeight         ( 0 ),
            bStatus         ( TRUE )
{
    pHexTable = new short[ 256 ];
    maUpperName = String::CreateFromAscii( "SVIXBM", 6 );
    InitTable();
}

// ------------------------------------------------------------------------

XBMReader::~XBMReader()
{
    delete[] pHexTable;

    if( pAcc1 )
        aBmp1.ReleaseAccess( pAcc1 );
}

// ------------------------------------------------------------------------

void XBMReader::InitTable()
{
    memset( pHexTable, 0, sizeof( short ) );

    pHexTable['0'] = 0;
    pHexTable['1'] = 1;
    pHexTable['2'] = 2;
    pHexTable['3'] = 3;
    pHexTable['4'] = 4;
    pHexTable['5'] = 5;
    pHexTable['6'] = 6;
    pHexTable['7'] = 7;
    pHexTable['8'] = 8;
    pHexTable['9'] = 9;
    pHexTable['A'] = 10;
    pHexTable['B'] = 11;
    pHexTable['C'] = 12;
    pHexTable['D'] = 13;
    pHexTable['E'] = 14;
    pHexTable['F'] = 15;
    pHexTable['X'] = 0;
    pHexTable['a'] = 10;
    pHexTable['b'] = 11;
    pHexTable['c'] = 12;
    pHexTable['d'] = 13;
    pHexTable['e'] = 14;
    pHexTable['f'] = 15;
    pHexTable['x'] = 0;
    pHexTable[' '] =     -1;
    pHexTable[','] = -1;
    pHexTable['}'] = -1;
    pHexTable['\n'] = -1;
    pHexTable['\t'] = -1;
    pHexTable['\0'] = -1;
}

// ------------------------------------------------------------------------

ByteString XBMReader::FindTokenLine( SvStream* pInStm, const char* pTok1,
                                 const char* pTok2, const char* pTok3 )
{
    ByteString  aRet;
    long        nPos1;
    long        nPos2;
    long        nPos3;

    bStatus = FALSE;

    do
    {
        if( !pInStm->ReadLine( aRet ) )
            break;

        if( pTok1 )
        {
            if( ( nPos1 = aRet.Search( pTok1 ) ) != STRING_NOTFOUND )
            {
                bStatus = TRUE;

                if( pTok2 )
                {
                    bStatus = FALSE;

                    if( ( ( nPos2 = aRet.Search( pTok2 ) ) != STRING_NOTFOUND ) &&
                         ( nPos2 > nPos1 ) )
                    {
                        bStatus = TRUE;

                        if( pTok3 )
                        {
                            bStatus = FALSE;

                            if( ( ( nPos3 = aRet.Search( pTok3 ) ) != STRING_NOTFOUND ) && ( nPos3 > nPos2 ) )
                                bStatus = TRUE;
                        }
                    }
                }
            }
        }
    }
    while( !bStatus );

    return aRet;
}

// ------------------------------------------------------------------------

long XBMReader::ParseDefine( const sal_Char* pDefine )
{
    long    nRet = 0;
    char*   pTmp = (char*) pDefine;
    char    cTmp;

    // bis zum Ende gehen
    pTmp += ( strlen( pDefine ) - 1 );
    cTmp = *pTmp--;

    // letzte Ziffer suchen
    while( pHexTable[ cTmp ] == -1 )
        cTmp = *pTmp--;

    // bis vor die Zahl laufen
    while( pHexTable[ cTmp ] != -1 )
        cTmp = *pTmp--;

    // auf Anfang der Zahl gehen
    pTmp += 2;

    // Hex lesen
    if( ( pTmp[0] == '0' ) && ( ( pTmp[1] == 'X' ) || ( pTmp[1] == 'x' ) ) )
    {
        pTmp += 2;
        cTmp = *pTmp++;

        while ( pHexTable[ cTmp ] != -1 )
        {
            nRet = ( nRet << 4 ) + pHexTable[ cTmp ];
            cTmp = *pTmp++;
        }
    }
    // Dezimal lesen
    else
    {
        cTmp = *pTmp++;
        while( ( cTmp >= '0' ) && ( cTmp <= '9' ) )
        {
            nRet = nRet * 10 + ( cTmp - '0' );
            cTmp = *pTmp++;
        }
    }

    return nRet;
}

// ------------------------------------------------------------------------

BOOL XBMReader::ParseData( SvStream* pInStm, const ByteString& aLastLine, XBMFormat eFormat )
{
    ByteString      aLine;
    long            nRow = 0;
    long            nCol = 0;
    long            nBits = ( eFormat == XBM10 ) ? 16 : 8;
    long            nBit;
    USHORT          nValue;
    USHORT          nDigits;
    BOOL            bFirstLine = TRUE;

    while( nRow < nHeight )
    {
        if( bFirstLine )
        {
            long nPos;

            // einfuehrende geschweifte Klammer loeschen
            if( (nPos = ( aLine = aLastLine ).Search( '{' ) ) != STRING_NOTFOUND )
                aLine.Erase( 0, nPos + 1 );

            bFirstLine = FALSE;
        }
        else if( !pInStm->ReadLine( aLine ) )
            break;

        if( aLine.Len() )
        {
            const USHORT nCount = aLine.GetTokenCount( ',' );

            for( USHORT i = 0; ( i < nCount ) && ( nRow < nHeight ); i++ )
            {
                const ByteString    aToken( aLine.GetToken( i, ',' ) );
                const ULONG         nLen = aToken.Len();
                BOOL                bProcessed = FALSE;

                nBit = nDigits = nValue = 0;

                for( ULONG n = 0UL; n < nLen; n++ )
                {
                    const unsigned char cChar = aToken.GetChar( n );
                    const short         nTable = pHexTable[ cChar ];

                    if( isxdigit( cChar ) || !nTable )
                    {
                        nValue = ( nValue << 4 ) + nTable;
                        nDigits++;
                        bProcessed = TRUE;
                    }
                    else if( ( nTable < 0 ) && nDigits )
                    {
                        bProcessed = TRUE;
                        break;
                    }
                }

                if( bProcessed )
                {
                    while( ( nCol < nWidth ) && ( nBit < nBits ) )
                        pAcc1->SetPixel( nRow, nCol++, ( nValue & ( 1 << nBit++ ) ) ? aBlack : aWhite );

                    if( nCol == nWidth )
                        nCol = 0, nRow++;
                }
            }
        }
    }

    return TRUE;
}

// ------------------------------------------------------------------------

ReadState XBMReader::ReadXBM( Graphic& rGraphic )
{
    ReadState   eReadState;
    BYTE        cDummy;

    // sehen, ob wir _alles_ lesen koennen
    rIStm.Seek( STREAM_SEEK_TO_END );
    rIStm >> cDummy;

    // falls wir nicht alles lesen koennen
    // kehren wir zurueck und warten auf neue Daten
    if ( rIStm.GetError() != ERRCODE_IO_PENDING )
    {
        ByteString  aLine;
        int         nValue;

        rIStm.Seek( nLastPos );
        bStatus = FALSE;
        aLine = FindTokenLine( &rIStm, "#define", "_width" );

        if ( bStatus )
        {
            if ( ( nValue = (int) ParseDefine( aLine.GetBuffer() ) ) > 0 )
            {
                nWidth = nValue;
                aLine = FindTokenLine( &rIStm, "#define", "_height" );

                // Falls die Hoehe nicht folgt, suchen wir noch
                // einmal vom Anfang der Datei an
                if ( !bStatus )
                {
                    rIStm.Seek( nLastPos );
                    aLine = FindTokenLine( &rIStm, "#define", "_height" );
                }
            }
            else
                bStatus = FALSE;

            if ( bStatus )
            {
                if ( ( nValue = (int) ParseDefine( aLine.GetBuffer() ) ) > 0 )
                {
                    nHeight = nValue;
                    aLine = FindTokenLine( &rIStm, "static", "_bits" );

                    if ( bStatus )
                    {
                        XBMFormat eFormat = XBM10;

                        if ( aLine.Search( "short" ) != STRING_NOTFOUND )
                            eFormat = XBM10;
                        else if ( aLine.Search( "char" ) != STRING_NOTFOUND )
                            eFormat = XBM11;
                        else
                            bStatus = FALSE;

                        if ( bStatus && nWidth && nHeight )
                        {
                            aBmp1 = Bitmap( Size( nWidth, nHeight ), 1 );
                            pAcc1 = aBmp1.AcquireWriteAccess();

                            if( pAcc1 )
                            {
                                aWhite = pAcc1->GetBestMatchingColor( Color( COL_WHITE ) );
                                aBlack = pAcc1->GetBestMatchingColor( Color( COL_BLACK ) );
                                bStatus = ParseData( &rIStm, aLine, eFormat );
                            }
                            else
                                bStatus = FALSE;
                        }
                    }
                }
            }
        }

        if( bStatus )
        {
            Bitmap aBlackBmp( Size( pAcc1->Width(), pAcc1->Height() ), 1 );

            aBmp1.ReleaseAccess( pAcc1 ), pAcc1 = NULL;
            aBlackBmp.Erase( Color( COL_BLACK ) );
            rGraphic = BitmapEx( aBlackBmp, aBmp1 );
            eReadState = XBMREAD_OK;
        }
        else
            eReadState = XBMREAD_ERROR;
    }
    else
    {
        rIStm.ResetError();
        eReadState = XBMREAD_NEED_MORE;
    }

    return eReadState;
}

// -------------
// - ImportXBM -
// -------------

BOOL ImportXBM( SvStream& rStm, Graphic& rGraphic, void* pCallerData )
{
    XBMReader*  pXBMReader = (XBMReader*) rGraphic.GetContext();
    ReadState   eReadState;
    BOOL        bRet = TRUE;

    if( !pXBMReader )
        pXBMReader = new XBMReader( rStm, pCallerData );

    rGraphic.SetContext( NULL );
    eReadState = pXBMReader->ReadXBM( rGraphic );

    if( eReadState == XBMREAD_ERROR )
    {
        bRet = FALSE;
        delete pXBMReader;
    }
    else if( eReadState == XBMREAD_OK )
        delete pXBMReader;
    else
        rGraphic.SetContext( pXBMReader );

    return bRet;
}
<|endoftext|>


<commit_before>#include "MenuState.h"

#include <SFML\Graphics\RenderWindow.hpp>

MenuState::MenuState(StateStack& stateStack, Context& context, States::ID id)
	:
	State(stateStack, context, id),
	m_button(sf::Vector2f(100, 40), context.font, false),
	m_ipbox("ip:port"),
	m_namebox("username")
{
	m_button.setPosition(400, 400);
	m_button.setAction([this]() {
		State::Context* con = getContext();
		if (con->address)
			delete con->address;
		std::string address = m_ipbox.getValue();
		int pos = -1;
		pos = address.find(':');
		if (pos != -1)
		{
			std::string port = address.substr(pos + 1);
			address = address.substr(0, pos);
			con->address = new sf::IpAddress(address);
			con->username = m_namebox.getValue();
			con->port = std::atoi(port.c_str());
			requestStackPush(States::Game);
		}
	});
	m_button.setText("Connect");

	m_ipbox.setPosition(400, 350);
	m_ipbox.setSize(sf::Vector2f(400, 30));
	m_ipbox.setFont(*context.font);
	m_ipbox.deactivate();

	m_namebox.setPosition(400, 300);
	m_namebox.setSize(sf::Vector2f(400, 30));
	m_namebox.setFont(*context.font);
	m_namebox.activate();
}

MenuState::~MenuState()
{
}

bool MenuState::update(sf::Time& p_deltaTime)
{

	return false;
}

bool MenuState::handleEvents(const sf::Event& event)
{
	if (event.type == sf::Event::MouseButtonPressed)
	{
		sf::FloatRect mousePos(sf::Vector2f(event.mouseButton.x, event.mouseButton.y), sf::Vector2f(1,1));
		sf::FloatRect namerect = m_namebox.getRectangle();
		sf::FloatRect iprect = m_ipbox.getRectangle();
		if (mousePos.intersects(iprect))
		{
			m_ipbox.activate();
			m_namebox.deactivate();
		}
		else if (mousePos.intersects(namerect))
		{
			m_namebox.activate();
			m_ipbox.deactivate();
		}
	}
	else if (event.type == sf::Event::KeyPressed)
	{
		if (event.key.code == sf::Keyboard::Tab)
		{
			if (m_ipbox.isActive())
			{
				m_ipbox.deactivate();
				m_namebox.activate();
			}
			else
			{
				m_namebox.deactivate();
				m_ipbox.activate();
			}
		}
		else if (event.key.code == sf::Keyboard::Return)
		{
			m_button.activate();
		}
	}

	m_button.handleEvent(event);
	m_ipbox.handleEvent(event);
	m_namebox.handleEvent(event);
	return false;
}

bool MenuState::draw()
{
	getContext()->window->clear(sf::Color(64, 64, 64));
	getContext()->window->draw(m_button);
	getContext()->window->draw(m_ipbox);
	getContext()->window->draw(m_namebox);
	return true;
}<commit_msg>Port not required. Default is 2828<commit_after>#include "MenuState.h"

#include <SFML\Graphics\RenderWindow.hpp>

MenuState::MenuState(StateStack& stateStack, Context& context, States::ID id)
	:
	State(stateStack, context, id),
	m_button(sf::Vector2f(100, 40), context.font, false),
	m_ipbox("ip:port"),
	m_namebox("username")
{
	m_button.setPosition(400, 400);
	m_button.setAction([this]() {
		State::Context* con = getContext();
		if (con->address)
			delete con->address;
		std::string address = m_ipbox.getValue();
		int pos = -1;
		pos = address.find(':');
		if (pos != -1)
		{
			std::string port = address.substr(pos + 1);
			address = address.substr(0, pos);
			con->port = std::atoi(port.c_str());
		}
		else
		{
			con->port = 2828;
		}
		con->address = new sf::IpAddress(address);
		con->username = m_namebox.getValue();
		requestStackPush(States::Game);
	});
	m_button.setText("Connect");

	m_ipbox.setPosition(400, 350);
	m_ipbox.setSize(sf::Vector2f(400, 30));
	m_ipbox.setFont(*context.font);
	m_ipbox.deactivate();

	m_namebox.setPosition(400, 300);
	m_namebox.setSize(sf::Vector2f(400, 30));
	m_namebox.setFont(*context.font);
	m_namebox.activate();
}

MenuState::~MenuState()
{
}

bool MenuState::update(sf::Time& p_deltaTime)
{

	return false;
}

bool MenuState::handleEvents(const sf::Event& event)
{
	if (event.type == sf::Event::MouseButtonPressed)
	{
		sf::FloatRect mousePos(sf::Vector2f(event.mouseButton.x, event.mouseButton.y), sf::Vector2f(1,1));
		sf::FloatRect namerect = m_namebox.getRectangle();
		sf::FloatRect iprect = m_ipbox.getRectangle();
		if (mousePos.intersects(iprect))
		{
			m_ipbox.activate();
			m_namebox.deactivate();
		}
		else if (mousePos.intersects(namerect))
		{
			m_namebox.activate();
			m_ipbox.deactivate();
		}
	}
	else if (event.type == sf::Event::KeyPressed)
	{
		if (event.key.code == sf::Keyboard::Tab)
		{
			if (m_ipbox.isActive())
			{
				m_ipbox.deactivate();
				m_namebox.activate();
			}
			else
			{
				m_namebox.deactivate();
				m_ipbox.activate();
			}
		}
		else if (event.key.code == sf::Keyboard::Return)
		{
			m_button.activate();
		}
	}

	m_button.handleEvent(event);
	m_ipbox.handleEvent(event);
	m_namebox.handleEvent(event);
	return false;
}

bool MenuState::draw()
{
	getContext()->window->clear(sf::Color(64, 64, 64));
	getContext()->window->draw(m_button);
	getContext()->window->draw(m_ipbox);
	getContext()->window->draw(m_namebox);
	return true;
}<|endoftext|>


<commit_before>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************

// NOTE: This file follows nGraph format style.
// Follows nGraph naming convention for public APIs only, else MLIR naming convention.

#include "compiler.hpp"

#include "ngraph_dialect/dialect.hpp"
#include "ngraph_dialect/ops.hpp"
#include "ngraph_dialect/type.hpp"
#include "pass/ng_dialect_builder.hpp"
#include "pass/ng_dialect_fused_ops.hpp"

#include "ngraph/check.hpp"
#include "ngraph/descriptor/tensor.hpp"
#include "ngraph/graph_util.hpp"
#include "ngraph/node.hpp"
#include "ngraph/ops.hpp"
#include "ngraph/type/element_type.hpp"

#include "contrib/mlir/utils.hpp"

#include <llvm/ADT/STLExtras.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/ErrorOr.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Target/TargetMachine.h>
#include <mlir/Conversion/LoopToStandard/ConvertLoopToStandard.h>
#include <mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h>
#include <mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h>
#include <mlir/Dialect/LLVMIR/LLVMDialect.h>
#include <mlir/ExecutionEngine/ExecutionEngine.h>
#include <mlir/ExecutionEngine/OptUtils.h>
#include <mlir/Pass/PassManager.h>
#include <mlir/Target/LLVMIR.h>
#include <mlir/Transforms/DialectConversion.h>
#include <mlir/Transforms/Passes.h>

#include <memory>
#include <mutex>

// Defines a new LLVM debug type for this file to be used by LLVM_DEBUG macro.
#define DEBUG_TYPE "mlir-compiler"

using llvm::SmallVector;
using llvm::StringRef;
using llvm::ArrayRef;

using namespace ngraph;
using namespace ngraph::runtime::ngmlir;

bool MLIRCompiler::initialized = false;

void MLIRCompiler::init()
{
    // Mutex to safely initialize MLIR.
    static std::mutex mlirInitMutex;

    std::unique_lock<std::mutex> lock(mlirInitMutex);

    if (!initialized)
    {
        // TODO: Remove this as it is not part of compiler init
        initializeNGraphMLIR();

        // Register MLIR command line options in the pool of supported flags and and process flags
        // from environment variable to be used by nGraph, MLIR and LLVM.
        mlir::registerPassManagerCLOptions();
        llvm::cl::ParseEnvironmentOptions("ngraph", "NGRAPH_MLIR_OPTIONS", "");

        initialized = true;
    }
}

void MLIRCompiler::compile()
{
    buildNgDialectModule();
}

// Creates an MLIR module and function with nGraph dialect ops from the input CompiledKernel.
void MLIRCompiler::buildNgDialectModule()
{
    // initialize an empty module
    m_module = mlir::ModuleOp::create(mlir::UnknownLoc::get(&m_context));

    mlir::PassManager pm(&m_context);
    pm.addPass(ngraph::pass::createNgDialectConversionPass(m_compiledKernel, &m_context));

    // Apply any generic pass manager command line options.
    mlir::applyPassManagerCLOptions(pm);

    if (failed(pm.run(m_module.get())))
    {
        NGRAPH_CHECK(false, "MLIR pass manager failed");
    }

    if (failed(m_module->verify()))
    {
        NGRAPH_CHECK(false, "Invalid module after lowering to NG dialect");
    }

    dumpMlirModule("nGraph Dialect Construction", m_module.get());

    optimizeNgDialect();
}

void MLIRCompiler::optimizeNgDialect()
{
    mlir::PassManager pm(&m_context);
    pm.addPass(ngraph::pass::createNgDialectFusedOpsPass());

    // Apply any generic pass manager command line options.
    mlir::applyPassManagerCLOptions(pm);

    if (failed(pm.run(m_module.get())))
    {
        NGRAPH_CHECK(false, "MLIR pass manager failed");
    }

    if (failed(m_module->verify()))
    {
        NGRAPH_CHECK(false, "Invalid module after NG dialect optimization");
    }

    dumpMlirModule("nGraph Dialect optimization", m_module.get());
}
<commit_msg>[MLIR] Add a flag to control ngraph dialect fusion pass. (#4362)<commit_after>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************

// NOTE: This file follows nGraph format style.
// Follows nGraph naming convention for public APIs only, else MLIR naming convention.

#include "compiler.hpp"

#include "ngraph_dialect/dialect.hpp"
#include "ngraph_dialect/ops.hpp"
#include "ngraph_dialect/type.hpp"
#include "pass/ng_dialect_builder.hpp"
#include "pass/ng_dialect_fused_ops.hpp"

#include "ngraph/check.hpp"
#include "ngraph/descriptor/tensor.hpp"
#include "ngraph/graph_util.hpp"
#include "ngraph/node.hpp"
#include "ngraph/ops.hpp"
#include "ngraph/type/element_type.hpp"

#include "contrib/mlir/utils.hpp"

#include <llvm/ADT/STLExtras.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/ErrorOr.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Target/TargetMachine.h>
#include <mlir/Conversion/LoopToStandard/ConvertLoopToStandard.h>
#include <mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h>
#include <mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h>
#include <mlir/Dialect/LLVMIR/LLVMDialect.h>
#include <mlir/ExecutionEngine/ExecutionEngine.h>
#include <mlir/ExecutionEngine/OptUtils.h>
#include <mlir/Pass/PassManager.h>
#include <mlir/Target/LLVMIR.h>
#include <mlir/Transforms/DialectConversion.h>
#include <mlir/Transforms/Passes.h>

#include <memory>
#include <mutex>

// Defines a new LLVM debug type for this file to be used by LLVM_DEBUG macro.
#define DEBUG_TYPE "mlir-compiler"

static llvm::cl::opt<bool> clEnableNgKernelLibFusion(
    "ngraph-kernel-lib-fusion",
    llvm::cl::init(false),
    llvm::cl::desc("Enable the ngraph pass that fuses ops to use kernel library"));

using llvm::SmallVector;
using llvm::StringRef;
using llvm::ArrayRef;

using namespace ngraph;
using namespace ngraph::runtime::ngmlir;

bool MLIRCompiler::initialized = false;

void MLIRCompiler::init()
{
    // Mutex to safely initialize MLIR.
    static std::mutex mlirInitMutex;

    std::unique_lock<std::mutex> lock(mlirInitMutex);

    if (!initialized)
    {
        // TODO: Remove this as it is not part of compiler init
        initializeNGraphMLIR();

        // Register MLIR command line options in the pool of supported flags and and process flags
        // from environment variable to be used by nGraph, MLIR and LLVM.
        mlir::registerPassManagerCLOptions();
        llvm::cl::ParseEnvironmentOptions("ngraph", "NGRAPH_MLIR_OPTIONS", "");

        initialized = true;
    }
}

void MLIRCompiler::compile()
{
    buildNgDialectModule();
}

// Creates an MLIR module and function with nGraph dialect ops from the input CompiledKernel.
void MLIRCompiler::buildNgDialectModule()
{
    // initialize an empty module
    m_module = mlir::ModuleOp::create(mlir::UnknownLoc::get(&m_context));

    mlir::PassManager pm(&m_context);
    pm.addPass(ngraph::pass::createNgDialectConversionPass(m_compiledKernel, &m_context));

    // Apply any generic pass manager command line options.
    mlir::applyPassManagerCLOptions(pm);

    if (failed(pm.run(m_module.get())))
    {
        NGRAPH_CHECK(false, "MLIR pass manager failed");
    }

    if (failed(m_module->verify()))
    {
        NGRAPH_CHECK(false, "Invalid module after lowering to NG dialect");
    }

    dumpMlirModule("nGraph Dialect Construction", m_module.get());

    optimizeNgDialect();
}

void MLIRCompiler::optimizeNgDialect()
{
    mlir::PassManager pm(&m_context);
    if (clEnableNgKernelLibFusion)
    {
        pm.addPass(ngraph::pass::createNgDialectFusedOpsPass());
    }

    // Apply any generic pass manager command line options.
    mlir::applyPassManagerCLOptions(pm);

    if (failed(pm.run(m_module.get())))
    {
        NGRAPH_CHECK(false, "MLIR pass manager failed");
    }

    if (failed(m_module->verify()))
    {
        NGRAPH_CHECK(false, "Invalid module after NG dialect optimization");
    }

    dumpMlirModule("nGraph Dialect optimization", m_module.get());
}
<|endoftext|>


<commit_before>#pragma once

#include <agency/detail/config.hpp>
#include <agency/cuda/detail/unique_ptr.hpp>
#include <type_traits>

namespace agency
{
namespace cuda
{
namespace detail
{

struct unit {};

struct unit_ptr : unit
{
  using element_type = unit;

  __host__ __device__
  unit& operator*()
  {
    return *this;
  }

  __host__ __device__
  const unit& operator*() const
  {
    return *this;
  }
};

template<class T>
struct state_requires_storage
  : std::integral_constant<
      bool,
      std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value
   >
{};

struct construct_ready_t {};
struct construct_not_ready_t {};

constexpr static construct_ready_t     construct_ready{};
constexpr static construct_not_ready_t construct_not_ready{};

// XXX this is suffixed with _impl because of nvbug 1700337
//     eliminate the suffix when that bug is resolved
// XXX should try to collapse the implementation of this as much as possible between the two
template<class T,
         bool requires_storage = state_requires_storage<T>::value>
class asynchronous_state_impl
{
  public:
    using value_type = T;
    using pointer = value_type*;

    // constructs an invalid state
    __host__ __device__
    asynchronous_state_impl() = default;

    // constructs an immediately ready state
    template<class... Args,
             class = typename std::enable_if<
               std::is_constructible<T,Args...>::value
             >::type
            >
    __host__ __device__
    asynchronous_state_impl(construct_ready_t, Args&&... ready_args)
      : data_(make_unique<T>(std::forward<Args>(ready_args)...))
    {}

    // constructs a not ready state
    // XXX we should avoid creating an object here
    //     instead, we should just create it uninitialized
    // XXX the destructor should check whether the state requires destruction
    __host__ __device__
    asynchronous_state_impl(construct_not_ready_t)
      : asynchronous_state_impl(construct_ready, T{})
    {}

    __host__ __device__
    asynchronous_state_impl(asynchronous_state_impl&& other) = default;

    __host__ __device__
    asynchronous_state_impl& operator=(asynchronous_state_impl&&) = default;

    __host__ __device__
    pointer data() const
    {
      return data_.get();
    }

    __host__ __device__
    T get()
    {
      T result = std::move(*data_);

      data_.reset();

      return std::move(result);
    }

    __host__ __device__
    bool valid() const
    {
      return data_;
    }

    __host__ __device__
    void swap(asynchronous_state_impl& other)
    {
      data_.swap(other.data_);
    }

  private:
    unique_ptr<T> data_;
};

// when a type is empty, we can create instances on the fly upon dereference
template<class T>
struct empty_type_ptr : T
{
  using element_type = T;

  __host__ __device__
  T& operator*()
  {
    return *this;
  }

  __host__ __device__
  const T& operator*() const
  {
    return *this;
  }
};

template<>
struct empty_type_ptr<void> : unit_ptr {};

// zero storage optimization
template<class T>
class asynchronous_state_impl<T,true>
{
  public:
    using value_type = T;
    using pointer = empty_type_ptr<T>;

    // constructs an invalid state
    __host__ __device__
    asynchronous_state_impl() : valid_(false) {}

    // constructs an immediately ready state
    template<class U,
             class = typename std::enable_if<
               std::is_constructible<T,U>::value
             >::type>
    __host__ __device__
    asynchronous_state_impl(construct_ready_t, U&&) : valid_(true) {}

    __host__ __device__
    asynchronous_state_impl(construct_ready_t) : valid_(true) {}
    {}

    // constructs a not ready state
    __host__ __device__
    asynchronous_state_impl(construct_not_ready_t) : valid_(true) {}

    __host__ __device__
    asynchronous_state_impl(asynchronous_state_impl&& other) : valid_(other.valid_)
    {
      other.valid_ = false;
    }

    // 1. allow moves to void states (this simply discards the state)
    // 2. allow moves to empty types if the type can be constructed from an empty argument list
    template<class U,
             class T1 = T,
             class = typename std::enable_if<
               std::is_void<T1>::value ||
               (std::is_empty<T>::value && std::is_void<U>::value && std::is_constructible<T>::value)
             >::type>
    __host__ __device__
    asynchronous_state_impl(asynchronous_state_impl<U>&& other)
      : valid_(other.valid())
    {
      if(valid())
      {
        // invalidate the old state by calling .get() if it was valid when we received it
        other.get();
      }
    }

    __host__ __device__
    asynchronous_state_impl& operator=(asynchronous_state_impl&& other)
    {
      valid_ = other.valid_;
      other.valid_ = false;

      return *this;
    }

    __host__ __device__
    empty_type_ptr<T> data() const
    {
      return empty_type_ptr<T>();
    }

    __host__ __device__
    T get()
    {
      valid_ = false;

      return get_impl(std::is_void<T>());
    }

    __host__ __device__
    bool valid() const
    {
      return valid_;
    }

    __host__ __device__
    void swap(asynchronous_state_impl& other)
    {
      bool other_valid_old = other.valid_;
      other.valid_ = valid_;
      valid_ = other_valid_old;
    }

  private:
    __host__ __device__
    static T get_impl(std::false_type)
    {
      return T{};
    }

    __host__ __device__
    static T get_impl(std::true_type)
    {
      return;
    }

    bool valid_;
};

// XXX this extra indirection is due to nvbug 1700337
//     eliminate this class when that bug is resolved
template<class T>
class asynchronous_state : public asynchronous_state_impl<T>
{
  public:
    using asynchronous_state_impl<T>::asynchronous_state_impl;
};

} // end detail
} // end cuda
} // end agency

<commit_msg>Allow conversion between related asynchronous_state_impl<commit_after>#pragma once

#include <agency/detail/config.hpp>
#include <agency/cuda/detail/unique_ptr.hpp>
#include <type_traits>

namespace agency
{
namespace cuda
{
namespace detail
{

struct unit {};

struct unit_ptr : unit
{
  using element_type = unit;

  __host__ __device__
  unit& operator*()
  {
    return *this;
  }

  __host__ __device__
  const unit& operator*() const
  {
    return *this;
  }
};

template<class T>
struct state_requires_storage
  : std::integral_constant<
      bool,
      std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value
   >
{};

struct construct_ready_t {};
struct construct_not_ready_t {};

constexpr static construct_ready_t     construct_ready{};
constexpr static construct_not_ready_t construct_not_ready{};

// XXX this is suffixed with _impl because of nvbug 1700337
//     eliminate the suffix when that bug is resolved
// XXX should try to collapse the implementation of this as much as possible between the two
template<class T,
         bool requires_storage = state_requires_storage<T>::value>
class asynchronous_state_impl
{
  public:
    using value_type = T;
    using pointer = value_type*;

    // constructs an invalid state
    __host__ __device__
    asynchronous_state_impl() = default;

    // constructs an immediately ready state
    template<class... Args,
             class = typename std::enable_if<
               std::is_constructible<T,Args...>::value
             >::type
            >
    __host__ __device__
    asynchronous_state_impl(construct_ready_t, Args&&... ready_args)
      : data_(make_unique<T>(std::forward<Args>(ready_args)...))
    {}

    // constructs a not ready state
    // XXX we should avoid creating an object here
    //     instead, we should just create it uninitialized
    // XXX the destructor should check whether the state requires destruction
    __host__ __device__
    asynchronous_state_impl(construct_not_ready_t)
      : asynchronous_state_impl(construct_ready, T{})
    {}

    __host__ __device__
    asynchronous_state_impl(asynchronous_state_impl&& other) = default;

    template<class U,
             class = typename std::enable_if<
               std::is_constructible<unique_ptr<T>, unique_ptr<U>&&>::value
             >::type
            >
    __host__ __device__
    asynchronous_state_impl(asynchronous_state_impl<U>&& other)
      : data_(std::move(other.data_))
    {}

    __host__ __device__
    asynchronous_state_impl& operator=(asynchronous_state_impl&&) = default;

    __host__ __device__
    pointer data() const
    {
      return data_.get();
    }

    __host__ __device__
    T get()
    {
      T result = std::move(*data_);

      data_.reset();

      return std::move(result);
    }

    __host__ __device__
    bool valid() const
    {
      return data_;
    }

    __host__ __device__
    void swap(asynchronous_state_impl& other)
    {
      data_.swap(other.data_);
    }

  private:
    template<class, bool>
    friend class asynchronous_state_impl;

    unique_ptr<T> data_;
};

// when a type is empty, we can create instances on the fly upon dereference
template<class T>
struct empty_type_ptr : T
{
  using element_type = T;

  __host__ __device__
  T& operator*()
  {
    return *this;
  }

  __host__ __device__
  const T& operator*() const
  {
    return *this;
  }
};

template<>
struct empty_type_ptr<void> : unit_ptr {};

// zero storage optimization
template<class T>
class asynchronous_state_impl<T,true>
{
  public:
    using value_type = T;
    using pointer = empty_type_ptr<T>;

    // constructs an invalid state
    __host__ __device__
    asynchronous_state_impl() : valid_(false) {}

    // constructs an immediately ready state
    template<class U,
             class = typename std::enable_if<
               std::is_constructible<T,U>::value
             >::type>
    __host__ __device__
    asynchronous_state_impl(construct_ready_t, U&&) : valid_(true) {}

    __host__ __device__
    asynchronous_state_impl(construct_ready_t) : valid_(true) {}

    // constructs a not ready state
    __host__ __device__
    asynchronous_state_impl(construct_not_ready_t) : valid_(true) {}

    __host__ __device__
    asynchronous_state_impl(asynchronous_state_impl&& other) : valid_(other.valid_)
    {
      other.valid_ = false;
    }

    // 1. allow moves to void states (this simply discards the state)
    // 2. allow moves to empty types if the type can be constructed from an empty argument list
    // 3. allow upcasts to a base T from a derived U
    template<class U,
             class T1 = T,
             class = typename std::enable_if<
               std::is_void<T1>::value ||
               (std::is_empty<T>::value && std::is_void<U>::value && std::is_constructible<T>::value) ||
               std::is_base_of<T,U>::value
             >::type>
    __host__ __device__
    asynchronous_state_impl(asynchronous_state_impl<U>&& other)
      : valid_(other.valid())
    {
      if(valid())
      {
        // invalidate the old state by calling .get() if it was valid when we received it
        other.get();
      }
    }

    __host__ __device__
    asynchronous_state_impl& operator=(asynchronous_state_impl&& other)
    {
      valid_ = other.valid_;
      other.valid_ = false;

      return *this;
    }

    __host__ __device__
    empty_type_ptr<T> data() const
    {
      return empty_type_ptr<T>();
    }

    __host__ __device__
    T get()
    {
      valid_ = false;

      return get_impl(std::is_void<T>());
    }

    __host__ __device__
    bool valid() const
    {
      return valid_;
    }

    __host__ __device__
    void swap(asynchronous_state_impl& other)
    {
      bool other_valid_old = other.valid_;
      other.valid_ = valid_;
      valid_ = other_valid_old;
    }

  private:
    __host__ __device__
    static T get_impl(std::false_type)
    {
      return T{};
    }

    __host__ __device__
    static T get_impl(std::true_type)
    {
      return;
    }

    bool valid_;
};

// XXX this extra indirection is due to nvbug 1700337
//     eliminate this class when that bug is resolved
template<class T>
class asynchronous_state : public asynchronous_state_impl<T>
{
  public:
    using asynchronous_state_impl<T>::asynchronous_state_impl;
};

} // end detail
} // end cuda
} // end agency

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011 - 2017 Stephen F. Booth <me@sbooth.org>
 * See https://github.com/sbooth/SFBAudioEngine/blob/master/LICENSE.txt for license information
 */

#include <AudioToolbox/AudioFormat.h>

#include "MonkeysAudioDecoder.h"
#include "CFErrorUtilities.h"
#include "Logger.h"

#define PLATFORM_APPLE

#include <mac/All.h>
#include <mac/MACLib.h>

#include <mac/IO.h>

namespace {

	void RegisterMonkeysAudioDecoder() __attribute__ ((constructor));
	void RegisterMonkeysAudioDecoder()
	{
		SFB::Audio::Decoder::RegisterSubclass<SFB::Audio::MonkeysAudioDecoder>();
	}

}

#pragma mark IO Interface

// The I/O interface for MAC
class SFB::Audio::MonkeysAudioDecoder::APEIOInterface : public APE::CIO
{
public:
	explicit APEIOInterface(SFB::InputSource& inputSource)
		: mInputSource(inputSource)
	{}

	inline virtual int Open(const wchar_t * pName, bool bOpenReadOnly)
	{
#pragma unused(pName)
#pragma unused(bOpenReadOnly)

		return ERROR_INVALID_INPUT_FILE;
	}

	inline virtual int Close()
	{
		return ERROR_SUCCESS;
	}

	virtual int Read(void * pBuffer, unsigned int nBytesToRead, unsigned int * pBytesRead)
	{
		SInt64 bytesRead = mInputSource.Read(pBuffer, nBytesToRead);
		if(-1 == bytesRead)
			return ERROR_IO_READ;

		*pBytesRead = (unsigned int)bytesRead;

		return ERROR_SUCCESS;
	}

	inline virtual int Write(const void * pBuffer, unsigned int nBytesToWrite, unsigned int * pBytesWritten)
	{
#pragma unused(pBuffer)
#pragma unused(nBytesToWrite)
#pragma unused(pBytesWritten)

		return ERROR_IO_WRITE;
	}

	virtual int Seek(int nDistance, unsigned int nMoveMode)
	{
		if(!mInputSource.SupportsSeeking())
			return ERROR_IO_READ;

		SInt64 offset = nDistance;
		switch(nMoveMode) {
			case SEEK_SET:
				// offset remains unchanged
				break;
			case SEEK_CUR:
				offset += mInputSource.GetOffset();
				break;
			case SEEK_END:
				offset += mInputSource.GetLength();
				break;
		}

		return (!mInputSource.SeekToOffset(offset));
	}

	inline virtual int Create(const wchar_t * pName)
	{
#pragma unused(pName)
		return ERROR_IO_WRITE;
	}

	inline virtual int Delete()
	{
		return ERROR_IO_WRITE;
	}

	inline virtual int SetEOF()
	{
		return ERROR_IO_WRITE;
	}

	inline virtual int GetPosition()
	{
		return (int)mInputSource.GetOffset();
	}

	inline virtual unsigned int GetSize()
	{
		return (unsigned int)mInputSource.GetLength();
	}

	inline virtual int GetName(wchar_t * pBuffer)
	{
#pragma unused(pBuffer)
		return ERROR_SUCCESS;
	}

private:

	SFB::InputSource& mInputSource;
};

#pragma mark Static Methods

CFArrayRef SFB::Audio::MonkeysAudioDecoder::CreateSupportedFileExtensions()
{
	CFStringRef supportedExtensions [] = { CFSTR("ape") };
	return CFArrayCreate(kCFAllocatorDefault, (const void **)supportedExtensions, 1, &kCFTypeArrayCallBacks);
}

CFArrayRef SFB::Audio::MonkeysAudioDecoder::CreateSupportedMIMETypes()
{
	CFStringRef supportedMIMETypes [] = { CFSTR("audio/monkeys-audio"), CFSTR("audio/x-monkeys-audio") };
	return CFArrayCreate(kCFAllocatorDefault, (const void **)supportedMIMETypes, 2, &kCFTypeArrayCallBacks);
}

bool SFB::Audio::MonkeysAudioDecoder::HandlesFilesWithExtension(CFStringRef extension)
{
	if(nullptr == extension)
		return false;

	if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("ape"), kCFCompareCaseInsensitive))
		return true;

	return false;
}

bool SFB::Audio::MonkeysAudioDecoder::HandlesMIMEType(CFStringRef mimeType)
{
	if(nullptr == mimeType)
		return false;

	if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/monkeys-audio"), kCFCompareCaseInsensitive))
		return true;

	if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/x-monkeys-audio"), kCFCompareCaseInsensitive))
		return true;

	return false;
}

SFB::Audio::Decoder::unique_ptr SFB::Audio::MonkeysAudioDecoder::CreateDecoder(InputSource::unique_ptr inputSource)
{
	return unique_ptr(new MonkeysAudioDecoder(std::move(inputSource)));
}

#pragma mark Creation and Destruction

SFB::Audio::MonkeysAudioDecoder::MonkeysAudioDecoder(InputSource::unique_ptr inputSource)
	: Decoder(std::move(inputSource))
{}

#pragma mark Functionality

bool SFB::Audio::MonkeysAudioDecoder::_Open(CFErrorRef *error)
{
	auto ioInterface = 	std::unique_ptr<APEIOInterface>(new APEIOInterface(GetInputSource()));

	auto decompressor = std::unique_ptr<APE::IAPEDecompress>(CreateIAPEDecompressEx(ioInterface.get(), nullptr));
	if(!decompressor) {
		if(error) {
			SFB::CFString description(CFCopyLocalizedString(CFSTR("The file “%@” is not a valid Monkey's Audio file."), ""));
			SFB::CFString failureReason(CFCopyLocalizedString(CFSTR("Not a Monkey's Audio file"), ""));
			SFB::CFString recoverySuggestion(CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::InputOutputError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		return false;
	}

	mDecompressor = std::move(decompressor);
	mIOInterface = std::move(ioInterface);

	// The file format
	mFormat.mFormatID			= kAudioFormatLinearPCM;
	mFormat.mFormatFlags		= kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;

	mFormat.mBitsPerChannel		= (UInt32)mDecompressor->GetInfo(APE::APE_INFO_BITS_PER_SAMPLE);
	mFormat.mSampleRate			= mDecompressor->GetInfo(APE::APE_INFO_SAMPLE_RATE);
	mFormat.mChannelsPerFrame	= (UInt32)mDecompressor->GetInfo(APE::APE_INFO_CHANNELS);

	mFormat.mBytesPerPacket		= (mFormat.mBitsPerChannel / 8) * mFormat.mChannelsPerFrame;
	mFormat.mFramesPerPacket	= 1;
	mFormat.mBytesPerFrame		= mFormat.mBytesPerPacket * mFormat.mFramesPerPacket;

	mFormat.mReserved			= 0;

	// Set up the source format
	mSourceFormat.mFormatID				= 'APE ';

	mSourceFormat.mSampleRate			= mFormat.mSampleRate;
	mSourceFormat.mChannelsPerFrame		= mFormat.mChannelsPerFrame;
	mSourceFormat.mBitsPerChannel		= mFormat.mBitsPerChannel;

	switch(mFormat.mChannelsPerFrame) {
		case 1:		mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Mono);			break;
		case 2:		mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Stereo);		break;
		case 4:		mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Quadraphonic);	break;
	}

	return true;
}

bool SFB::Audio::MonkeysAudioDecoder::_Close(CFErrorRef */*error*/)
{
	mIOInterface.reset();
	mDecompressor.reset();

	return true;
}

SFB::CFString SFB::Audio::MonkeysAudioDecoder::_GetSourceFormatDescription() const
{
	return CFString(nullptr,
					CFSTR("Monkey's Audio, %u channels, %u Hz"),
					mSourceFormat.mChannelsPerFrame,
					(unsigned int)mSourceFormat.mSampleRate);
}

UInt32 SFB::Audio::MonkeysAudioDecoder::_ReadAudio(AudioBufferList *bufferList, UInt32 frameCount)
{
	int blocksRead = 0;
	if(ERROR_SUCCESS != mDecompressor->GetData((char *)bufferList->mBuffers[0].mData, (int)frameCount, &blocksRead)) {
		LOGGER_ERR("org.sbooth.AudioEngine.Decoder.MonkeysAudio", "Monkey's Audio invalid checksum");
		return 0;
	}

	bufferList->mBuffers[0].mDataByteSize = (UInt32)blocksRead * mFormat.mBytesPerFrame;
	bufferList->mBuffers[0].mNumberChannels = mFormat.mChannelsPerFrame;

	return (UInt32)blocksRead;
}

SInt64 SFB::Audio::MonkeysAudioDecoder::_GetTotalFrames() const
{
	return mDecompressor->GetInfo(APE::APE_DECOMPRESS_TOTAL_BLOCKS);
}

SInt64 SFB::Audio::MonkeysAudioDecoder::_GetCurrentFrame() const
{
	return mDecompressor->GetInfo(APE::APE_DECOMPRESS_CURRENT_BLOCK);
}

SInt64 SFB::Audio::MonkeysAudioDecoder::_SeekToFrame(SInt64 frame)
{
	if(ERROR_SUCCESS != mDecompressor->Seek((int)frame)) {
		LOGGER_ERR("org.sbooth.AudioEngine.Decoder.MonkeysAudio", "mDecompressor->Seek() failed");
		return -1;
	}

	return this->GetCurrentFrame();
}
<commit_msg>Updated to MAC_SDK_435<commit_after>/*
 * Copyright (c) 2011 - 2017 Stephen F. Booth <me@sbooth.org>
 * See https://github.com/sbooth/SFBAudioEngine/blob/master/LICENSE.txt for license information
 */

#include <AudioToolbox/AudioFormat.h>

#include "MonkeysAudioDecoder.h"
#include "CFErrorUtilities.h"
#include "Logger.h"

#define PLATFORM_APPLE

#include <mac/All.h>
#include <mac/MACLib.h>

#include <mac/IO.h>

namespace {

	void RegisterMonkeysAudioDecoder() __attribute__ ((constructor));
	void RegisterMonkeysAudioDecoder()
	{
		SFB::Audio::Decoder::RegisterSubclass<SFB::Audio::MonkeysAudioDecoder>();
	}

}

#pragma mark IO Interface

// The I/O interface for MAC
class SFB::Audio::MonkeysAudioDecoder::APEIOInterface : public APE::CIO
{
public:
	explicit APEIOInterface(SFB::InputSource& inputSource)
		: mInputSource(inputSource)
	{}

	inline virtual int Open(const wchar_t * pName, bool bOpenReadOnly)
	{
#pragma unused(pName)
#pragma unused(bOpenReadOnly)

		return ERROR_INVALID_INPUT_FILE;
	}

	inline virtual int Close()
	{
		return ERROR_SUCCESS;
	}

	virtual int Read(void * pBuffer, unsigned int nBytesToRead, unsigned int * pBytesRead)
	{
		SInt64 bytesRead = mInputSource.Read(pBuffer, nBytesToRead);
		if(-1 == bytesRead)
			return ERROR_IO_READ;

		*pBytesRead = (unsigned int)bytesRead;

		return ERROR_SUCCESS;
	}

	inline virtual int Write(const void * pBuffer, unsigned int nBytesToWrite, unsigned int * pBytesWritten)
	{
#pragma unused(pBuffer)
#pragma unused(nBytesToWrite)
#pragma unused(pBytesWritten)

		return ERROR_IO_WRITE;
	}

	virtual int Seek(int64_t nDistance, unsigned int nMoveMode)
	{
		if(!mInputSource.SupportsSeeking())
			return ERROR_IO_READ;

		SInt64 offset = nDistance;
		switch(nMoveMode) {
			case SEEK_SET:
				// offset remains unchanged
				break;
			case SEEK_CUR:
				offset += mInputSource.GetOffset();
				break;
			case SEEK_END:
				offset += mInputSource.GetLength();
				break;
		}

		return (!mInputSource.SeekToOffset(offset));
	}

	inline virtual int Create(const wchar_t * pName)
	{
#pragma unused(pName)
		return ERROR_IO_WRITE;
	}

	inline virtual int Delete()
	{
		return ERROR_IO_WRITE;
	}

	inline virtual int SetEOF()
	{
		return ERROR_IO_WRITE;
	}

	inline virtual int GetPosition()
	{
		return (int)mInputSource.GetOffset();
	}

	inline virtual unsigned int GetSize()
	{
		return (unsigned int)mInputSource.GetLength();
	}

	inline virtual int GetName(wchar_t * pBuffer)
	{
#pragma unused(pBuffer)
		return ERROR_SUCCESS;
	}

private:

	SFB::InputSource& mInputSource;
};

#pragma mark Static Methods

CFArrayRef SFB::Audio::MonkeysAudioDecoder::CreateSupportedFileExtensions()
{
	CFStringRef supportedExtensions [] = { CFSTR("ape") };
	return CFArrayCreate(kCFAllocatorDefault, (const void **)supportedExtensions, 1, &kCFTypeArrayCallBacks);
}

CFArrayRef SFB::Audio::MonkeysAudioDecoder::CreateSupportedMIMETypes()
{
	CFStringRef supportedMIMETypes [] = { CFSTR("audio/monkeys-audio"), CFSTR("audio/x-monkeys-audio") };
	return CFArrayCreate(kCFAllocatorDefault, (const void **)supportedMIMETypes, 2, &kCFTypeArrayCallBacks);
}

bool SFB::Audio::MonkeysAudioDecoder::HandlesFilesWithExtension(CFStringRef extension)
{
	if(nullptr == extension)
		return false;

	if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("ape"), kCFCompareCaseInsensitive))
		return true;

	return false;
}

bool SFB::Audio::MonkeysAudioDecoder::HandlesMIMEType(CFStringRef mimeType)
{
	if(nullptr == mimeType)
		return false;

	if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/monkeys-audio"), kCFCompareCaseInsensitive))
		return true;

	if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/x-monkeys-audio"), kCFCompareCaseInsensitive))
		return true;

	return false;
}

SFB::Audio::Decoder::unique_ptr SFB::Audio::MonkeysAudioDecoder::CreateDecoder(InputSource::unique_ptr inputSource)
{
	return unique_ptr(new MonkeysAudioDecoder(std::move(inputSource)));
}

#pragma mark Creation and Destruction

SFB::Audio::MonkeysAudioDecoder::MonkeysAudioDecoder(InputSource::unique_ptr inputSource)
	: Decoder(std::move(inputSource))
{}

#pragma mark Functionality

bool SFB::Audio::MonkeysAudioDecoder::_Open(CFErrorRef *error)
{
	auto ioInterface = 	std::unique_ptr<APEIOInterface>(new APEIOInterface(GetInputSource()));

	auto decompressor = std::unique_ptr<APE::IAPEDecompress>(CreateIAPEDecompressEx(ioInterface.get(), nullptr));
	if(!decompressor) {
		if(error) {
			SFB::CFString description(CFCopyLocalizedString(CFSTR("The file “%@” is not a valid Monkey's Audio file."), ""));
			SFB::CFString failureReason(CFCopyLocalizedString(CFSTR("Not a Monkey's Audio file"), ""));
			SFB::CFString recoverySuggestion(CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::InputOutputError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		return false;
	}

	mDecompressor = std::move(decompressor);
	mIOInterface = std::move(ioInterface);

	// The file format
	mFormat.mFormatID			= kAudioFormatLinearPCM;
	mFormat.mFormatFlags		= kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;

	mFormat.mBitsPerChannel		= (UInt32)mDecompressor->GetInfo(APE::APE_INFO_BITS_PER_SAMPLE);
	mFormat.mSampleRate			= mDecompressor->GetInfo(APE::APE_INFO_SAMPLE_RATE);
	mFormat.mChannelsPerFrame	= (UInt32)mDecompressor->GetInfo(APE::APE_INFO_CHANNELS);

	mFormat.mBytesPerPacket		= (mFormat.mBitsPerChannel / 8) * mFormat.mChannelsPerFrame;
	mFormat.mFramesPerPacket	= 1;
	mFormat.mBytesPerFrame		= mFormat.mBytesPerPacket * mFormat.mFramesPerPacket;

	mFormat.mReserved			= 0;

	// Set up the source format
	mSourceFormat.mFormatID				= 'APE ';

	mSourceFormat.mSampleRate			= mFormat.mSampleRate;
	mSourceFormat.mChannelsPerFrame		= mFormat.mChannelsPerFrame;
	mSourceFormat.mBitsPerChannel		= mFormat.mBitsPerChannel;

	switch(mFormat.mChannelsPerFrame) {
		case 1:		mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Mono);			break;
		case 2:		mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Stereo);		break;
		case 4:		mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Quadraphonic);	break;
	}

	return true;
}

bool SFB::Audio::MonkeysAudioDecoder::_Close(CFErrorRef */*error*/)
{
	mIOInterface.reset();
	mDecompressor.reset();

	return true;
}

SFB::CFString SFB::Audio::MonkeysAudioDecoder::_GetSourceFormatDescription() const
{
	return CFString(nullptr,
					CFSTR("Monkey's Audio, %u channels, %u Hz"),
					mSourceFormat.mChannelsPerFrame,
					(unsigned int)mSourceFormat.mSampleRate);
}

UInt32 SFB::Audio::MonkeysAudioDecoder::_ReadAudio(AudioBufferList *bufferList, UInt32 frameCount)
{
	int64_t blocksRead = 0;
	if(ERROR_SUCCESS != mDecompressor->GetData((char *)bufferList->mBuffers[0].mData, (int64_t)frameCount, &blocksRead)) {
		LOGGER_ERR("org.sbooth.AudioEngine.Decoder.MonkeysAudio", "Monkey's Audio invalid checksum");
		return 0;
	}

	bufferList->mBuffers[0].mDataByteSize = (UInt32)blocksRead * mFormat.mBytesPerFrame;
	bufferList->mBuffers[0].mNumberChannels = mFormat.mChannelsPerFrame;

	return (UInt32)blocksRead;
}

SInt64 SFB::Audio::MonkeysAudioDecoder::_GetTotalFrames() const
{
	return mDecompressor->GetInfo(APE::APE_DECOMPRESS_TOTAL_BLOCKS);
}

SInt64 SFB::Audio::MonkeysAudioDecoder::_GetCurrentFrame() const
{
	return mDecompressor->GetInfo(APE::APE_DECOMPRESS_CURRENT_BLOCK);
}

SInt64 SFB::Audio::MonkeysAudioDecoder::_SeekToFrame(SInt64 frame)
{
	if(ERROR_SUCCESS != mDecompressor->Seek((int)frame)) {
		LOGGER_ERR("org.sbooth.AudioEngine.Decoder.MonkeysAudio", "mDecompressor->Seek() failed");
		return -1;
	}

	return this->GetCurrentFrame();
}
<|endoftext|>