<commit_before>/*************************************************************************
 *
 *  $RCSfile: accembedded.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: mib $ $Date: 2002-08-15 10:25:09 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _ACCEMBEDDED_HXX
#define _ACCEMBEDDED_HXX

#ifndef _ACCNOTEXTFRAME_HXX
#include "accnotextframe.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif

class SwAccessibleEmbeddedObject : public   SwAccessibleNoTextFrame
{

protected:

    virtual ~SwAccessibleEmbeddedObject();

public:

    SwAccessibleEmbeddedObject( SwAccessibleMap *pMap,
                         const SwFlyFrm *pFlyFrm );

    //=====  XServiceInfo  ====================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName (void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Return whether the specified service is supported by this class.
    */
    virtual sal_Bool SAL_CALL
        supportsService (const ::rtl::OUString& sServiceName)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.  In this case that is just
        the AccessibleContext service.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames (void)
        throw (::com::sun::star::uno::RuntimeException);

    //=====  XTypeProvider  ====================================================
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1424); FILE MERGED 2005/09/05 13:38:12 rt 1.2.1424.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accembedded.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:47:10 $
 *
 *  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 _ACCEMBEDDED_HXX
#define _ACCEMBEDDED_HXX

#ifndef _ACCNOTEXTFRAME_HXX
#include "accnotextframe.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif

class SwAccessibleEmbeddedObject : public   SwAccessibleNoTextFrame
{

protected:

    virtual ~SwAccessibleEmbeddedObject();

public:

    SwAccessibleEmbeddedObject( SwAccessibleMap *pMap,
                         const SwFlyFrm *pFlyFrm );

    //=====  XServiceInfo  ====================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName (void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Return whether the specified service is supported by this class.
    */
    virtual sal_Bool SAL_CALL
        supportsService (const ::rtl::OUString& sServiceName)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.  In this case that is just
        the AccessibleContext service.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames (void)
        throw (::com::sun::star::uno::RuntimeException);

    //=====  XTypeProvider  ====================================================
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: accportions.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:11:44 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _ACCPORTIONS_HXX
#define _ACCPORTIONS_HXX

#include <SwPortionHandler.hxx>
#include <sal/types.h>

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#include <vector>

class String;
class SwTxtNode;
struct SwSpecialPos;
class SwViewOption;
namespace com { namespace sun { namespace star {
    namespace i18n { struct Boundary; }
} } }

/**
 * collect text portion data from the layout through SwPortionHandler interface
 */
class SwAccessiblePortionData : public SwPortionHandler
{
    // the node this portion is referring to
    const SwTxtNode* pTxtNode;

    // variables used while collecting the data
    rtl::OUStringBuffer aBuffer;
    sal_Int32 nModelPosition;
    sal_Bool bFinished;
    const SwViewOption* pViewOptions;

    // the accessible string
    rtl::OUString sAccessibleString;

    // positions array
    // instances of Position_t must always include the minimum and
    // maximum positions as first/last elements (to simplify the
    // algorithms)
    typedef std::vector<sal_Int32> Positions_t;

    Positions_t aLineBreaks;        /// position of line breaks
    Positions_t aModelPositions;    /// position of portion breaks in the model
    Positions_t aAccessiblePositions;   /// portion breaks in sAccessibleString

    typedef std::vector<sal_uInt8> PortionAttrs_t;
    PortionAttrs_t aPortionAttrs;   /// additional portion attributes

    Positions_t* pSentences;    /// positions of sentence breaks

    size_t nBeforePortions;     /// # of portions before first model character
    sal_Bool bLastIsSpecial;    /// set if last portion was 'Special()'

    /// returns the index of the first position whose value is smaller
    /// or equal, and whose following value is equal or larger
    size_t FindBreak( const Positions_t& rPositions, sal_Int32 nValue );

    /// like FindBreak, but finds the last equal or larger position
    size_t FindLastBreak( const Positions_t& rPositions, sal_Int32 nValue );

    /// fill the boundary with the values from rPositions[nPos]
    void FillBoundary(com::sun::star::i18n::Boundary& rBound,
                      const Positions_t& rPositions,
                      size_t nPos );

    /// Access to portion attributes
    sal_Bool IsPortionAttrSet( size_t nPortionNo, sal_uInt8 nAttr );
    inline sal_Bool IsSpecialPortion( size_t nPortionNo );
    inline sal_Bool IsReadOnlyPortion( size_t nPortionNo );
    inline sal_Bool IsGrayPortion( size_t nPortionNo );

    // Helper methods for SwPortionHandler:

    /// Is a portion of this type gray?
    sal_Bool IsGrayPortionType( USHORT nType );

    // helper method for GetEditableRange(...):
    void AdjustAndCheck( sal_Int32 nPos, size_t& nPortionNo,
                         USHORT& nCorePos, sal_Bool& bEdit );

public:
    SwAccessiblePortionData( const SwTxtNode* pTxtNd,
                             const SwViewOption* pViewOpt = NULL );
    virtual ~SwAccessiblePortionData();

    // SwPortionHandler methods
    virtual void Text(USHORT nLength, USHORT nType);
    virtual void Special(USHORT nLength, const String& rText, USHORT nType);
    virtual void LineBreak();
    virtual void Skip(USHORT nLength);
    virtual void Finish();

    // access to the portion data

    /// get the text string, as presented by the layout
    const rtl::OUString& GetAccessibleString();

    /// get the start & end positions of the sentence
    void GetLineBoundary( com::sun::star::i18n::Boundary& rBound,
                          sal_Int32 nPos );

    // get start and end position of the last line
    void GetLastLineBoundary( com::sun::star::i18n::Boundary& rBound );

    /// get the position in the model string for a given
    /// (accessibility) position
    USHORT GetModelPosition( sal_Int32 nPos );

    /// get the position in the accessibility string for a given model position
    sal_Int32 GetAccessiblePosition( USHORT nPos );

    /// fill a SwSpecialPos structure, suitable for calling
    /// SwTxtFrm->GetCharRect
    /// Returns the core position, and fills thr rpPos either with NULL or
    /// with the &rPos, after putting the appropriate data into it.
    USHORT FillSpecialPos( sal_Int32 nPos,
                           SwSpecialPos& rPos,
                           SwSpecialPos*& rpPos );

    // get boundaries of words/sentences. The data structures are
    // created on-demand.
    void GetSentenceBoundary( com::sun::star::i18n::Boundary& rBound,
                              sal_Int32 nPos );

    // get (a) boundary for attribut change
    void GetAttributeBoundary( com::sun::star::i18n::Boundary& rBound,
                               sal_Int32 nPos );

    /// Determine whether this portion should have a gray background
    /// accoridng to the view options
    sal_Bool IsInGrayPortion( sal_Int32 nPos );

    /// Convert start and end positions into core positions.
    /// @returns true if 'special' portions are included either completely
    ///          or not at all. This can be used to test whether editing
    ///          that range would be legal
    sal_Bool GetEditableRange( sal_Int32 nStart, sal_Int32 nEnd,
                               USHORT& nCoreStart, USHORT& nCoreEnd );

    /// Determine whether this core position is valid for these portions.
    /// (A paragraph may be split into several frames, e.g. at page
    ///  boundaries. In this case, only part of a paragraph is represented
    ///  through this object. This method determines whether one particular
    ///  position is valid for this object or not.)
    sal_Bool IsValidCorePosition( USHORT nPos );
    USHORT GetFirstValidCorePosition();
    USHORT GetLastValidCorePosition();
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.14.600); FILE MERGED 2005/09/05 13:38:26 rt 1.14.600.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accportions.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:54:18 $
 *
 *  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 _ACCPORTIONS_HXX
#define _ACCPORTIONS_HXX

#include <SwPortionHandler.hxx>
#include <sal/types.h>

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#include <vector>

class String;
class SwTxtNode;
struct SwSpecialPos;
class SwViewOption;
namespace com { namespace sun { namespace star {
    namespace i18n { struct Boundary; }
} } }

/**
 * collect text portion data from the layout through SwPortionHandler interface
 */
class SwAccessiblePortionData : public SwPortionHandler
{
    // the node this portion is referring to
    const SwTxtNode* pTxtNode;

    // variables used while collecting the data
    rtl::OUStringBuffer aBuffer;
    sal_Int32 nModelPosition;
    sal_Bool bFinished;
    const SwViewOption* pViewOptions;

    // the accessible string
    rtl::OUString sAccessibleString;

    // positions array
    // instances of Position_t must always include the minimum and
    // maximum positions as first/last elements (to simplify the
    // algorithms)
    typedef std::vector<sal_Int32> Positions_t;

    Positions_t aLineBreaks;        /// position of line breaks
    Positions_t aModelPositions;    /// position of portion breaks in the model
    Positions_t aAccessiblePositions;   /// portion breaks in sAccessibleString

    typedef std::vector<sal_uInt8> PortionAttrs_t;
    PortionAttrs_t aPortionAttrs;   /// additional portion attributes

    Positions_t* pSentences;    /// positions of sentence breaks

    size_t nBeforePortions;     /// # of portions before first model character
    sal_Bool bLastIsSpecial;    /// set if last portion was 'Special()'

    /// returns the index of the first position whose value is smaller
    /// or equal, and whose following value is equal or larger
    size_t FindBreak( const Positions_t& rPositions, sal_Int32 nValue );

    /// like FindBreak, but finds the last equal or larger position
    size_t FindLastBreak( const Positions_t& rPositions, sal_Int32 nValue );

    /// fill the boundary with the values from rPositions[nPos]
    void FillBoundary(com::sun::star::i18n::Boundary& rBound,
                      const Positions_t& rPositions,
                      size_t nPos );

    /// Access to portion attributes
    sal_Bool IsPortionAttrSet( size_t nPortionNo, sal_uInt8 nAttr );
    inline sal_Bool IsSpecialPortion( size_t nPortionNo );
    inline sal_Bool IsReadOnlyPortion( size_t nPortionNo );
    inline sal_Bool IsGrayPortion( size_t nPortionNo );

    // Helper methods for SwPortionHandler:

    /// Is a portion of this type gray?
    sal_Bool IsGrayPortionType( USHORT nType );

    // helper method for GetEditableRange(...):
    void AdjustAndCheck( sal_Int32 nPos, size_t& nPortionNo,
                         USHORT& nCorePos, sal_Bool& bEdit );

public:
    SwAccessiblePortionData( const SwTxtNode* pTxtNd,
                             const SwViewOption* pViewOpt = NULL );
    virtual ~SwAccessiblePortionData();

    // SwPortionHandler methods
    virtual void Text(USHORT nLength, USHORT nType);
    virtual void Special(USHORT nLength, const String& rText, USHORT nType);
    virtual void LineBreak();
    virtual void Skip(USHORT nLength);
    virtual void Finish();

    // access to the portion data

    /// get the text string, as presented by the layout
    const rtl::OUString& GetAccessibleString();

    /// get the start & end positions of the sentence
    void GetLineBoundary( com::sun::star::i18n::Boundary& rBound,
                          sal_Int32 nPos );

    // get start and end position of the last line
    void GetLastLineBoundary( com::sun::star::i18n::Boundary& rBound );

    /// get the position in the model string for a given
    /// (accessibility) position
    USHORT GetModelPosition( sal_Int32 nPos );

    /// get the position in the accessibility string for a given model position
    sal_Int32 GetAccessiblePosition( USHORT nPos );

    /// fill a SwSpecialPos structure, suitable for calling
    /// SwTxtFrm->GetCharRect
    /// Returns the core position, and fills thr rpPos either with NULL or
    /// with the &rPos, after putting the appropriate data into it.
    USHORT FillSpecialPos( sal_Int32 nPos,
                           SwSpecialPos& rPos,
                           SwSpecialPos*& rpPos );

    // get boundaries of words/sentences. The data structures are
    // created on-demand.
    void GetSentenceBoundary( com::sun::star::i18n::Boundary& rBound,
                              sal_Int32 nPos );

    // get (a) boundary for attribut change
    void GetAttributeBoundary( com::sun::star::i18n::Boundary& rBound,
                               sal_Int32 nPos );

    /// Determine whether this portion should have a gray background
    /// accoridng to the view options
    sal_Bool IsInGrayPortion( sal_Int32 nPos );

    /// Convert start and end positions into core positions.
    /// @returns true if 'special' portions are included either completely
    ///          or not at all. This can be used to test whether editing
    ///          that range would be legal
    sal_Bool GetEditableRange( sal_Int32 nStart, sal_Int32 nEnd,
                               USHORT& nCoreStart, USHORT& nCoreEnd );

    /// Determine whether this core position is valid for these portions.
    /// (A paragraph may be split into several frames, e.g. at page
    ///  boundaries. In this case, only part of a paragraph is represented
    ///  through this object. This method determines whether one particular
    ///  position is valid for this object or not.)
    sal_Bool IsValidCorePosition( USHORT nPos );
    USHORT GetFirstValidCorePosition();
    USHORT GetLastValidCorePosition();
};

#endif

<|endoftext|>


<commit_before>/*
    BelaCsound.cpp:

    Copyright (C) 2017 V Lazzarini

    This file is part of Csound.

    The Csound Library is free software; you can redistribute it
    and/or modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    Csound 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 Csound; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
    02111-1307 USA
*/
#include <Bela.h>
#include <Midi.h>
#include <csound/csound.hpp>
#include <vector>
#include <sstream>

#define ANCHNS 8

static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
			int nbytes);

struct CsChan {
  std::vector<MYFLT> data;
  std::stringstream name;
};

struct CsData {
  Csound *csound;
  int blocksize;
  int res;
  int count;
  CsChan channel[ANCHNS];
};

static CsData gCsData;
static Midi gMidi;

bool setup(BelaContext *context, void *Data)
{
  Csound *csound;
  const char *csdfile = "my.csd"; /* CSD name */
  const char *midiDev = "-Mhw:1,0,0"; /* MIDI device */
  const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
			 "--realtime", "--daemon", midiDev };
  int numArgs = (int) (sizeof(args)/sizeof(char *));

  if(context->audioInChannels != context->audioOutChannels) {
    printf("Error: number of audio inputs != number of audio outputs.\n");
    return false;
  }

  /* setup Csound */
  csound = new Csound();
  gCsData.csound = csound;
  csound->SetHostImplementedAudioIO(1,0);
  csound->SetHostImplementedMIDIIO(1);
  csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
  csound->SetExternalMidiReadCallback(ReadMidiData);
  csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
  if((gCsData.res = csound->Compile(numArgs, args)) != 0) {
    printf("Error: Csound could not compile CSD file.\n");
    return false;
  }
  gCsData.blocksize = csound->GetKsmps()*csound->GetNchnls();
  gCsData.count = 0;

  /* set up the channels */
  for(int i=0; i < ANCHNS; i++) {
    gCsData.channel[i].data.resize(csound->GetKsmps());
    gCsData.channel[i].name << "analogue" << i+1;
  }

  return true;
}

void render(BelaContext *context, void *Data)
{
  if(gCsData.res == 0) {
    int n,i,k,count, frmcount,blocksize,res;
    Csound *csound = gCsData.csound;
    MYFLT scal = csound->Get0dBFS();
    MYFLT* audioIn = csound->GetSpin();
    MYFLT* audioOut = csound->GetSpout();
    int nchnls = csound->GetNchnls();
    int chns = nchnls < context->audioOutChannels ?
      nchnls : context->audioOutChannels;
    int an_chns = context->analogInChannels > ANCHNS ?
      ANCHNS : context->analogInChannels;
    CsChan *channel = &(gCsData.channel[0]);
    float frm = 0.f, incr = ((float) context->analogFrames)/context->audioFrames;
    count = gCsData.count;
    blocksize = gCsData.blocksize;

    /* processing loop */
    for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
      if(count == blocksize) {
	/* set the channels */
	for(i = 0; i < an_chns; i++) {
          csound->SetChannel(channel[i].name.str().c_str(),
			     &(channel[i].data[0]));
	}
	/* run csound */
	if((res = csound->PerformKsmps()) == 0) count = 0;
	else break;
      }
      /* read/write audio data */
      for(i = 0; i < chns; i++){
	audioIn[count+i] = audioRead(context,n,i);
	audioWrite(context,n,i,audioOut[count+i]/scal);
      }
      /* read analogue data
         analogue frame pos frm gets incremented according to the
         ratio analogFrames/audioFrames.
      */
      frmcount = count/nchnls;
      for(i = 0; i < an_chns; i++) {
	k = (int) frm;
        channel[i].data[frmcount] = analogRead(context,k,i);
      }
    }
    gCsData.res = res;
    gCsData.count = count;
  }
}

void cleanup(BelaContext *context, void *Data)
{
  delete gCsData.csound;
}

/** MIDI Input functions
 */
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
  if(gMidi.readFrom(dev) == 1) {
    gMidi.enableParser(false);
    *userData = (void *) &gMidi;
    return 0;
  }
  csoundMessage(csound, "Could not open Midi device %s", dev);
  delete midi;
  return -1;
}

int CloseMidiInDevice(CSOUND *csound, void *userData) {
}

int ReadMidiData(CSOUND *csound, void *userData,
		 unsigned char *mbuf, int nbytes) {
  int n = 0, byte;
  if(userData) {
  Midi *midi = (Midi *) userData;

  while((byte = midi->getInput()) >= 0) {
    *mbuf++ = (unsigned char) byte;
    if(++n == nbytes) break;
  }
  return n;
  }
  return 0;
}
<commit_msg>static midi object<commit_after>/*
    BelaCsound.cpp:

    Copyright (C) 2017 V Lazzarini

    This file is part of Csound.

    The Csound Library is free software; you can redistribute it
    and/or modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    Csound 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 Csound; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
    02111-1307 USA
*/
#include <Bela.h>
#include <Midi.h>
#include <csound/csound.hpp>
#include <vector>
#include <sstream>

#define ANCHNS 8

static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
			int nbytes);

struct CsChan {
  std::vector<MYFLT> data;
  std::stringstream name;
};

struct CsData {
  Csound *csound;
  int blocksize;
  int res;
  int count;
  CsChan channel[ANCHNS];
};

static CsData gCsData;
static Midi gMidi;

bool setup(BelaContext *context, void *Data)
{
  Csound *csound;
  const char *csdfile = "my.csd"; /* CSD name */
  const char *midiDev = "-Mhw:1,0,0"; /* MIDI device */
  const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
			 "--realtime", "--daemon", midiDev };
  int numArgs = (int) (sizeof(args)/sizeof(char *));

  if(context->audioInChannels != context->audioOutChannels) {
    printf("Error: number of audio inputs != number of audio outputs.\n");
    return false;
  }

  /* setup Csound */
  csound = new Csound();
  gCsData.csound = csound;
  csound->SetHostImplementedAudioIO(1,0);
  csound->SetHostImplementedMIDIIO(1);
  csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
  csound->SetExternalMidiReadCallback(ReadMidiData);
  csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
  if((gCsData.res = csound->Compile(numArgs, args)) != 0) {
    printf("Error: Csound could not compile CSD file.\n");
    return false;
  }
  gCsData.blocksize = csound->GetKsmps()*csound->GetNchnls();
  gCsData.count = 0;

  /* set up the channels */
  for(int i=0; i < ANCHNS; i++) {
    gCsData.channel[i].data.resize(csound->GetKsmps());
    gCsData.channel[i].name << "analogue" << i+1;
  }

  return true;
}

void render(BelaContext *context, void *Data)
{
  if(gCsData.res == 0) {
    int n,i,k,count, frmcount,blocksize,res;
    Csound *csound = gCsData.csound;
    MYFLT scal = csound->Get0dBFS();
    MYFLT* audioIn = csound->GetSpin();
    MYFLT* audioOut = csound->GetSpout();
    int nchnls = csound->GetNchnls();
    int chns = nchnls < context->audioOutChannels ?
      nchnls : context->audioOutChannels;
    int an_chns = context->analogInChannels > ANCHNS ?
      ANCHNS : context->analogInChannels;
    CsChan *channel = &(gCsData.channel[0]);
    float frm = 0.f, incr = ((float) context->analogFrames)/context->audioFrames;
    count = gCsData.count;
    blocksize = gCsData.blocksize;

    /* processing loop */
    for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
      if(count == blocksize) {
	/* set the channels */
	for(i = 0; i < an_chns; i++) {
          csound->SetChannel(channel[i].name.str().c_str(),
			     &(channel[i].data[0]));
	}
	/* run csound */
	if((res = csound->PerformKsmps()) == 0) count = 0;
	else break;
      }
      /* read/write audio data */
      for(i = 0; i < chns; i++){
	audioIn[count+i] = audioRead(context,n,i);
	audioWrite(context,n,i,audioOut[count+i]/scal);
      }
      /* read analogue data
         analogue frame pos frm gets incremented according to the
         ratio analogFrames/audioFrames.
      */
      frmcount = count/nchnls;
      for(i = 0; i < an_chns; i++) {
	k = (int) frm;
        channel[i].data[frmcount] = analogRead(context,k,i);
      }
    }
    gCsData.res = res;
    gCsData.count = count;
  }
}

void cleanup(BelaContext *context, void *Data)
{
  delete gCsData.csound;
}

/** MIDI Input functions
 */
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
  if(gMidi.readFrom(dev) == 1) {
    gMidi.enableParser(false);
    *userData = (void *) &gMidi;
    return 0;
  }
  csoundMessage(csound, "Could not open Midi device %s", dev);
  return -1;
}

int CloseMidiInDevice(CSOUND *csound, void *userData) {
}

int ReadMidiData(CSOUND *csound, void *userData,
		 unsigned char *mbuf, int nbytes) {
  int n = 0, byte;
  if(userData) {
  Midi *midi = (Midi *) userData;

  while((byte = midi->getInput()) >= 0) {
    *mbuf++ = (unsigned char) byte;
    if(++n == nbytes) break;
  }
  return n;
  }
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: imaildsplistener.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-20 13:21:55 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef INCLUDED_IMAILDSPLISTENER_HXX
#define INCLUDED_IMAILDSPLISTENER_HXX

#ifndef _COM_SUN_STAR_MAIL_XMAILMESSAGE_HPP_
#include "com/sun/star/mail/XMailMessage.hpp"
#endif

#ifndef _SALHELPER_REFOBJ_HXX_
#include <salhelper/refobj.hxx>
#endif

class MailDispatcher;

/**
    MailDispatcher listener interface.
    Clients may implement and register instances of the
    mail dispatcher interface in order to get notifications
    about the MailDispatcher status.

    @see MailDispatcher
*/
class IMailDispatcherListener : public ::salhelper::ReferenceObject
{
public:
    /**
        Called when the MailDispatcher is started.
    */
    virtual void started(::rtl::Reference<MailDispatcher> xMailDispatcher) = 0;

    /**
        Called when the MailDispatcher is stopped.
    */
    virtual void stopped(::rtl::Reference<MailDispatcher> xMailDispatcher) = 0;

    /**
        Called when there are no more mail messages
        to deliver.
    */
    virtual void idle(::rtl::Reference<MailDispatcher> xMailDispatcher) = 0;

    /**
        Called for every mail message that has been
        successfully delivered.
    */
    virtual void mailDelivered(::rtl::Reference<MailDispatcher> xMailDispatcher, ::com::sun::star::uno::Reference< ::com::sun::star::mail::XMailMessage> xMailMessage) = 0;

    /**
        Called for every mail message whose delivery
        failed.
    */
    virtual void mailDeliveryError(::rtl::Reference<MailDispatcher> xMailDispatcher, ::com::sun::star::uno::Reference< ::com::sun::star::mail::XMailMessage> xMailMessage, const rtl::OUString& sErrorMessage) = 0;
};

#endif // INCLUDED_IMAILDISPATCHERLISTENER_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.580); FILE MERGED 2005/09/05 13:45:17 rt 1.2.580.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: imaildsplistener.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 09:20:27 $
 *
 *  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 INCLUDED_IMAILDSPLISTENER_HXX
#define INCLUDED_IMAILDSPLISTENER_HXX

#ifndef _COM_SUN_STAR_MAIL_XMAILMESSAGE_HPP_
#include "com/sun/star/mail/XMailMessage.hpp"
#endif

#ifndef _SALHELPER_REFOBJ_HXX_
#include <salhelper/refobj.hxx>
#endif

class MailDispatcher;

/**
    MailDispatcher listener interface.
    Clients may implement and register instances of the
    mail dispatcher interface in order to get notifications
    about the MailDispatcher status.

    @see MailDispatcher
*/
class IMailDispatcherListener : public ::salhelper::ReferenceObject
{
public:
    /**
        Called when the MailDispatcher is started.
    */
    virtual void started(::rtl::Reference<MailDispatcher> xMailDispatcher) = 0;

    /**
        Called when the MailDispatcher is stopped.
    */
    virtual void stopped(::rtl::Reference<MailDispatcher> xMailDispatcher) = 0;

    /**
        Called when there are no more mail messages
        to deliver.
    */
    virtual void idle(::rtl::Reference<MailDispatcher> xMailDispatcher) = 0;

    /**
        Called for every mail message that has been
        successfully delivered.
    */
    virtual void mailDelivered(::rtl::Reference<MailDispatcher> xMailDispatcher, ::com::sun::star::uno::Reference< ::com::sun::star::mail::XMailMessage> xMailMessage) = 0;

    /**
        Called for every mail message whose delivery
        failed.
    */
    virtual void mailDeliveryError(::rtl::Reference<MailDispatcher> xMailDispatcher, ::com::sun::star::uno::Reference< ::com::sun::star::mail::XMailMessage> xMailMessage, const rtl::OUString& sErrorMessage) = 0;
};

#endif // INCLUDED_IMAILDISPATCHERLISTENER_HXX
<|endoftext|>


<commit_before>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/system/SDLApp.hpp"

namespace nom {

SDLApp::SDLApp ( void ) :
  //state_factory { new GameStates() }
  app_state_ ( true ),
  show_fps_ ( true ),
  input_map_ { std::unique_ptr<InputMapping> ( nullptr ) }
{
  NOM_LOG_TRACE( NOM );

  this->app_timer_.start();

  // Mac OS X "bug" fix for keeping our window from getting minimized upon
  // losing focus to an application on another display.
  #if defined( NOM_PLATFORM_OSX )
    if( nom::set_hint( SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0" ) == false )
    {
      NOM_LOG_ERR( NOM, "Could not disable minimizing window on focus loss." );
    }
  #endif
}

SDLApp::~SDLApp ( void )
{
  NOM_LOG_TRACE( NOM );

  this->app_timer_.stop();

  this->quit();

  if ( SDL_WasInit ( SDL_INIT_JOYSTICK ) )
  {
    SDL_QuitSubSystem ( SDL_INIT_JOYSTICK );
  }
}

bool SDLApp::on_init( void )
{
  // User implemented

  return true;
}

void SDLApp::on_event( SDL_Event* ev )
{
  // Active (set) input mappings take priority over traditional events
  // handling -- virtual inheritance.
  // if( this->on_map( event ) == true ) return;

  this->on_map( ev );

  // First, handle our events
  Input::on_input( ev );

  // Next, handle the state's events
  this->states.process_events( ev );
}

void SDLApp::on_update ( float delta )
{
  this->states.update( delta );
}

void SDLApp::on_draw ( IDrawable::RenderTarget& target )
{
  this->states.draw( target );
}

void SDLApp::on_window_close( const Event& ev )
{
  // A call is made here to the virtual method being re-implemented here in
  // order to catch debugging output when the applicable define(s) are compiled
  // in; see also Input.hpp.
  Input::on_window_close( ev );

  this->on_app_quit( ev );
}

void SDLApp::on_app_quit( const Event& ev )
{
  // A call is made here to the virtual method being re-implemented here in
  // order to catch debugging output when the applicable define(s) are compiled
  // in; see also Input.hpp.
  Input::on_app_quit( ev );

  this->quit();
}

bool SDLApp::running( void )
{
  if ( this->app_state_ == true ) return true;

  return false;
}

uint32 SDLApp::ticks ( void )
{
  return this->app_timer_.ticks();
}

void SDLApp::quit( void )
{
  this->app_state_ = false;
}

bool SDLApp::show_fps ( void ) const
{
  return this->show_fps_;
}

void SDLApp::set_show_fps ( bool toggle )
{
  this->show_fps_ = toggle;
}

bool SDLApp::toggle_fps ( void )
{
  if ( this->show_fps() )
  {
    this->set_show_fps ( false );
  }
  else
  {
    this->set_show_fps ( true );
  }

  return this->show_fps_;
}

uint32 SDLApp::previous_state ( void ) const
{
  return this->states.previous_state();
}

void SDLApp::set_state ( uint32 id, void_ptr data )
{
/*
  IState::UniquePtr state = this->state_factory->state( id );

  this->states.set_state( std::move(state), data );
  if ( state != nullptr )
  {
    this->states.set_state( std::move(state), data );
  }
*/
}

void SDLApp::set_state ( IState::UniquePtr state, void_ptr data )
{
  this->states.set_state( std::move(state), data );
}

void SDLApp::push_state ( IState::UniquePtr state, void_ptr data )
{
  this->states.push_state( std::move(state), data );
}

void SDLApp::pop_state ( IState::UniquePtr state, void_ptr data )
{
  this->states.pop_state( std::move(state), data );
}

void SDLApp::pop_state ( void_ptr data )
{
  this->states.pop_state( data );
}

bool SDLApp::add_input_mapping( const std::string& key, const Action& action )
{
  // First, we must initialize our input map if this is the first insertion.
  if( ! this->valid_input_map() )
  {
    this->input_map_ = std::unique_ptr<InputMapping> ( new InputMapping() );
  }

  // Second, if we have an existing input map key, we must remove it, otherwise
  // we segfault when jumping through game states.
  auto itr = this->input_map_->find( key );

  if( itr->second.callback.valid() )
  {
    this->remove_input_mapping( key );
  }

  // Finally, we can insert the new input mapping.
  std::pair<std::string, Action> pair( key, action );
  auto res = this->input_map_->insert( pair );

  if( res.second ) return true;

  return false;
}

bool SDLApp::remove_input_mapping( const std::string& key )
{
  if( this->valid_input_map() )
  {
    InputMapping::iterator itr = this->input_map_->find( key );

    // No match found
    if( itr == this->input_map_->end() )
    {
      return false;
    }
    else // Match found; remove this input mapping
    {
      this->input_map_->erase( itr );

      return true;
    }
  }

  return false;
}

bool SDLApp::valid_input_map( void )
{
  if( this->input_map_.get() != nullptr ) return true;

  return false;
}

bool SDLApp::on_map( const SDL_Event* ev )
{
  if( this->valid_input_map() )
  {
    for( InputMapping::const_iterator itr = this->input_map_->begin(); itr != this->input_map_->end(); ++itr )
    {
      if(
          itr->second.type == ev->type  &&
          itr->second.event == ev->key.keysym.sym
        )
      {
        itr->second.callback();
        return true;
      }
      else if (
                itr->second.type == ev->type &&
                itr->second.event == ev->button.button
              )
      {
        itr->second.callback();
        return true;
      }
      else if (
                itr->second.type == ev->type  &&
                itr->second.event == ev->jbutton.button
              )
      {
        itr->second.callback();
        return true;
      }
    }
  }

  return false;
}

} // namespace nom
<commit_msg>SDLApp: Receive input mapped events last in SDLApp::on_event method<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/system/SDLApp.hpp"

namespace nom {

SDLApp::SDLApp ( void ) :
  //state_factory { new GameStates() }
  app_state_ ( true ),
  show_fps_ ( true ),
  input_map_ { std::unique_ptr<InputMapping> ( nullptr ) }
{
  NOM_LOG_TRACE( NOM );

  this->app_timer_.start();

  // Mac OS X "bug" fix for keeping our window from getting minimized upon
  // losing focus to an application on another display.
  #if defined( NOM_PLATFORM_OSX )
    if( nom::set_hint( SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0" ) == false )
    {
      NOM_LOG_ERR( NOM, "Could not disable minimizing window on focus loss." );
    }
  #endif
}

SDLApp::~SDLApp ( void )
{
  NOM_LOG_TRACE( NOM );

  this->app_timer_.stop();

  this->quit();

  if ( SDL_WasInit ( SDL_INIT_JOYSTICK ) )
  {
    SDL_QuitSubSystem ( SDL_INIT_JOYSTICK );
  }
}

bool SDLApp::on_init( void )
{
  // User implemented

  return true;
}

void SDLApp::on_event( SDL_Event* ev )
{
  // Active (set) input mappings take priority over traditional events
  // handling -- virtual inheritance.
  // if( this->on_map( event ) == true ) return;

  // First, handle our events
  Input::on_input( ev );

  // Next, handle the state's events
  this->states.process_events( ev );

  this->on_map( ev );
}

void SDLApp::on_update ( float delta )
{
  this->states.update( delta );
}

void SDLApp::on_draw ( IDrawable::RenderTarget& target )
{
  this->states.draw( target );
}

void SDLApp::on_window_close( const Event& ev )
{
  // A call is made here to the virtual method being re-implemented here in
  // order to catch debugging output when the applicable define(s) are compiled
  // in; see also Input.hpp.
  Input::on_window_close( ev );

  this->on_app_quit( ev );
}

void SDLApp::on_app_quit( const Event& ev )
{
  // A call is made here to the virtual method being re-implemented here in
  // order to catch debugging output when the applicable define(s) are compiled
  // in; see also Input.hpp.
  Input::on_app_quit( ev );

  this->quit();
}

bool SDLApp::running( void )
{
  if ( this->app_state_ == true ) return true;

  return false;
}

uint32 SDLApp::ticks ( void )
{
  return this->app_timer_.ticks();
}

void SDLApp::quit( void )
{
  this->app_state_ = false;
}

bool SDLApp::show_fps ( void ) const
{
  return this->show_fps_;
}

void SDLApp::set_show_fps ( bool toggle )
{
  this->show_fps_ = toggle;
}

bool SDLApp::toggle_fps ( void )
{
  if ( this->show_fps() )
  {
    this->set_show_fps ( false );
  }
  else
  {
    this->set_show_fps ( true );
  }

  return this->show_fps_;
}

uint32 SDLApp::previous_state ( void ) const
{
  return this->states.previous_state();
}

void SDLApp::set_state ( uint32 id, void_ptr data )
{
/*
  IState::UniquePtr state = this->state_factory->state( id );

  this->states.set_state( std::move(state), data );
  if ( state != nullptr )
  {
    this->states.set_state( std::move(state), data );
  }
*/
}

void SDLApp::set_state ( IState::UniquePtr state, void_ptr data )
{
  this->states.set_state( std::move(state), data );
}

void SDLApp::push_state ( IState::UniquePtr state, void_ptr data )
{
  this->states.push_state( std::move(state), data );
}

void SDLApp::pop_state ( IState::UniquePtr state, void_ptr data )
{
  this->states.pop_state( std::move(state), data );
}

void SDLApp::pop_state ( void_ptr data )
{
  this->states.pop_state( data );
}

bool SDLApp::add_input_mapping( const std::string& key, const Action& action )
{
  // First, we must initialize our input map if this is the first insertion.
  if( ! this->valid_input_map() )
  {
    this->input_map_ = std::unique_ptr<InputMapping> ( new InputMapping() );
  }

  // Second, if we have an existing input map key, we must remove it, otherwise
  // we segfault when jumping through game states.
  auto itr = this->input_map_->find( key );

  if( itr->second.callback.valid() )
  {
    this->remove_input_mapping( key );
  }

  // Finally, we can insert the new input mapping.
  std::pair<std::string, Action> pair( key, action );
  auto res = this->input_map_->insert( pair );

  if( res.second ) return true;

  return false;
}

bool SDLApp::remove_input_mapping( const std::string& key )
{
  if( this->valid_input_map() )
  {
    InputMapping::iterator itr = this->input_map_->find( key );

    // No match found
    if( itr == this->input_map_->end() )
    {
      return false;
    }
    else // Match found; remove this input mapping
    {
      this->input_map_->erase( itr );

      return true;
    }
  }

  return false;
}

bool SDLApp::valid_input_map( void )
{
  if( this->input_map_.get() != nullptr ) return true;

  return false;
}

bool SDLApp::on_map( const SDL_Event* ev )
{
  if( this->valid_input_map() )
  {
    for( InputMapping::const_iterator itr = this->input_map_->begin(); itr != this->input_map_->end(); ++itr )
    {
      if(
          itr->second.type == ev->type  &&
          itr->second.event == ev->key.keysym.sym
        )
      {
        itr->second.callback();
        return true;
      }
      else if (
                itr->second.type == ev->type &&
                itr->second.event == ev->button.button
              )
      {
        itr->second.callback();
        return true;
      }
      else if (
                itr->second.type == ev->type  &&
                itr->second.event == ev->jbutton.button
              )
      {
        itr->second.callback();
        return true;
      }
    }
  }

  return false;
}

} // namespace nom
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 ScyllaDB
 */
/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <algorithm>
#include <random>

#include <boost/range/algorithm/generate.hpp>

namespace tests::random {

namespace internal {

inline std::random_device::result_type get_seed()
{
    std::random_device rd;
    auto seed = rd();
    std::cout << "tests::random seed = " << seed << "\n";
    return seed;
}

}

inline std::default_random_engine gen(internal::get_seed());

template<typename T>
T get_int() {
    std::uniform_int_distribution<T> dist;
    return dist(gen);
}

template<typename T>
T get_int(T max) {
    std::uniform_int_distribution<T> dist(0, max);
    return dist(gen);
}

template<typename T>
T get_int(T min, T max) {
    std::uniform_int_distribution<T> dist(min, max);
    return dist(gen);
}

inline bool get_bool() {
    static std::bernoulli_distribution dist;
    return dist(gen);
}

inline bytes get_bytes(size_t n) {
    bytes b(bytes::initialized_later(), n);
    boost::generate(b, [] { return get_int<bytes::value_type>(); });
    return b;
}

inline bytes get_bytes() {
    return get_bytes(get_int<unsigned>(128 * 1024));
}

inline sstring get_sstring(size_t n) {
    sstring str(sstring::initialized_later(), n);
    boost::generate(str, [] { return get_int<sstring::value_type>('a', 'z'); });
    return str;
}

inline sstring get_sstring() {
    return get_sstring(get_int<unsigned>(1024));
}

}
<commit_msg>tests: Add missing include in random-utils.hh<commit_after>/*
 * Copyright (C) 2018 ScyllaDB
 */
/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <algorithm>
#include <random>

#include <boost/range/algorithm/generate.hpp>
#include <iostream>

namespace tests::random {

namespace internal {

inline std::random_device::result_type get_seed()
{
    std::random_device rd;
    auto seed = rd();
    std::cout << "tests::random seed = " << seed << "\n";
    return seed;
}

}

inline std::default_random_engine gen(internal::get_seed());

template<typename T>
T get_int() {
    std::uniform_int_distribution<T> dist;
    return dist(gen);
}

template<typename T>
T get_int(T max) {
    std::uniform_int_distribution<T> dist(0, max);
    return dist(gen);
}

template<typename T>
T get_int(T min, T max) {
    std::uniform_int_distribution<T> dist(min, max);
    return dist(gen);
}

inline bool get_bool() {
    static std::bernoulli_distribution dist;
    return dist(gen);
}

inline bytes get_bytes(size_t n) {
    bytes b(bytes::initialized_later(), n);
    boost::generate(b, [] { return get_int<bytes::value_type>(); });
    return b;
}

inline bytes get_bytes() {
    return get_bytes(get_int<unsigned>(128 * 1024));
}

inline sstring get_sstring(size_t n) {
    sstring str(sstring::initialized_later(), n);
    boost::generate(str, [] { return get_int<sstring::value_type>('a', 'z'); });
    return str;
}

inline sstring get_sstring() {
    return get_sstring(get_int<unsigned>(1024));
}

}
<|endoftext|>


<commit_before>#include "MP3File.hpp"

using namespace std;

MP3File::MP3File(const string &path)
{
	m_file = new TagLib::MPEG::File(path.c_str());
}

void MP3File::clearCover()
{
	TagLib::ID3v2::Tag *t = dynamic_cast<TagLib::MPEG::File*>(m_file)->ID3v2Tag(true);
	TagLib::ID3v2::FrameList frameList = t->frameList();
	TagLib::List<TagLib::ID3v2::Frame*>::Iterator it;

	for(it = frameList.begin(); it != frameList.end(); ++it)
		if(strcmp((*it)->frameID().data(), "APIC") == 0)
			frameList.erase(it);
}

void MP3File::setCover(const TagLib::String &path)
{
	try
	{
		TagLib::ID3v2::Tag *t = dynamic_cast<TagLib::MPEG::File*>(m_file)->ID3v2Tag(true);

		clearCover();

		if(path != TagLib::String::null)
		{

			Cover c(path.toCString());

			TagLib::ID3v2::AttachedPictureFrame *frame = new TagLib::ID3v2::AttachedPictureFrame;
			frame->setMimeType(c.getMimeType());
			frame->setPicture(c.data());

			t->addFrame(frame);
		}
	}
	catch(string &s)
	{
		cerr << s << endl;
	}
}
<commit_msg>Fixed serious bug when clearing MP3 covers.<commit_after>#include "MP3File.hpp"

using namespace std;

MP3File::MP3File(const string &path)
{
	m_file = new TagLib::MPEG::File(path.c_str());
}

void MP3File::clearCover()
{
	TagLib::ID3v2::Tag *t = dynamic_cast<TagLib::MPEG::File*>(m_file)->ID3v2Tag(true);
	t->removeFrames(TagLib::ByteVector("APIC"));
}

void MP3File::setCover(const TagLib::String &path)
{
	try
	{
		TagLib::ID3v2::Tag *t = dynamic_cast<TagLib::MPEG::File*>(m_file)->ID3v2Tag(true);

		clearCover();

		if(path != TagLib::String::null)
		{

			Cover c(path.toCString());

			TagLib::ID3v2::AttachedPictureFrame *frame = new TagLib::ID3v2::AttachedPictureFrame;
			frame->setMimeType(c.getMimeType());
			frame->setPicture(c.data());

			t->addFrame(frame);
		}
	}
	catch(string &s)
	{
		cerr << s << endl;
	}
}
<|endoftext|>


<commit_before>#include <Matrix.hpp>
#include <catch.hpp>
#include <fstream>

SCENARIO("Matrix init", "[init]") {
	GIVEN("The number of lines and columns") {
		auto lines = 36;
		auto columns = 39;

		WHEN("Create instansce of Matrix") {
			Matrix matrix(lines, columns);
			THEN("The number of lines and columns must be preserved") {
				REQUIRE(matrix.GetNumberOfLines() == lines);
				REQUIRE(matrix.GetNumberOfColumns() == columns);
			}
		}
	}
}

SCENARIO("Matrix InitFromFile", "[fill]") {
	Matrix A(2, 2);
	A.InitFromFile("A2x2.txt");
	REQUIRE( A[0][0] == 1 );
	REQUIRE( A[0][1] == 1 );
	REQUIRE( A[1][0] == 2 );
	REQUIRE( A[1][1] == 2 );
}
SCENARIO("Matrix +", "[addition]") {
	Matrix A(3, 3);
	A.InitFromFile("A3x3.txt");
	Matrix B(3, 3);
	B.InitFromFile("B3x3.txt");
	Matrix expected = Matrix(3, 3);
	expected.InitFromFile("(A3x3)+(B3x3).txt");

	Matrix result = A + B;
	for (int i = 0; i < 3; i++){
		for (int j = 0; j < 3; j++){
			REQUIRE(result[i][j] == expected[i][j]);
		}
	}
}

SCENARIO("Matrix *", "[multiplication]") {
	Matrix A = Matrix(3, 3);
	A.InitFromFile("A3x3.txt");
	Matrix C = Matrix(3, 1);
	C.InitFromFile("C3x1.txt");
	Matrix expected = Matrix(3, 1);
	expected.InitFrom("(A3x3)(C3x1).txt");

	Matrix result = A * B;
	for (int i = 0; i < 3; i++){
		for (int j = 0; j < 3; j++){
			REQUIRE(result[i][j] == expected[i][j]);
		}
	}
}
<commit_msg>Update init.cpp<commit_after>#include <Matrix.hpp>
#include <catch.hpp>
#include <fstream>

SCENARIO("Matrix init", "[init]") {
	GIVEN("The number of lines and columns") {
		auto lines = 36;
		auto columns = 39;

		WHEN("Create instansce of Matrix") {
			Matrix matrix(lines, columns);
			THEN("The number of lines and columns must be preserved") {
				REQUIRE(matrix.GetNumberOfLines() == lines);
				REQUIRE(matrix.GetNumberOfColumns() == columns);
			}
		}
	}
}

SCENARIO("Matrix InitFromFile", "[fill]") {
	Matrix A(2, 2);
	A.InitFromFile("A2x2.txt");
	REQUIRE( A[0][0] == 1 );
	REQUIRE( A[0][1] == 1 );
	REQUIRE( A[1][0] == 2 );
	REQUIRE( A[1][1] == 2 );
}
SCENARIO("Matrix +", "[addition]") {
	Matrix A(3, 3);
	A.InitFromFile("A3x3.txt");
	Matrix B(3, 3);
	B.InitFromFile("B3x3.txt");
	Matrix expected = Matrix(3, 3);
	expected.InitFromFile("(A3x3)+(B3x3).txt");

	Matrix result = A + B;
	for (int i = 0; i < 3; i++){
		for (int j = 0; j < 3; j++){
			REQUIRE(result[i][j] == expected[i][j]);
		}
	}
}
SCENARIO("Matrix *", "[multiplication]") {
	Matrix A = Matrix(3, 3);
	A.InitFromFile("A3x3.txt");
	Matrix C = Matrix(3, 1);
	C.InitFromFile("C3x1.txt");
	Matrix expected = Matrix(3, 1);
	expected.InitFromFile("(A3x3)(C3x1).txt");

	Matrix result = A * B;
	for (int i = 0; i < 3; i++){
		for (int j = 0; j < 3; j++){
			REQUIRE(result[i][j] == expected[i][j]);
		}
	}
}
<|endoftext|>


<commit_before>#include <Stack.h>
#include <catch.hpp>

SCENARIO("Stack count", "[count]"){
	bool mark=false;
	stack<int> st;
	if ((st.count()==0))
	{
		mark=true;
	}
	st.push(1);
	if ((st.count()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack push", "[push]"){
	bool mark=false;
	stack<int> st;
	st.push(1);
	if ((st.count()==1)&&(st.pop()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack pop", "[pop]"){
	bool mark=false;
	stack<int> st;
	st.push(123);
	st.pop();
	if (st.count()==0)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack top", "[top]"){
	bool mark=false;
	stack<int> st;
	st.push(11);
	st.push(22);
	int v=st.top();
	if (v==22)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Assign", "[assign]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_;
	st_=st;
	if ((st_.count()==1)&(st_.pop()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Copy","[copy]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_=st;
	if ((st_.count()==1)&(st_.pop()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}
<commit_msg>Update init.cpp<commit_after>#include <Stack.h>
#include <catch.hpp>

SCENARIO("Stack count", "[count]"){
	bool mark=false;
	stack<int> st;
	if ((st.count()==0))
	{
		mark=true;
	}
	st.push(1);
	if ((st.count()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack push", "[push]"){
	bool mark=false;
	stack<int> st;
	st.push(1);
	if ((st.count()==1)&&(st.top()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack pop", "[pop]"){
	bool mark=false;
	stack<int> st;
	st.push(123);
	st.pop();
	if (st.count()==0)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack top", "[top]"){
	bool mark=false;
	stack<int> st;
	st.push(11);
	st.push(22);
	int v=st.top();
	if (v==22)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Assign", "[assign]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_;
	st_=st;
	if ((st_.count()==1)&(st_.top()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Copy","[copy]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_=st;
	if ((st_.count()==1)&(st_.top()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}
<|endoftext|>


<commit_before>//
//  Blackjack.cpp
//  Cards
//
//  Created by Wesley Howell on 6/27/15.
//  Copyright (c) 2015 Wesley Howell. All rights reserved.
//

// Card Game includes
#include "Blackjack.h"
#include "Chips.h"
#include "Players.h"

// STL Includes
#include <iostream>
#include <algorithm>
#include <ctime>
#include <vector>
using namespace std;

namespace CardGames
{
    Blackjack::Blackjack()
    : m_deck()
    {
    }

    Blackjack::~Blackjack()
    {
        m_deck.clear();
    }

    void
    Blackjack::CreateCardDeck()
    {
        if( m_deck.size() > 0 )
        {
            m_deck.clear();
        }

        // Make a deck for blackjack
        // TODO: This is for 6-deck blackjack. Modify to be configurable up to 6.
        for( unsigned int c = 0; c <= 6; ++c )
        {
            for( unsigned int card = Card::SPADES_ACE; card < Card::JOKER1; ++card )
            {
                m_deck.push_back( static_cast<Card::Cards>( card ) );
            }
        }
    }

    void
    Blackjack::ClearCardDeck()
    {
        m_deck.clear();
    }

    // Random number generator for use in ShuffleCardDeck
    int RNG (int n)
    {
        return std::rand() / (1.0 + RAND_MAX) * n;
    }

    void
    Blackjack::ShuffleCardDeck()
    {
        // Shuffle the deck of cards if it's been populated.
        if( m_deck.size() > 0 )
        {

            srand( unsigned( time(NULL) ) );
            random_shuffle( m_deck.begin(), m_deck.end(), RNG );
            // Burn card
            m_deck.erase( m_deck.begin() );
        }
    }

    unsigned int
    Blackjack::GetCardTotal
        (
        const vector<Card::Cards>& a_hand
        )
    {
        unsigned int faceCardTotal = 0;
        unsigned int numberOfAces = 0;

        for( vector<Card::Cards>::const_iterator card = a_hand.begin(); card < a_hand.end(); ++card )
        {
            switch(*card)
            {
                case Card::SPADES_ACE:
                    ++numberOfAces;
                    break;
                case Card::SPADES_2:
                    faceCardTotal += 2;
                    break;
                case Card::SPADES_3:
                    faceCardTotal += 3;
                    break;
                case Card::SPADES_4:
                    faceCardTotal += 4;
                    break;
                case Card::SPADES_5:
                    faceCardTotal += 5;
                    break;
                case Card::SPADES_6:
                    faceCardTotal += 6;
                    break;
                case Card::SPADES_7:
                    faceCardTotal += 7;
                    break;
                case Card::SPADES_8:
                    faceCardTotal += 8;
                    break;
                case Card::SPADES_9:
                    faceCardTotal += 9;
                    break;
                case Card::SPADES_10:
                    faceCardTotal += 10;
                    break;
                case Card::SPADES_JACK:
                    faceCardTotal += 10;
                    break;
                case Card::SPADES_QUEEN:
                    faceCardTotal += 10;
                    break;
                case Card::SPADES_KING:
                    faceCardTotal += 10;
                    break;
                case Card::HEARTS_ACE:
                    ++numberOfAces;
                    break;
                case Card::HEARTS_2:
                    faceCardTotal += 2;
                    break;
                case Card::HEARTS_3:
                    faceCardTotal += 3;
                    break;
                case Card::HEARTS_4:
                    faceCardTotal += 4;
                    break;
                case Card::HEARTS_5:
                    faceCardTotal += 5;
                    break;
                case Card::HEARTS_6:
                    faceCardTotal += 6;
                    break;
                case Card::HEARTS_7:
                    faceCardTotal += 7;
                    break;
                case Card::HEARTS_8:
                    faceCardTotal += 8;
                    break;
                case Card::HEARTS_9:
                    faceCardTotal += 9;
                    break;
                case Card::HEARTS_10:
                    faceCardTotal += 10;
                    break;
                case Card::HEARTS_JACK:
                    faceCardTotal += 10;
                    break;
                case Card::HEARTS_QUEEN:
                    faceCardTotal += 10;
                    break;
                case Card::HEARTS_KING:
                    faceCardTotal += 10;
                    break;
                case Card::CLUBS_ACE:
                    ++numberOfAces;
                    break;
                case Card::CLUBS_2:
                    faceCardTotal += 2;
                    break;
                case Card::CLUBS_3:
                    faceCardTotal += 3;
                    break;
                case Card::CLUBS_4:
                    faceCardTotal += 4;
                    break;
                case Card::CLUBS_5:
                    faceCardTotal += 5;
                    break;
                case Card::CLUBS_6:
                    faceCardTotal += 6;
                    break;
                case Card::CLUBS_7:
                    faceCardTotal += 7;
                    break;
                case Card::CLUBS_8:
                    faceCardTotal += 8;
                    break;
                case Card::CLUBS_9:
                    faceCardTotal += 9;
                    break;
                case Card::CLUBS_10:
                    faceCardTotal += 10;
                    break;
                case Card::CLUBS_JACK:
                    faceCardTotal += 10;
                    break;
                case Card::CLUBS_QUEEN:
                    faceCardTotal += 10;
                    break;
                case Card::CLUBS_KING:
                    faceCardTotal += 10;
                    break;
                case Card::DIAMONDS_ACE:
                    ++numberOfAces;
                    break;
                case Card::DIAMONDS_2:
                    faceCardTotal += 2;
                    break;
                case Card::DIAMONDS_3:
                    faceCardTotal += 3;
                    break;
                case Card::DIAMONDS_4:
                    faceCardTotal += 4;
                    break;
                case Card::DIAMONDS_5:
                    faceCardTotal += 5;
                    break;
                case Card::DIAMONDS_6:
                    faceCardTotal += 6;
                    break;
                case Card::DIAMONDS_7:
                    faceCardTotal += 7;
                    break;
                case Card::DIAMONDS_8:
                    faceCardTotal += 8;
                    break;
                case Card::DIAMONDS_9:
                    faceCardTotal += 9;
                    break;
                case Card::DIAMONDS_10:
                    faceCardTotal += 10;
                    break;
                case Card::DIAMONDS_JACK:
                    faceCardTotal += 10;
                    break;
                case Card::DIAMONDS_QUEEN:
                    faceCardTotal += 10;
                    break;
                case Card::DIAMONDS_KING:
                    faceCardTotal += 10;
                    break;
                default: break;// Do Nothing
            }
        }

        unsigned int total = 0;
        unsigned int aces11 = numberOfAces + 10;

        // Note, one of the Aces can be 1 or 11.
        // return the highest possible number.
        if( (faceCardTotal + numberOfAces) > 11 )
        {
            total = faceCardTotal + numberOfAces;
        }
        else if( numberOfAces > 0 )
        {
            total = faceCardTotal + aces11;
        }
        else
        {
            total = faceCardTotal;
        }

        return total;
    }

    bool
    Blackjack::DealCards()
    {
        vector<Card::Cards>::iterator start = m_deck.begin();
        vector<Card::Cards>::iterator card = m_deck.begin();
        // Add one card to player's hand
        m_player.addToHand( *card );
        ++card;

        // Add face-up card to dealer's hand
        m_dealer.addToHand( *card );
        ++card;

        // Add final card to player's hand
        m_player.addToHand( *card );
        ++card;

        // Add final card to dealer's hand
        m_dealer.addToHand( *card );

        // Remove cards from hand
        m_deck.erase( start, card );

        // If we are running low on cards, we need to re-shuffle
        // TODO: Make this value configurable based on number of decks
        if( m_deck.size() < 10 )
        {
            return false;
        }
        return true;
    }

    void
    Blackjack::CleanupDealtCards()
    {
        m_player.getHand().clear();
        m_dealer.getHand().clear();
    }

    void
    Blackjack::PlaceBet( const unsigned int a_amount )
    {
        m_player.getChips().Debit( a_amount );
    }

    bool
    Blackjack::MakePlayerMove( Blackjack::Move a_action )
    {
        bool complete = false;
        switch( a_action )
        {
            case STAY:
                complete = true;
                break;
            case HIT:
            {
                vector<Card::Cards>::iterator card = m_deck.begin();
                m_player.addToHand( *card );
                m_deck.erase( card );
                if( GetCardTotal( m_player.getHand() )> 21)
                {
                    // Uh-Oh, the player has busted.
                    complete = true;
                }
            } break;
            case DOUBLE_DOWN:
                break;
            case SPLIT:
                break;
            default:
                // Not a supported operation
                break;
        }
        return complete;
    }

    void
    Blackjack::TurnDealerCards()
    {

    }

    Blackjack::Outcome
    Blackjack::EvaluateWinner()
    {
        Blackjack::Outcome result = Blackjack::OUTCOME_PUSH;
        vector<Card::Cards> player = m_player.getHand();
        vector<Card::Cards> dealer = m_dealer.getHand();

        if( GetCardTotal( player ) > 21 || // Player bust
            GetCardTotal( dealer ) > GetCardTotal( player ) // Dealer hand wins
          )
        {
            // Loss
            result = Blackjack::OUTCOME_LOSS;
        }
        else if ( GetCardTotal( dealer ) == 21 && dealer.size() == 2 ) // Dealer Blackjack
        {
            if( GetCardTotal( player ) > 21 && player.size() == 2 )
            {
                result = Blackjack::OUTCOME_PUSH;
            }
            else
            {
                result = Blackjack::OUTCOME_LOSS;
            }
        }
        else if( GetCardTotal( dealer ) == GetCardTotal( player ) )
        {
            // Push
            result = Blackjack::OUTCOME_PUSH;
        }
        else if( GetCardTotal( dealer ) > 21 )
        {
            // Dealer bust, Winner
            result = Blackjack::OUTCOME_WINNER;
        }
        else
        {
            // Winner
            result = Blackjack::OUTCOME_WINNER;
        }

        return result;
    }

    void Blackjack::PlayBlackjack()
    {
        // Shuffle Cards
        CreateCardDeck();
        ShuffleCardDeck();

        // Give the player some money to start
        Chips& chips = m_player.getChips();
        chips.Credit( 500 );

        bool continueGame = true;
        while( continueGame )
        {
            // Ask a player to place a bet
            cout << "Chip Total: " << chips.GetTotal();
            cout << "Place a bet..." << endl;
            unsigned int input;
            cin >> input;

            // Verify that the player has enough money
            bool enoughMoney = chips.Debit( input );

            if( enoughMoney )
            {
                // Deal the damn cards :)
                bool reshuffle = DealCards();

                // Print the cards
                Card::Cards faceUp = m_dealer.getHand().at( 0 );
                cout << "Dealers Up-Card: " <<  Card::toString( faceUp ) << endl;

                Card::Cards one = m_player.getHand().at( 0 );
                Card::Cards two = m_player.getHand().at( 1 );
                cout << "Your Cards: " << Card::toString( one ) << "  " << Card::toString( two ) << endl;

                // TODO: Verify dealer doesn't have a blackjack

                // Ask player for action
                int moveInput = 0;
                cout << "Make a Move:\n 0: STAY\n 1: HIT\n 2: DOUBLE DOWN\n 3: SPLIT" << endl;
                cin >> moveInput;
                while( !MakePlayerMove( static_cast<Blackjack::Move>(moveInput) ) )
                {
                    // Print the players hand
                    cout << "-----------------------------------" << endl;
                    for( int i = 0; i < m_player.getHand().size(); ++i )
                    {
                        Card::Cards current = m_player.getHand().at( i );
                        cout << Card::toString( current ) << endl;
                    }
                    cout << GetCardTotal( m_player.getHand() ) << endl;
                    cout << "Make a Move:\n 0: STAY\n 1: HIT\n 2: DOUBLE DOWN\n 3: SPLIT" << endl;
                    cin >> moveInput;
                }

                // TODO: Play out the dealers hand...

                // Print the Final players hand
                cout << "------------PLAYER-------------" << endl;
                for( int i = 0; i < m_player.getHand().size(); ++i )
                {
                    Card::Cards current = m_player.getHand().at( i );
                    cout << Card::toString( current ) << endl;
                }
                cout << GetCardTotal( m_player.getHand() ) << endl;

                // Print the dealers hand
                cout << "------------DEALER-------------" << endl;
                for( int i = 0; i < m_dealer.getHand().size(); ++i )
                {
                    Card::Cards current = m_dealer.getHand().at( i );
                    cout << Card::toString( current ) << endl;
                }
                cout << GetCardTotal( m_dealer.getHand() ) << endl;

                Blackjack::Outcome outcome = EvaluateWinner();
                switch( outcome )
                {
                    case OUTCOME_WINNER:
                        chips.Credit( input * 2 );
                        cout << "WINNER!" << endl;
                        break;
                    case OUTCOME_LOSS:
                        cout << "Loss :(" << endl;
                        break;
                    case OUTCOME_PUSH:
                        chips.Credit( input );
                        cout << "PUSH." << endl;
                        break;
                    default:
                        break;
                }

                m_player.getHand().clear();
                m_dealer.getHand().clear();

                if( reshuffle )
                {
                    CreateCardDeck();
                    ShuffleCardDeck();
                }

            }
            else if( chips.GetTotal() == 0 )
            {
                cout << "Wha-Wha-Wha... You are broke. The computer is like the governement and will give you some money :)" << endl;
                chips.Credit( 500 );
                cout << "Chip Total: " << chips.GetTotal() << endl;
            }
            else
            {
                cout << "Not enough money to place a bet" << endl;
            }
        }
    }
}
<commit_msg>Implemented Double Down and Dealer Blackjack logic<commit_after>//
//  Blackjack.cpp
//  Cards
//
//  Created by Wesley Howell on 6/27/15.
//  Copyright (c) 2015 Wesley Howell. All rights reserved.
//

// Card Game includes
#include "Blackjack.h"
#include "Chips.h"
#include "Players.h"

// STL Includes
#include <iostream>
#include <algorithm>
#include <ctime>
#include <vector>
using namespace std;

namespace CardGames
{
    Blackjack::Blackjack()
    : m_deck()
    {
    }

    Blackjack::~Blackjack()
    {
        m_deck.clear();
    }

    void
    Blackjack::CreateCardDeck()
    {
        if( m_deck.size() > 0 )
        {
            m_deck.clear();
        }

        // Make a deck for blackjack
        // TODO: This is for 6-deck blackjack. Modify to be configurable up to 6.
        for( unsigned int c = 0; c <= 6; ++c )
        {
            for( unsigned int card = Card::SPADES_ACE; card < Card::JOKER1; ++card )
            {
                m_deck.push_back( static_cast<Card::Cards>( card ) );
            }
        }
    }

    void
    Blackjack::ClearCardDeck()
    {
        m_deck.clear();
    }

    // Random number generator for use in ShuffleCardDeck
    int RNG (int n)
    {
        return std::rand() / (1.0 + RAND_MAX) * n;
    }

    void
    Blackjack::ShuffleCardDeck()
    {
        // Shuffle the deck of cards if it's been populated.
        if( m_deck.size() > 0 )
        {

            srand( unsigned( time(NULL) ) );
            random_shuffle( m_deck.begin(), m_deck.end(), RNG );
            // Burn card
            m_deck.erase( m_deck.begin() );
        }
    }

    unsigned int
    Blackjack::GetCardTotal
        (
        const vector<Card::Cards>& a_hand
        )
    {
        unsigned int faceCardTotal = 0;
        unsigned int numberOfAces = 0;

        for( vector<Card::Cards>::const_iterator card = a_hand.begin(); card < a_hand.end(); ++card )
        {
            switch(*card)
            {
                case Card::SPADES_ACE:
                    ++numberOfAces;
                    break;
                case Card::SPADES_2:
                    faceCardTotal += 2;
                    break;
                case Card::SPADES_3:
                    faceCardTotal += 3;
                    break;
                case Card::SPADES_4:
                    faceCardTotal += 4;
                    break;
                case Card::SPADES_5:
                    faceCardTotal += 5;
                    break;
                case Card::SPADES_6:
                    faceCardTotal += 6;
                    break;
                case Card::SPADES_7:
                    faceCardTotal += 7;
                    break;
                case Card::SPADES_8:
                    faceCardTotal += 8;
                    break;
                case Card::SPADES_9:
                    faceCardTotal += 9;
                    break;
                case Card::SPADES_10:
                    faceCardTotal += 10;
                    break;
                case Card::SPADES_JACK:
                    faceCardTotal += 10;
                    break;
                case Card::SPADES_QUEEN:
                    faceCardTotal += 10;
                    break;
                case Card::SPADES_KING:
                    faceCardTotal += 10;
                    break;
                case Card::HEARTS_ACE:
                    ++numberOfAces;
                    break;
                case Card::HEARTS_2:
                    faceCardTotal += 2;
                    break;
                case Card::HEARTS_3:
                    faceCardTotal += 3;
                    break;
                case Card::HEARTS_4:
                    faceCardTotal += 4;
                    break;
                case Card::HEARTS_5:
                    faceCardTotal += 5;
                    break;
                case Card::HEARTS_6:
                    faceCardTotal += 6;
                    break;
                case Card::HEARTS_7:
                    faceCardTotal += 7;
                    break;
                case Card::HEARTS_8:
                    faceCardTotal += 8;
                    break;
                case Card::HEARTS_9:
                    faceCardTotal += 9;
                    break;
                case Card::HEARTS_10:
                    faceCardTotal += 10;
                    break;
                case Card::HEARTS_JACK:
                    faceCardTotal += 10;
                    break;
                case Card::HEARTS_QUEEN:
                    faceCardTotal += 10;
                    break;
                case Card::HEARTS_KING:
                    faceCardTotal += 10;
                    break;
                case Card::CLUBS_ACE:
                    ++numberOfAces;
                    break;
                case Card::CLUBS_2:
                    faceCardTotal += 2;
                    break;
                case Card::CLUBS_3:
                    faceCardTotal += 3;
                    break;
                case Card::CLUBS_4:
                    faceCardTotal += 4;
                    break;
                case Card::CLUBS_5:
                    faceCardTotal += 5;
                    break;
                case Card::CLUBS_6:
                    faceCardTotal += 6;
                    break;
                case Card::CLUBS_7:
                    faceCardTotal += 7;
                    break;
                case Card::CLUBS_8:
                    faceCardTotal += 8;
                    break;
                case Card::CLUBS_9:
                    faceCardTotal += 9;
                    break;
                case Card::CLUBS_10:
                    faceCardTotal += 10;
                    break;
                case Card::CLUBS_JACK:
                    faceCardTotal += 10;
                    break;
                case Card::CLUBS_QUEEN:
                    faceCardTotal += 10;
                    break;
                case Card::CLUBS_KING:
                    faceCardTotal += 10;
                    break;
                case Card::DIAMONDS_ACE:
                    ++numberOfAces;
                    break;
                case Card::DIAMONDS_2:
                    faceCardTotal += 2;
                    break;
                case Card::DIAMONDS_3:
                    faceCardTotal += 3;
                    break;
                case Card::DIAMONDS_4:
                    faceCardTotal += 4;
                    break;
                case Card::DIAMONDS_5:
                    faceCardTotal += 5;
                    break;
                case Card::DIAMONDS_6:
                    faceCardTotal += 6;
                    break;
                case Card::DIAMONDS_7:
                    faceCardTotal += 7;
                    break;
                case Card::DIAMONDS_8:
                    faceCardTotal += 8;
                    break;
                case Card::DIAMONDS_9:
                    faceCardTotal += 9;
                    break;
                case Card::DIAMONDS_10:
                    faceCardTotal += 10;
                    break;
                case Card::DIAMONDS_JACK:
                    faceCardTotal += 10;
                    break;
                case Card::DIAMONDS_QUEEN:
                    faceCardTotal += 10;
                    break;
                case Card::DIAMONDS_KING:
                    faceCardTotal += 10;
                    break;
                default: break;// Do Nothing
            }
        }

        unsigned int total = 0;
        unsigned int aces11 = numberOfAces + 10;

        // Note, one of the Aces can be 1 or 11.
        // return the highest possible number.
        if( (faceCardTotal + numberOfAces) > 11 )
        {
            total = faceCardTotal + numberOfAces;
        }
        else if( numberOfAces > 0 )
        {
            total = faceCardTotal + aces11;
        }
        else
        {
            total = faceCardTotal;
        }

        return total;
    }

    bool
    Blackjack::DealCards()
    {
        vector<Card::Cards>::iterator start = m_deck.begin();
        vector<Card::Cards>::iterator card = m_deck.begin();
        // Add one card to player's hand
        m_player.addToHand( *card );
        ++card;

        // Add face-up card to dealer's hand
        m_dealer.addToHand( *card );
        ++card;

        // Add final card to player's hand
        m_player.addToHand( *card );
        ++card;

        // Add final card to dealer's hand
        m_dealer.addToHand( *card );

        // Remove cards from hand
        m_deck.erase( start, card );

        // If we are running low on cards, we need to re-shuffle
        // TODO: Make this value configurable based on number of decks
        if( m_deck.size() < 10 )
        {
            return false;
        }
        return true;
    }

    void
    Blackjack::CleanupDealtCards()
    {
        m_player.getHand().clear();
        m_dealer.getHand().clear();
    }

    void
    Blackjack::PlaceBet( const unsigned int a_amount )
    {
        m_player.getChips().Debit( a_amount );
    }

    bool
    Blackjack::MakePlayerMove( Blackjack::Move a_action )
    {
        bool complete = false;
        switch( a_action )
        {
            case STAY:
                complete = true;
                break;
            case HIT:
            {
                vector<Card::Cards>::iterator card = m_deck.begin();
                m_player.addToHand( *card );
                m_deck.erase( card );
                if( GetCardTotal( m_player.getHand() )> 21)
                {
                    // Uh-Oh, the player has busted.
                    complete = true;
                }
            } break;
            case DOUBLE_DOWN:
            {
                vector<Card::Cards>::iterator card = m_deck.begin();
                m_player.addToHand( *card );
                m_deck.erase( card );
                complete = true;
            }break;
            case SPLIT:
                break;
            default:
                // Not a supported operation
                break;
        }
        return complete;
    }

    void
    Blackjack::TurnDealerCards()
    {
        while( GetCardTotal( m_dealer.getHand() ) < 17 )
        {
            vector<Card::Cards>::iterator card = m_deck.begin();
            m_dealer.addToHand( *card );
            m_deck.erase( card );
        }
    }

    Blackjack::Outcome
    Blackjack::EvaluateWinner()
    {
        Blackjack::Outcome result = Blackjack::OUTCOME_PUSH;
        vector<Card::Cards> player = m_player.getHand();
        vector<Card::Cards> dealer = m_dealer.getHand();

        if( GetCardTotal( player ) > 21 ) // Player bust
        {
            // Loss
            result = Blackjack::OUTCOME_LOSS;
        }
        else if( GetCardTotal( dealer ) == 21 && dealer.size() == 2 ) // Dealer Blackjack
        {
            if( GetCardTotal( player ) > 21 && player.size() == 2 )
            {
                result = Blackjack::OUTCOME_PUSH;
            }
            else
            {
                result = Blackjack::OUTCOME_LOSS;
            }
        }
        else if( GetCardTotal( dealer ) == GetCardTotal( player ) )
        {
            // Push
            result = Blackjack::OUTCOME_PUSH;
        }
        else if( GetCardTotal( dealer ) > 21 )
        {
            // Dealer bust, Winner
            result = Blackjack::OUTCOME_WINNER;
        }
        else if( GetCardTotal( dealer) > GetCardTotal( player ) )
        {
            // Dealer beats player
            result = Blackjack::OUTCOME_LOSS;
        }
        else
        {
            // Winner
            result = Blackjack::OUTCOME_WINNER;
        }

        return result;
    }

    // Driver for a CLI
    void Blackjack::PlayBlackjack()
    {
        // Shuffle Cards
        CreateCardDeck();
        ShuffleCardDeck();

        // Give the player some money to start
        Chips& chips = m_player.getChips();
        chips.Credit( 500 );

        bool continueGame = true;
        while( continueGame )
        {
            // Ask a player to place a bet
            cout << "Chip Total: " << chips.GetTotal();
            cout << "Place a bet..." << endl;
            unsigned int input;
            cin >> input;

            // Verify that the player has enough money
            bool enoughMoney = chips.Debit( input );
            if( enoughMoney )
            {
                // Deal the damn cards :)
                bool reshuffle = DealCards();

                // Print the cards
                Card::Cards faceUp = m_dealer.getHand().at( 0 );
                cout << "Dealers Up-Card: " <<  Card::toString( faceUp ) << endl;

                Card::Cards one = m_player.getHand().at( 0 );
                Card::Cards two = m_player.getHand().at( 1 );
                cout << "Your Cards: " << Card::toString( one ) << "  " << Card::toString( two ) << endl;

                // Play game if dealer doesn't have a blackjack.
                if( GetCardTotal( m_dealer.getHand() ) != 21 )
                {

                    // Ask player for action
                    int moveInput = 0;
                    cout << "Make a Move:\n 0: STAY\n 1: HIT\n 2: DOUBLE DOWN\n 3: SPLIT" << endl;
                    cin >> moveInput;
                    while( !MakePlayerMove( static_cast<Blackjack::Move>(moveInput) ) )
                    {
                        // Print the players hand
                        cout << "-----------------------------------" << endl;
                        for( int i = 0; i < m_player.getHand().size(); ++i )
                        {
                            Card::Cards current = m_player.getHand().at( i );
                            cout << Card::toString( current ) << endl;
                        }
                        cout << GetCardTotal( m_player.getHand() ) << endl;
                        cout << "Make a Move:\n 0: STAY\n 1: HIT\n 2: DOUBLE DOWN\n 3: SPLIT" << endl;
                        cin >> moveInput;
                    }

                    TurnDealerCards();
                }

                // Print the Final players hand
                cout << "------------PLAYER-------------" << endl;
                for( int i = 0; i < m_player.getHand().size(); ++i )
                {
                    Card::Cards current = m_player.getHand().at( i );
                    cout << Card::toString( current ) << endl;
                }
                cout << GetCardTotal( m_player.getHand() ) << endl;

                // Print the dealers hand
                cout << "------------DEALER-------------" << endl;
                for( int i = 0; i < m_dealer.getHand().size(); ++i )
                {
                    Card::Cards current = m_dealer.getHand().at( i );
                    cout << Card::toString( current ) << endl;
                }
                cout << GetCardTotal( m_dealer.getHand() ) << endl;

                Blackjack::Outcome outcome = EvaluateWinner();
                switch( outcome )
                {
                    case OUTCOME_WINNER:
                        chips.Credit( input * 2 );
                        cout << "WINNER!" << endl;
                        break;
                    case OUTCOME_LOSS:
                        cout << "Loss :(" << endl;
                        break;
                    case OUTCOME_PUSH:
                        chips.Credit( input );
                        cout << "PUSH." << endl;
                        break;
                    default:
                        break;
                }

                m_player.getHand().clear();
                m_dealer.getHand().clear();

                if( reshuffle )
                {
                    CreateCardDeck();
                    ShuffleCardDeck();
                }

            }
            else if( chips.GetTotal() == 0 )
            {
                cout << "Wha-Wha-Wha... You are broke. The computer is like the governement and will give you some money :)" << endl;
                chips.Credit( 500 );
                cout << "Chip Total: " << chips.GetTotal() << endl;
            }
            else
            {
                cout << "Not enough money to place a bet" << endl;
            }
        }
    }
}
<|endoftext|>