<commit_before>#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
#include <assert.h>
#include "shared/path_creator.h"
#include "shared/tdmap.hpp"
#include "shared/sizes.h"
#include <map>

using namespace std;

class GUI
{

private:

  void logSDLError(std::ostream &os, const std::string &msg)
  {
    os << msg << " error: " << SDL_GetError() << std::endl;
  }

  std::map<std::string, SDL_Texture *> loaded_textures;
  std::string resPath;

  SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren)
  {
    SDL_Texture *texture;

    if(loaded_textures.find(file) != loaded_textures.end())
    {
      texture = loaded_textures[file];
    }
    else
    {
      texture = IMG_LoadTexture(ren, (resPath + file).c_str());
      if (texture == nullptr)
      {
        logSDLError(std::cout, "LoadTexture");
      }
    }
    return texture;
  }

    /**
  * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving
  * the texture's width and height
  * @param tex The source texture we want to draw
  * @param ren The renderer we want to draw to
  * @param x The x coordinate to draw to
  * @param y The y coordinate to draw to
  */
  void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int rw, int rh)
  {
    //Setup the destination rectangle to be at the position we want
    SDL_Rect dst;
    dst.x = x;
    dst.y = y;
    dst.w = rw;
    dst.h = rh;
    //Query the texture to get its width and height to use
    SDL_RenderCopy(ren, tex, NULL, &dst);
  }

  int row_width;
  int row_height;
  SDL_Renderer * ren;

  void fill_screen_tiles(int numrows, int numcols, Path * path, SDL_Renderer *ren, SDL_Texture *background, SDL_Texture * tile)
  {

    for(int i = 0; i < numrows; i++)
    {
      for(int j = 0; j < numcols; j++)
      {

        coordinate screen_cord = game_to_screen_coord(coordinate(i, j));

        renderTexture(background, ren, screen_cord.first, screen_cord.second, row_width, row_height);

        if(path->in(i, j))
        {
          renderTexture(tile, ren, screen_cord.first, screen_cord.second, row_width, row_height);
        }
      }
    }

  }

  TDMap * map;

  public:
    GUI(int rows, int columns, Path * path, TDMap * map)
    {

        assert(rows > 0 && columns > 0 && path != nullptr && map != nullptr);

        row_width = DEFAULT_WIDTH/rows;
        row_height = DEFAULT_HEIGHT/columns;
        resPath = "/home/utsav/projects/final_project/src/native/graphics/";

        this->map = map;

        SDL_Window *win;

        if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
        {
          logSDLError(std::cout, "SDL_Init");
          exit(1);
        }

        win = SDL_CreateWindow("Tower Defense",
          SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_WIDTH, DEFAULT_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);

        if (win == nullptr)
        {
          logSDLError(std::cout, "CreateWindow");
          SDL_Quit();
          exit(1);

        }
        ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        if (ren == nullptr)
        {
          logSDLError(std::cout, "CreateRenderer");
          //TODO free window
          SDL_Quit();
          exit(1);
        }

        SDL_Texture *background = loadTexture("grass.png", ren);
        SDL_Texture * tile = loadTexture("tile.png", ren);
        SDL_Texture *image = loadTexture("fg.bmp", ren);

        if (background == nullptr || image == nullptr || tile == nullptr)
            {
          logSDLError(std::cout, "Getting Images");
          //TODO cleanup
          SDL_Quit();
          exit(1);
        }

        fill_screen_tiles(rows, columns, path, ren, background, tile);
        SDL_RenderPresent(ren);
    }

    void Update()
    {

      for(int i = 0; i < NUM_ROWS; i++)
      {
        for(int j = 0; j < NUM_COLS; j++)
        {

          Tile& t = map->at(i, j);

          if(t.tower != nullptr)
          {
            SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren);

            if(texture != nullptr)
            {
              coordinate screen_cord = game_to_screen_coord(coordinate(i, j));
              renderTexture(texture, ren, screen_cord.first, screen_cord.second, row_width, row_height);
            }
          }
        }
      }
      SDL_RenderPresent(ren);
      SDL_Delay(10000);
    }

    coordinate game_to_screen_coord(coordinate game_coord)
    {
      return coordinate(game_coord.first * row_width, game_coord.second * row_height);
    }

    coordinate game_to_screen_coord(int x, int y)
    {
      return game_to_screen_coord(coordinate(x, y));
    }
};
<commit_msg>tests?<commit_after>#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
#include <assert.h>
#include "shared/path_creator.h"
#include "shared/tdmap.hpp"
#include "shared/sizes.h"
#include <map>

using namespace std;

class GUI
{

private:

  void logSDLError(std::ostream &os, const std::string &msg)
  {
    os << msg << " error: " << SDL_GetError() << std::endl;
  }

  std::map<std::string, SDL_Texture *> loaded_textures;
  std::string resPath;

  SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren)
  {
    SDL_Texture *texture;

    if(loaded_textures.find(file) != loaded_textures.end())
    {
      texture = loaded_textures[file];
    }
    else
    {
      texture = IMG_LoadTexture(ren, (resPath + file).c_str());
      if (texture == nullptr)
      {
        logSDLError(std::cout, "LoadTexture");
      }
    }
    return texture;
  }

    /**
  * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving
  * the texture's width and height
  * @param tex The source texture we want to draw
  * @param ren The renderer we want to draw to
  * @param x The x coordinate to draw to
  * @param y The y coordinate to draw to
  */
  void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int rw, int rh)
  {
    //Setup the destination rectangle to be at the position we want
    SDL_Rect dst;
    dst.x = x;
    dst.y = y;
    dst.w = rw;
    dst.h = rh;
    //Query the texture to get its width and height to use
    SDL_RenderCopy(ren, tex, NULL, &dst);
  }

  int row_width;
  int row_height;
  SDL_Renderer * ren;

  void fill_screen_tiles(int numrows, int numcols, Path * path, SDL_Renderer *ren, SDL_Texture *background, SDL_Texture * tile)
  {

    for(int i = 0; i < numrows; i++)
    {
      for(int j = 0; j < numcols; j++)
      {

        coordinate screen_cord = game_to_screen_coord(coordinate(i, j));

        renderTexture(background, ren, screen_cord.first, screen_cord.second, row_width, row_height);

        if(path->in(i, j))
        {
          renderTexture(tile, ren, screen_cord.first, screen_cord.second, row_width, row_height);
        }
      }
    }

  }

  TDMap * map;

  public:
    GUI(int rows, int columns, Path * path, TDMap * map)
    {

        assert(rows > 0 && columns > 0 && path != nullptr && map != nullptr);

        row_width = DEFAULT_WIDTH/rows;
        row_height = DEFAULT_HEIGHT/columns;
        resPath = "/home/shiv/Programming/battle-bots/native/graphics/";

        this->map = map;

        SDL_Window *win;

        if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
        {
          logSDLError(std::cout, "SDL_Init");
          exit(1);
        }

        win = SDL_CreateWindow("Tower Defense",
          SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_WIDTH, DEFAULT_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);

        if (win == nullptr)
        {
          logSDLError(std::cout, "CreateWindow");
          SDL_Quit();
          exit(1);

        }
        ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        if (ren == nullptr)
        {
          logSDLError(std::cout, "CreateRenderer");
          //TODO free window
          SDL_Quit();
          exit(1);
        }

        SDL_Texture *background = loadTexture("grass.png", ren);
        SDL_Texture * tile = loadTexture("tile.png", ren);
        SDL_Texture *image = loadTexture("fg.bmp", ren);

        if (background == nullptr || image == nullptr || tile == nullptr)
            {
          logSDLError(std::cout, "Getting Images");
          //TODO cleanup
          SDL_Quit();
          exit(1);
        }

        fill_screen_tiles(rows, columns, path, ren, background, tile);
        SDL_RenderPresent(ren);
    }

    void Update()
    {

      for(int i = 0; i < NUM_ROWS; i++)
      {
        for(int j = 0; j < NUM_COLS; j++)
        {

          Tile& t = map->at(i, j);

          if(t.tower != nullptr)
          {
            SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren);

            if(texture != nullptr)
            {
              coordinate screen_cord = game_to_screen_coord(coordinate(i, j));
              renderTexture(texture, ren, screen_cord.first, screen_cord.second, row_width, row_height);
            }
          }
        }
      }
      SDL_RenderPresent(ren);
      SDL_Delay(10000);
    }

    coordinate game_to_screen_coord(coordinate game_coord)
    {
      return coordinate(game_coord.first * row_width, game_coord.second * row_height);
    }

    coordinate game_to_screen_coord(int x, int y)
    {
      return game_to_screen_coord(coordinate(x, y));
    }
};
<|endoftext|>


<commit_before>// @(#)root/star:$Name:  $:$Id: TObjectSet.cxx,v 1.4 2001/03/24 21:26:00 fine Exp $
// Author: Valery Fine(fine@bnl.gov)   25/12/98
// $Id: TObjectSet.cxx,v 1.4 2001/03/24 21:26:00 fine Exp $
// $Log: TObjectSet.cxx,v $
// Revision 1.4  2001/03/24 21:26:00  fine
// New method TDataSet::Intstance has been introduced
//
// Revision 1.3  2001/03/02 00:45:03  fine
// TTable::SavePrimitive bug fixed
//
// Revision 1.1.1.3  2001/02/07 13:11:28  fisyak
// *** empty log message ***
//
// Revision 1.3  2001/02/07 08:18:15  brun
//
// New version of the STAR classes compiling with no warnings.
//
// Revision 1.1.1.2  2001/01/22 12:59:37  fisyak
// *** empty log message ***
//
// Revision 1.2  2001/01/19 07:22:54  brun
// A few changes in the STAR classes to remove some compiler warnings.
//
// Revision 1.2  2001/01/14 01:27:02  fine
// New implementation TTable::SavePrimitive and AsString
//
// Revision 1.1.1.1  2000/11/27 22:57:14  fisyak
//
//
// Revision 1.1.1.1  2000/05/16 17:00:48  rdm
// Initial import of ROOT into CVS
//
// Revision 1.7  1999/05/07 21:35:32  fine
// Fix some first implemenation bugs
//
// Revision 1.6  1999/05/07 17:53:18  fine
// owner bit has been introduced to deal with the embedded objects
//
#include "TObjectSet.h"
#include "TBrowser.h"

ClassImp(TObjectSet)

//////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//  TObjectSet  - is a container TDataSet                                           //
//                  This means this object has an extra pointer to an embedded      //
//                  TObject.                                                        //
//  Terminology:    This TObjectSet may be an OWNER of the embeded TObject          //
//                  If the container is the owner it can delete the embeded object  //
//                  otherwsie it leaves that object "as is"                         //
//                                                                                //
//////////////////////////////////////////////////////////////////////////////////////

//_____________________________________________________________________________
TObjectSet::TObjectSet(const Char_t *name, TObject *obj, Bool_t makeOwner):TDataSet(name)
{
  SetTitle("TObjectSet");
  SetObject(obj,makeOwner);
}

//_____________________________________________________________________________
TObjectSet::TObjectSet(TObject *obj,Bool_t makeOwner) : TDataSet("unknown","TObjectSet")
{
  SetObject(obj,makeOwner);
}

//_____________________________________________________________________________
TObjectSet::~TObjectSet()
{
// Attn.: virtual  TObject::Delete will be called via virtual dtor of TDataSet
}

//______________________________________________________________________________
TObject *TObjectSet::AddObject(TObject *obj,Bool_t makeOwner)
{
  // Aliase for SetObject method
 return SetObject(obj,makeOwner);
}

//______________________________________________________________________________
void TObjectSet::Browse(TBrowser *b)
{
  // Browse this dataset (called by TBrowser).
   if (b && fObj) b->Add(fObj);
  TDataSet::Browse(b);
}

//_____________________________________________________________________________
void TObjectSet::Delete(Option_t *opt)
{
   if (opt) {/* no used */}
   if (fObj && IsOwner()) delete fObj;
   fObj = 0;
   TDataSet::Delete();
}
//______________________________________________________________________________
Bool_t TObjectSet::DoOwner(Bool_t done)
{
 // Set / Reset the ownerships and returns the previous
 // status of the ownerships.

  Bool_t own = IsOwner();
  if (own != done) {
    if (done) SetBit(kIsOwner);
    else ResetBit(kIsOwner);
  }
  return own;
}
//______________________________________________________________________________
TDataSet *TObjectSet::Instance() const
{
 // apply the class default ctor to instantiate a new object of the same kind.
 // This is a base method to be overriden by the classes
 // derived from TDataSet (to support TDataSetIter::Mkdir for example)
 return instance();
}
//______________________________________________________________________________
TObject *TObjectSet::SetObject(TObject *obj,Bool_t makeOwner)
{
  //
  // - Replace the embedded object with a new supplied
  // - Destroy the preivous embedded object if this is its owner
  // - Return the previous embedded object if any
  //
   TObject *oldObject = fObj;
   if (IsOwner()) { delete oldObject; oldObject = 0;} // the object has been killed
   fObj = obj;
   DoOwner(makeOwner);
   return oldObject;
}
<commit_msg>Fix a memory leak in the TObjectSet destructor<commit_after>// @(#)root/star:$Name:  $:$Id: TObjectSet.cxx,v 1.4 2001/05/14 06:44:09 brun Exp $
// Author: Valery Fine(fine@bnl.gov)   25/12/98
// $Id: TObjectSet.cxx,v 1.4 2001/05/14 06:44:09 brun Exp $
// $Log: TObjectSet.cxx,v $
// Revision 1.4  2001/05/14 06:44:09  brun
// Previous update of STAR classes from Valery was wrong.
//
// Revision 1.4  2001/03/24 21:26:00  fine
// New method TDataSet::Intstance has been introduced
//
// Revision 1.3  2001/03/02 00:45:03  fine
// TTable::SavePrimitive bug fixed
//
// Revision 1.1.1.3  2001/02/07 13:11:28  fisyak
// *** empty log message ***
//
// Revision 1.3  2001/02/07 08:18:15  brun
//
// New version of the STAR classes compiling with no warnings.
//
// Revision 1.1.1.2  2001/01/22 12:59:37  fisyak
// *** empty log message ***
//
// Revision 1.2  2001/01/19 07:22:54  brun
// A few changes in the STAR classes to remove some compiler warnings.
//
// Revision 1.2  2001/01/14 01:27:02  fine
// New implementation TTable::SavePrimitive and AsString
//
// Revision 1.1.1.1  2000/11/27 22:57:14  fisyak
//
//
// Revision 1.1.1.1  2000/05/16 17:00:48  rdm
// Initial import of ROOT into CVS
//
// Revision 1.7  1999/05/07 21:35:32  fine
// Fix some first implemenation bugs
//
// Revision 1.6  1999/05/07 17:53:18  fine
// owner bit has been introduced to deal with the embedded objects
//
#include "TObjectSet.h"
#include "TBrowser.h"

ClassImp(TObjectSet)

//////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//  TObjectSet  - is a container TDataSet                                           //
//                  This means this object has an extra pointer to an embedded      //
//                  TObject.                                                        //
//  Terminology:    This TObjectSet may be an OWNER of the embeded TObject          //
//                  If the container is the owner it can delete the embeded object  //
//                  otherwsie it leaves that object "as is"                         //
//                                                                                //
//////////////////////////////////////////////////////////////////////////////////////

//_____________________________________________________________________________
TObjectSet::TObjectSet(const Char_t *name, TObject *obj, Bool_t makeOwner):TDataSet(name)
{
  SetTitle("TObjectSet");
  SetObject(obj,makeOwner);
}

//_____________________________________________________________________________
TObjectSet::TObjectSet(TObject *obj,Bool_t makeOwner) : TDataSet("unknown","TObjectSet")
{
  SetObject(obj,makeOwner);
}

//_____________________________________________________________________________
TObjectSet::~TObjectSet()
{
  if (fObj && IsOwner()) delete fObj;
  fObj = 0;
}

//______________________________________________________________________________
TObject *TObjectSet::AddObject(TObject *obj,Bool_t makeOwner)
{
  // Aliase for SetObject method
 return SetObject(obj,makeOwner);
}

//______________________________________________________________________________
void TObjectSet::Browse(TBrowser *b)
{
  // Browse this dataset (called by TBrowser).
   if (b && fObj) b->Add(fObj);
  TDataSet::Browse(b);
}

//_____________________________________________________________________________
void TObjectSet::Delete(Option_t *opt)
{
   if (opt) {/* no used */}
   if (fObj && IsOwner()) delete fObj;
   fObj = 0;
   TDataSet::Delete();
}
//______________________________________________________________________________
Bool_t TObjectSet::DoOwner(Bool_t done)
{
 // Set / Reset the ownerships and returns the previous
 // status of the ownerships.

  Bool_t own = IsOwner();
  if (own != done) {
    if (done) SetBit(kIsOwner);
    else ResetBit(kIsOwner);
  }
  return own;
}
//______________________________________________________________________________
TDataSet *TObjectSet::Instance() const
{
 // apply the class default ctor to instantiate a new object of the same kind.
 // This is a base method to be overriden by the classes
 // derived from TDataSet (to support TDataSetIter::Mkdir for example)
 return instance();
}
//______________________________________________________________________________
TObject *TObjectSet::SetObject(TObject *obj,Bool_t makeOwner)
{
  //
  // - Replace the embedded object with a new supplied
  // - Destroy the preivous embedded object if this is its owner
  // - Return the previous embedded object if any
  //
   TObject *oldObject = fObj;
   if (IsOwner()) { delete oldObject; oldObject = 0;} // the object has been killed
   fObj = obj;
   DoOwner(makeOwner);
   return oldObject;
}
<|endoftext|>


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

    state.hpp - support file for writing LV2 plugins in C++

    Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com>

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

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307  USA

****************************************************************************/

#ifndef LV2_STATE_HPP
#define LV2_STATE_HPP

/** TODO: Add map and make path */

#include <lv2/lv2plug.in/ns/ext/state/state.h>

namespace LV2 {

   typedef enum {
         /**
            Plain Old Data.

            Values with this flag contain no pointers or references to other areas
            of memory.  It is safe to copy POD values with a simple memcpy and store
            them for the duration of the process.  A POD value is not necessarily
            safe to trasmit between processes or machines (e.g. filenames are POD),
            see LV2_STATE_IS_PORTABLE for details.

            Implementations MUST NOT attempt to copy or serialise a non-POD value if
            they do not understand its type (and thus know how to correctly do so).
         */

         STATE_IS_POD = LV2_STATE_IS_POD,

         /**
            Portable (architecture independent) data.

            Values with this flag are in a format that is usable on any
            architecture.  A portable value saved on one machine can be restored on
            another machine regardless of architecture.  The format of portable
            values MUST NOT depend on architecture-specific properties like
            endianness or alignment.  Portable values MUST NOT contain filenames.
         */
         STATE_IS_PORTABLE = LV2_STATE_IS_PORTABLE,

         /**
            Native data.

            This flag is used by the host to indicate that the saved data is only
            going to be used locally in the currently running process (e.g. for
            instance duplication or snapshots), so the plugin should use the most
            efficient representation possible and not worry about serialisation
            and portability.
         */
         STATE_IS_NATIVE = LV2_STATE_IS_NATIVE
      } StateFlags;

      typedef enum {
         STATE_SUCCESS         = LV2_STATE_SUCCESS,          /**< Completed successfully. */
         STATE_ERR_UNKNOWN     = LV2_STATE_ERR_UNKNOWN,      /**< Unknown error. */
         STATE_ERR_BAD_TYPE    = LV2_STATE_ERR_BAD_TYPE,     /**< Failed due to unsupported type. */
         STATE_ERR_BAD_FLAGS   = LV2_STATE_ERR_BAD_FLAGS,    /**< Failed due to unsupported flags. */
         STATE_ERR_NO_FEATURE  = LV2_STATE_ERR_NO_FEATURE,   /**< Failed due to missing features. */
         STATE_ERR_NO_PROPERTY = LV2_STATE_ERR_NO_PROPERTY   /**< Failed due to missing property. */
      } StateStatus;
   typedef LV2_State_Retrieve_Function         StateRetrieveFunction;
   typedef LV2_State_Store_Function            StateStoreFunction;
   typedef LV2_State_Handle                    StateHandle;

   /**
       Wrapper struct for state retrieval. This wraps an
       LV2_State_Retrieve_Function and exeucutes via operator ()
    */
   struct StateRetrieve {
      StateRetrieve(StateRetrieveFunction srfunc, StateHandle handle)
      : p_handle(handle), p_srfunc(srfunc) { }

      /**
          Execute the retrieve functor.
          @param key
          @param size
          @param type
          @param flags
          @return Associate 'value' data for the given key
       */
      const void* operator () (uint32_t key, size_t *size  = NULL,
                                           uint32_t *type  = NULL,
                                           uint32_t *flags = NULL)
      {
         return p_srfunc(p_handle, key, size, type, flags);
      }

   private:
      StateHandle              p_handle;
      StateRetrieveFunction    p_srfunc;
   };

   /* A little redundant */

   /**
      Wrapper struct for state storage. This wraps an
      LV2_State_Store_Function and exeucutes via operator ()
   */
   struct StateStore {
      StateStore(StateStoreFunction ssfunc, StateHandle handle)
      : p_handle(handle), p_ssfunc(ssfunc) { }

      /**
          Execute the store functor.
          @param key
          @param value
          @param size
          @param type
          @param flags
          @return STATE_SUCCESS on Success
       */
      StateStatus operator () (uint32_t key, const void* value,
                                             size_t   size,
                                             uint32_t type,
                                             uint32_t flags = 0)
      {
         return (StateStatus) p_ssfunc(
                      p_handle, key, value, size, type, flags
                );
      }

   private:
      StateHandle              p_handle;
      StateStoreFunction       p_ssfunc;
   };

  /**
   * The State Feature.
   * The actual type that your plugin class will inherit when you use
   * this mixin is the internal struct template I.
   * @ingroup pluginmixins
   */
   template <bool Required = true>
   struct State {

     /** This is the type that your plugin class will inherit when you use the
         EventRef mixin. The public and protected members defined here
         will be available in your plugin class.
     */
     template <class Derived> struct I : Extension<Required> {

       /** @internal */
       I() { }

       /** @internal */
       static void map_feature_handlers(FeatureHandlerMap& hmap) {

       }

       /** @internal */
       static void handle_feature(void* instance, void* data) {

       }

       bool check_ok() {
         if (LV2CXX_DEBUG) {
           std::clog<<"    [LV2::State] Validation "
                    <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl;
         }
         return this->m_ok;
       }

       /** @internal */
       static const void* extension_data (const char* uri) {
         if (!std::strcmp (uri, LV2_STATE__interface)) {
           static LV2_State_Interface state = { &I<Derived>::_save,
                                                &I<Derived>::_restore };
           return &state;
         }
         return 0;
       }

       StateStatus save(const StateStore &store, uint32_t flags,
                        const FeatureSet &features)
       {
          return STATE_SUCCESS;
       }

       StateStatus restore(const StateRetrieve &retrieve, uint32_t flags,
                           const FeatureSet &features)
       {
          return STATE_SUCCESS;
       }

     protected:

       /** LV2 Api Implementation */

       /** @internal - called from host */
       static LV2_State_Status _save(LV2_Handle                 instance,
                                     LV2_State_Store_Function   store,
                                     LV2_State_Handle           handle,
                                     uint32_t                   flags,
                                     const LV2_Feature *const * features)
       {
         Derived* plugin = reinterpret_cast<Derived*>(instance);
         StateStore ss (store, handle);
         FeatureSet feature_set;

         for (int i = 0; features[i]; ++i) {
            feature_set.push_back (features[i]);
         }

         return (LV2_State_Status)plugin->save(ss, flags, feature_set);
       }

      /** @internal - called from host */
      static LV2_State_Status _restore(LV2_Handle                  instance,
                                       LV2_State_Retrieve_Function retrieve,
                                       LV2_State_Handle            handle,
                                       uint32_t                    flags,
                                       const LV2_Feature *const *  features)
      {
       Derived* plugin = reinterpret_cast<Derived*>(instance);
       StateRetrieve sr (retrieve, handle);
       FeatureSet feature_set;

       for (int i = 0; features[i]; ++i) {
          feature_set.push_back (features[i]);
       }

       return (LV2_State_Status)plugin->restore(sr, flags, feature_set);
      }
     };
   };

} /* namespace LV2 */

#endif /* LV2_STATE_HPP */
<commit_msg>house keeping<commit_after>/****************************************************************************

    state.hpp - support file for writing LV2 plugins in C++

    Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com>

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

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307  USA

****************************************************************************/

#ifndef LV2_STATE_HPP
#define LV2_STATE_HPP

/** TODO: Add map and make path */

#include <lv2/lv2plug.in/ns/ext/state/state.h>

namespace LV2 {

   typedef enum {
         /**
            Plain Old Data.

            Values with this flag contain no pointers or references to other areas
            of memory.  It is safe to copy POD values with a simple memcpy and store
            them for the duration of the process.  A POD value is not necessarily
            safe to trasmit between processes or machines (e.g. filenames are POD),
            see LV2_STATE_IS_PORTABLE for details.

            Implementations MUST NOT attempt to copy or serialise a non-POD value if
            they do not understand its type (and thus know how to correctly do so).
         */

         STATE_IS_POD = LV2_STATE_IS_POD,

         /**
            Portable (architecture independent) data.

            Values with this flag are in a format that is usable on any
            architecture.  A portable value saved on one machine can be restored on
            another machine regardless of architecture.  The format of portable
            values MUST NOT depend on architecture-specific properties like
            endianness or alignment.  Portable values MUST NOT contain filenames.
         */
         STATE_IS_PORTABLE = LV2_STATE_IS_PORTABLE,

         /**
            Native data.

            This flag is used by the host to indicate that the saved data is only
            going to be used locally in the currently running process (e.g. for
            instance duplication or snapshots), so the plugin should use the most
            efficient representation possible and not worry about serialisation
            and portability.
         */
         STATE_IS_NATIVE = LV2_STATE_IS_NATIVE
      } StateFlags;

      typedef enum {
         STATE_SUCCESS         = LV2_STATE_SUCCESS,          /**< Completed successfully. */
         STATE_ERR_UNKNOWN     = LV2_STATE_ERR_UNKNOWN,      /**< Unknown error. */
         STATE_ERR_BAD_TYPE    = LV2_STATE_ERR_BAD_TYPE,     /**< Failed due to unsupported type. */
         STATE_ERR_BAD_FLAGS   = LV2_STATE_ERR_BAD_FLAGS,    /**< Failed due to unsupported flags. */
         STATE_ERR_NO_FEATURE  = LV2_STATE_ERR_NO_FEATURE,   /**< Failed due to missing features. */
         STATE_ERR_NO_PROPERTY = LV2_STATE_ERR_NO_PROPERTY   /**< Failed due to missing property. */
      } StateStatus;

   typedef LV2_State_Retrieve_Function         StateRetrieveFunction;
   typedef LV2_State_Store_Function            StateStoreFunction;
   typedef LV2_State_Handle                    StateHandle;

   /**
       Wrapper struct for state retrieval. This wraps an
       LV2_State_Retrieve_Function and exeucutes via operator ()
    */
   struct StateRetrieve {
      StateRetrieve(StateRetrieveFunction srfunc, StateHandle handle)
      : p_handle(handle), p_srfunc(srfunc) { }

      /**
          Execute the retrieve functor.
          @param key
          @param size
          @param type
          @param flags
          @return Associate 'value' data for the given key
       */
      const void* operator () (uint32_t key, size_t *size  = NULL,
                                           uint32_t *type  = NULL,
                                           uint32_t *flags = NULL)
      {
         return p_srfunc(p_handle, key, size, type, flags);
      }

   private:
      StateHandle              p_handle;
      StateRetrieveFunction    p_srfunc;
   };

   /* A little redundant */

   /**
      Wrapper struct for state storage. This wraps an
      LV2_State_Store_Function and exeucutes via operator ()
   */
   struct StateStore {
      StateStore(StateStoreFunction ssfunc, StateHandle handle)
      : p_handle(handle), p_ssfunc(ssfunc) { }

      /**
          Execute the store functor.
          @param key
          @param value
          @param size
          @param type
          @param flags
          @return STATE_SUCCESS on Success
       */
      StateStatus operator () (uint32_t key, const void* value,
                                             size_t   size,
                                             uint32_t type,
                                             uint32_t flags = 0)
      {
         return (StateStatus) p_ssfunc(
                      p_handle, key, value, size, type, flags
                );
      }

   private:
      StateHandle              p_handle;
      StateStoreFunction       p_ssfunc;
   };

  /**
   * The State Feature.
   * The actual type that your plugin class will inherit when you use
   * this mixin is the internal struct template I.
   * @ingroup pluginmixins
   */
   template <bool Required = true>
   struct State {

     /** This is the type that your plugin class will inherit when you use the
         EventRef mixin. The public and protected members defined here
         will be available in your plugin class.
     */
     template <class Derived> struct I : Extension<Required> {

       /** @internal */
       I() { }

       /** @internal */
       static void map_feature_handlers(FeatureHandlerMap& hmap) {

       }

       /** @internal */
       static void handle_feature(void* instance, void* data) {

       }

       bool check_ok() {
         if (LV2CXX_DEBUG) {
           std::clog<<"    [LV2::State] Validation "
                    <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl;
         }
         return this->m_ok;
       }

       /** @internal */
       static const void* extension_data (const char* uri) {
         if (!std::strcmp (uri, LV2_STATE__interface)) {
           static LV2_State_Interface state = { &I<Derived>::_save,
                                                &I<Derived>::_restore };
           return &state;
         }
         return 0;
       }

       StateStatus save(const StateStore &store, uint32_t flags,
                        const FeatureSet &features)
       {
          return STATE_SUCCESS;
       }

       StateStatus restore(const StateRetrieve &retrieve, uint32_t flags,
                           const FeatureSet &features)
       {
          return STATE_SUCCESS;
       }

     protected:

       /** LV2 Api Implementation */

       /** @internal - called from host */
       static LV2_State_Status _save(LV2_Handle                 instance,
                                     LV2_State_Store_Function   store,
                                     LV2_State_Handle           handle,
                                     uint32_t                   flags,
                                     const LV2_Feature *const * features)
       {
         Derived* plugin = reinterpret_cast<Derived*>(instance);
         StateStore ss (store, handle);
         FeatureSet feature_set;

         for (int i = 0; features[i]; ++i) {
            feature_set.push_back (features[i]);
         }

         return (LV2_State_Status)plugin->save(ss, flags, feature_set);
       }

      /** @internal - called from host */
      static LV2_State_Status _restore(LV2_Handle                  instance,
                                       LV2_State_Retrieve_Function retrieve,
                                       LV2_State_Handle            handle,
                                       uint32_t                    flags,
                                       const LV2_Feature *const *  features)
      {
       Derived* plugin = reinterpret_cast<Derived*>(instance);
       StateRetrieve sr (retrieve, handle);
       FeatureSet feature_set;

       for (int i = 0; features[i]; ++i) {
          feature_set.push_back (features[i]);
       }

       return (LV2_State_Status)plugin->restore(sr, flags, feature_set);
      }
     };
   };

} /* namespace LV2 */

#endif /* LV2_STATE_HPP */
<|endoftext|>


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

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

#ifdef SOLARIS
#include <sys/time.h>
#endif

#ifdef WNT
#define UNDER_WINDOWS_DEBUGGING
// Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.
#ifdef UNDER_WINDOWS_DEBUGGING
#include <tools/presys.h>
#include <windows.h>
#include <MAPIWin.h>
#include <tools/postsys.h>

#define VCL_NEED_BASETSD

#endif /* UNDER_WINDOWS_DEBUGGING */
#endif /* WNT */

#include <iostream>
#include <vector>
#include <memory> /* auto_ptr */
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

// #include <rtl/tres.h>
#include "autoregisterhelper.hxx"
// #include "cmdlinebits.hxx"
#include "log.hxx"
#include "filehelper.hxx"
#include "getopt.hxx"
#include "cppunit/result/outputter.hxx"
#include "cppunit/joblist.hxx"

// #include <osl/time.h>

using namespace std;

#include "cppunit/result/testshlTestResult.h"
#include "cppunit/result/emacsTestResult.hxx"

// Prototype for signal handling
void setSignalFilename(GetOpt & opt);

void my_sleep(int sec)
{
#ifdef WNT
    Sleep(sec * 1000);
#else
    usleep(sec * 1000000); // 10 ms
#endif
}

// -----------------------------------------------------------------------------
class ProcessHandler
{
    std::string m_sProcessIDFilename;
    void write(int);
    int  getPID();
public:
    ProcessHandler();
    void setName(std::string const& _sFilename);
    ~ProcessHandler();
};

// ------------------------------- ProcessHelper -------------------------------
ProcessHandler::ProcessHandler() {}

void ProcessHandler::setName(std::string const& _sPIDFilename)
{
    m_sProcessIDFilename = _sPIDFilename;
    write(getPID());
}

int ProcessHandler::getPID()
{
    int nPID = 0;
#ifdef WNT
    nPID = GetCurrentProcessId();
#else
    nPID = getpid();
#endif

    return nPID;
}

void ProcessHandler::write(int _nPID)
{
    // get own PID

    if (m_sProcessIDFilename.size() > 0)
    {
        FILE* out;
        out = fopen(m_sProcessIDFilename.c_str(), "w");
        if (!out)
        {
            fprintf(stderr, "warning: (testshl.cxx) can't write own pid.\n");
            return;
            // exit(0);
        }
        fprintf(out, "%d", _nPID);
        fclose(out);
        my_sleep(2); // short wait, so testshl2_timeout can find this pid.
    }
    else
    {
        fprintf(stderr, "warning: (testshl.cxx) PID Filename empty, must set.\n");
    }
}

ProcessHandler::~ProcessHandler()
{
    if (m_sProcessIDFilename.size() > 0)
    {
        write(0);
        my_sleep(2);
        fprintf(stderr, "hint: it is save to remove PID file.\n");
    }
}

// -----------------------------------------------------------------------------
std::auto_ptr<CppUnit::TestResult> initResult(GetOpt & _aOptions)
{
    std::auto_ptr<CppUnit::TestResult> pResult;
    if (_aOptions.hasOpt("-mode"))
    {
        if (_aOptions.getOpt("-mode").equals("emacs") == sal_True)
        {
            pResult = std::auto_ptr<CppUnit::TestResult>(new CppUnit::emacsTestResult(_aOptions));
        }
    }
    else
    {
        pResult = std::auto_ptr<CppUnit::TestResult>(new CppUnit::testshlTestResult(_aOptions));
    }
    return pResult;
}

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

std::auto_ptr<Outputter> initOutputter(GetOpt & _aOptions)
{
    std::auto_ptr<Outputter> pOutputter;

    if (_aOptions.hasOpt("-log"))
    {
        rtl::OString sLogFile = _aOptions.getOpt("-log");

        Log* pLog = new Log( FileHelper::convertPath( sLogFile ) );
        if ( pLog->open() != osl::FileBase::E_None )
        {
            // cerr << "could not open LogFile: " << pLog->getName().getStr() << endl;
            fprintf(stderr, "could not open LogFile: %s\n", pLog->getName().getStr());
            exit(1);
        }
        pOutputter = std::auto_ptr<Outputter>(new Outputter(pLog));
    }
    else
    {
        pOutputter = std::auto_ptr<Outputter>(new Outputter(std::cout));
    }

    return pOutputter;
}

int starttest(GetOpt & opt, AutomaticRegisterHelper const& aHelper);

void endless()
{
    while(1)
    {
        my_sleep(1);
    }
}

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
    static char* optionSet[] = {
        "-boom,         stop near error position, exception only",
        "-mode=s,       the output mode, emacs, xml, old. Default is -mode old",
        "-log=s,        destination file for logging",
        "-noerrors,     shows all tests, but not it's errors.",
        "-onlyerrors,   shows only the failed test functions",
/*      "-tc=s@,        name(s) of testcase(s) to generate", */
        "-sf=s,         absolute path and name to the signal file.",
//! new (helpful if at debug time)
        "-dntsf,        if given, do not touch signal file, also if one exist.",
        "-dnrmsf,       do not remove signalfile. ",
        "-jobonly=s,    job control file, these jobs should only executed.",
        "-jobfilter=s,  use a filter for just some tests.",
        "-onlyshowjobs, show only all jobs, do no tests.",
        "-forward=s,    this string will forwarded to the test libraries.",
        "-projectid=s,  this text is added to the date output line.",
        "-buildid=s,    this text is added to the date output line.",
        "-waitforkey,   wait until key pressed.",
        "-verbose,      be verbose.",
        "-pid=s,        write current process id to file",
        "-endless,      testshl runs endless, for test only!!!",
        "-whereami,     shows at runtime, which function is tested next.",
        "-noerroronexit, if this is given the program exits with return code 0 even if runtime errors occurs.",
        "-h:s,          display help or help on option",
        "-help:s,       see -h",
        NULL
    };

    ProcessHandler aCurrentProcess;

    GetOpt opt( argv, optionSet );
    if ( opt.hasOpt("-pid") )
    {
        aCurrentProcess.setName(opt.getOpt("-pid").getStr());
    }

    if ( opt.hasOpt("-verbose") )
    {
        fprintf(stderr, "testshl2 $Revision: 1.13 $\n");
    }

    if ( opt.hasOpt("-endless"))                 // this exists only for self test issues
    {
        endless();
    }

    int  nExitCode = 0;
    bool bLibrary = true;

    // someone indicates that he needs help
    if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) )
    {
        opt.showUsage();
        nExitCode = 0;
    }
    else
    {
        if (opt.getParams().empty())
        {
            // no library is given, but if a jobonly list is given, we should generate UNKNOWN errors.
            if (! opt.hasOpt("-jobonly"))
            {
                // std::cerr << "error: At least a library or a job file should given." << std::endl;
                fprintf(stderr, "error: At least a library or a job file should given.\n");
                opt.showUsage();
                nExitCode = 2;
            }
            else
            {
                bLibrary = false;
            }
        }
        else
        {
            setSignalFilename(opt);

//#ifdef UNDER_WINDOWS_DEBUGGING
//    DebugBreak();
//#endif
            rtl::OUString suLibraryName;
            if (bLibrary)
            {
                suLibraryName = rtl::OStringToOUString(opt.getFirstParam(), osl_getThreadTextEncoding() /* RTL_TEXTENCODING_ASCII_US */ );
            }

            AutomaticRegisterHelper aHelper(suLibraryName, opt /*, &aJobs*/);

            // start the tests
            nExitCode = starttest(opt, aHelper);
        }
    }

    if (opt.hasOpt("-noerroronexit"))
    {
        nExitCode = 0;
    }
    return nExitCode;
}

// -----------------------------------------------------------------------------
// this function is only inserted to give a better startpoint for breakpoints

int starttest(GetOpt & opt, AutomaticRegisterHelper const& aHelper)
{
    // create a TestResult
    std::auto_ptr<CppUnit::TestResult> pResult = initResult(opt);

    // call all test functions
    aHelper.CallAll(pResult.get());

    // create and open log
    std::auto_ptr<Outputter> pOutput = initOutputter(opt);

    // give the output
    pResult->print(*pOutput.get());

    // this is a debug extension, so you can read the output and after a key is pressed the program will end.
    if (opt.hasOpt("-waitforkey"))
    {
        fprintf(stderr, "Press return key.");
        fflush(stderr);
        getchar();
    }
    int nExit = pResult->getExitValue();
    return nExit;
}

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

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

#ifdef SOLARIS
#include <sys/time.h>
#endif

#ifdef WNT
#define UNDER_WINDOWS_DEBUGGING
// Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.
#ifdef UNDER_WINDOWS_DEBUGGING
#include <tools/presys.h>
#include <windows.h>
#include <MAPIWin.h>
#include <tools/postsys.h>

#define VCL_NEED_BASETSD

#endif /* UNDER_WINDOWS_DEBUGGING */
#endif /* WNT */

#include <iostream>
#include <vector>
#include <memory> /* auto_ptr */
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

// #include <rtl/tres.h>
#include "autoregisterhelper.hxx"
// #include "cmdlinebits.hxx"
#include "log.hxx"
#include "filehelper.hxx"
#include "getopt.hxx"
#include "cppunit/result/outputter.hxx"
#include "cppunit/joblist.hxx"

// #include <osl/time.h>

using namespace std;

#include "cppunit/result/testshlTestResult.h"
#include "cppunit/result/emacsTestResult.hxx"

// Prototype for signal handling
void setSignalFilename(GetOpt & opt);

void my_sleep(int sec)
{
#ifdef WNT
    Sleep(sec * 1000);
#else
    usleep(sec * 1000000); // 10 ms
#endif
}

// -----------------------------------------------------------------------------
class ProcessHandler
{
    std::string m_sProcessIDFilename;
    void write(int);
    int  getPID();
public:
    ProcessHandler();
    void setName(std::string const& _sFilename);
    ~ProcessHandler();
};

// ------------------------------- ProcessHelper -------------------------------
ProcessHandler::ProcessHandler() {}

void ProcessHandler::setName(std::string const& _sPIDFilename)
{
    m_sProcessIDFilename = _sPIDFilename;
    write(getPID());
}

int ProcessHandler::getPID()
{
    int nPID = 0;
#ifdef WNT
    nPID = GetCurrentProcessId();
#else
    nPID = getpid();
#endif

    return nPID;
}

void ProcessHandler::write(int _nPID)
{
    // get own PID

    if (m_sProcessIDFilename.size() > 0)
    {
        FILE* out;
        out = fopen(m_sProcessIDFilename.c_str(), "w");
        if (!out)
        {
            fprintf(stderr, "warning: (testshl.cxx) can't write own pid.\n");
            return;
            // exit(0);
        }
        fprintf(out, "%d", _nPID);
        fclose(out);
        my_sleep(2); // short wait, so testshl2_timeout can find this pid.
    }
    else
    {
        fprintf(stderr, "warning: (testshl.cxx) PID Filename empty, must set.\n");
    }
}

ProcessHandler::~ProcessHandler()
{
    if (m_sProcessIDFilename.size() > 0)
    {
        write(0);
        my_sleep(2);
        fprintf(stderr, "hint: it is save to remove PID file.\n");
    }
}

// -----------------------------------------------------------------------------
std::auto_ptr<CppUnit::TestResult> initResult(GetOpt & _aOptions)
{
    std::auto_ptr<CppUnit::TestResult> pResult;
    if (_aOptions.hasOpt("-mode"))
    {
        if (_aOptions.getOpt("-mode").equals("emacs") == sal_True)
        {
            pResult = std::auto_ptr<CppUnit::TestResult>(new CppUnit::emacsTestResult(_aOptions));
        }
    }
    else
    {
        pResult = std::auto_ptr<CppUnit::TestResult>(new CppUnit::testshlTestResult(_aOptions));
    }
    return pResult;
}

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

std::auto_ptr<Outputter> initOutputter(GetOpt & _aOptions)
{
    std::auto_ptr<Outputter> pOutputter;

    if (_aOptions.hasOpt("-log"))
    {
        rtl::OString sLogFile = _aOptions.getOpt("-log");

        Log* pLog = new Log( FileHelper::convertPath( sLogFile ) );
        if ( pLog->open() != osl::FileBase::E_None )
        {
            // cerr << "could not open LogFile: " << pLog->getName().getStr() << endl;
            fprintf(stderr, "could not open LogFile: %s\n", pLog->getName().getStr());
            exit(1);
        }
        pOutputter = std::auto_ptr<Outputter>(new Outputter(pLog));
    }
    else
    {
        pOutputter = std::auto_ptr<Outputter>(new Outputter(std::cout));
    }

    return pOutputter;
}

int starttest(GetOpt & opt, AutomaticRegisterHelper const& aHelper);

void endless()
{
    while(1)
    {
        my_sleep(1);
    }
}

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
    static char* optionSet[] = {
        "-boom,         stop near error position, exception only",
        "-mode=s,       the output mode, emacs, xml, old. Default is -mode old",
        "-log=s,        destination file for logging",
        "-noerrors,     shows all tests, but not it's errors.",
        "-onlyerrors,   shows only the failed test functions",
/*      "-tc=s@,        name(s) of testcase(s) to generate", */
        "-sf=s,         absolute path and name to the signal file.",
//! new (helpful if at debug time)
        "-dntsf,        if given, do not touch signal file, also if one exist.",
        "-dnrmsf,       do not remove signalfile. ",
        "-jobonly=s,    job control file, these jobs should only executed.",
        "-jobexclude=s, job control file, but contains only job, they not execute.",
        "-jobfilter=s,  use a filter for just some tests.",
        "-onlyshowjobs, show only all jobs, do no tests.",
        "-forward=s,    this string will forwarded to the test libraries.",
        "-projectid=s,  this text is added to the date output line.",
        "-buildid=s,    this text is added to the date output line.",
        "-waitforkey,   wait until key pressed.",
        "-verbose,      be verbose.",
        "-quiet,        be quiet. No t_print(...) will create output.",
        "-pid=s,        write current process id to file",
        "-endless,      testshl runs endless, for test only!!!",
        "-whereami,     shows at runtime, which function is tested next.",
        "-noerroronexit, if this is given the program exits with return code 0 even if runtime errors occurs.",
        "-h:s,          display help or help on option",
        "-help:s,       see -h",
        NULL
    };

    ProcessHandler aCurrentProcess;

    GetOpt opt( argv, optionSet );
    if ( opt.hasOpt("-pid") )
    {
        aCurrentProcess.setName(opt.getOpt("-pid").getStr());
    }

    if ( opt.hasOpt("-verbose") )
    {
        fprintf(stderr, "testshl2 $Revision: 1.14 $\n");
    }

    if ( opt.hasOpt("-endless"))                 // this exists only for self test issues
    {
        endless();
    }

    int  nExitCode = 0;
    bool bLibrary = true;

    // someone indicates that he needs help
    if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) )
    {
        opt.showUsage();
        nExitCode = 0;
    }
    else
    {
        if (opt.getParams().empty())
        {
            // no library is given, but if a jobonly list is given, we should generate UNKNOWN errors.
            if (! opt.hasOpt("-jobonly"))
            {
                // std::cerr << "error: At least a library or a job file should given." << std::endl;
                fprintf(stderr, "error: At least a library or a job file should given.\n");
                opt.showUsage();
                nExitCode = 2;
            }
            else
            {
                bLibrary = false;
            }
        }
        else
        {
            setSignalFilename(opt);

//#ifdef UNDER_WINDOWS_DEBUGGING
//    DebugBreak();
//#endif
            rtl::OUString suLibraryName;
            if (bLibrary)
            {
                suLibraryName = rtl::OStringToOUString(opt.getFirstParam(), osl_getThreadTextEncoding() /* RTL_TEXTENCODING_ASCII_US */ );
            }

            AutomaticRegisterHelper aHelper(suLibraryName, opt /*, &aJobs*/);

            // start the tests
            nExitCode = starttest(opt, aHelper);
        }
    }

    if (opt.hasOpt("-noerroronexit"))
    {
        nExitCode = 0;
    }
    return nExitCode;
}

// -----------------------------------------------------------------------------
// this function is only inserted to give a better startpoint for breakpoints

int starttest(GetOpt & opt, AutomaticRegisterHelper const& aHelper)
{
    // create a TestResult
    std::auto_ptr<CppUnit::TestResult> pResult = initResult(opt);

    // call all test functions
    aHelper.CallAll(pResult.get());

    // create and open log
    std::auto_ptr<Outputter> pOutput = initOutputter(opt);

    // give the output
    pResult->print(*pOutput.get());

    // this is a debug extension, so you can read the output and after a key is pressed the program will end.
    if (opt.hasOpt("-waitforkey"))
    {
        fprintf(stderr, "Press return key.");
        fflush(stderr);
        getchar();
    }
    int nExit = pResult->getExitValue();
    return nExit;
}

<|endoftext|>


<commit_before>/**
  * Touhou Community Reliant Automatic Patcher
  * Tasogare Frontier support plugin
  *
  * ----
  *
  * New Super Marisa Land support functions
  */

#include <thcrap.h>
#include "./png.h"
#include "thcrap_tasofro.h"

int patch_cv2(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*);
int patch_bmp(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*);

int nsml_init()
{
	if (game_id == TH_MEGAMARI) {
		patchhook_register("*.bmp", patch_bmp);
	}
	if (game_id == TH_NSML || game_id == TH105) {
		patchhook_register("*.cv2", patch_cv2);
	}
	return 0;
}

int patch_cv2(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*)
{
	BYTE *file_out = (BYTE*)file_inout;
	VLA(char, fn_png, strlen(fn) + 1);
	strcpy(fn_png, fn);
	strcpy(PathFindExtensionA(fn_png), ".png");

	uint32_t width, height;
	uint8_t bpp;
	BYTE** row_pointers = png_image_read(fn_png, &width, &height, &bpp);
	VLA_FREE(fn_png);

	if (!row_pointers) {
		return 0;
	}

	if (17 + width * height * 4 > size_out) {
		log_print("Destination buffer too small!\n");
		free(row_pointers);
		return -1;
	}

	file_out[0] = bpp;
	DWORD *header = (DWORD*)(file_out + 1);
	header[0] = width;
	header[1] = height;
	header[2] = width;
	header[3] = 0;
	for (unsigned int h = 0; h < height; h++) {
		for (unsigned int w = 0; w < width; w++) {
			file_out[17 + h * width * 4 + w * 4 + 0] = row_pointers[h][w * bpp / 8 + 2];
			file_out[17 + h * width * 4 + w * 4 + 1] = row_pointers[h][w * bpp / 8 + 1];
			file_out[17 + h * width * 4 + w * 4 + 2] = row_pointers[h][w * bpp / 8 + 0];
			if (bpp == 32) {
				file_out[17 + h * width * 4 + w * 4 + 3] = row_pointers[h][w * bpp / 8 + 3];
			}
			else {
				file_out[17 + h * width * 4 + w * 4 + 3] = 0xFF;
			}
		}
	}

	free(row_pointers);
	return 1;
}

int patch_bmp(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*)
{
	VLA(char, fn_png, strlen(fn) + 1);
	strcpy(fn_png, fn);
	strcpy(PathFindExtensionA(fn_png), ".png");

	uint32_t width, height, rowbytes;
	uint8_t bpp;
	BYTE** row_pointers = png_image_read(fn_png, &width, &height, &bpp);
	VLA_FREE(fn_png);

	if (!row_pointers) {
		return 0;
	}

	rowbytes = width * bpp / 8;
	if (rowbytes % 4 != 0) {
		rowbytes += 4 - (rowbytes % 4);
	}
	if (size_out < sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + rowbytes * height) {
		log_print("Destination buffer too small!\n");
		free(row_pointers);
		return -1;
	}

	BITMAPFILEHEADER *bpFile = (BITMAPFILEHEADER*)file_inout;
	BITMAPINFOHEADER *bpInfo = (BITMAPINFOHEADER*)(bpFile + 1);
	BYTE *bpData = (BYTE*)(bpInfo + 1);
	bpFile->bfType = 0x4D42;
	bpFile->bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + rowbytes * height;
	bpFile->bfReserved1 = 0;
	bpFile->bfReserved2 = 0;
	bpFile->bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

	bpInfo->biSize = sizeof(BITMAPINFOHEADER);
	bpInfo->biWidth = width;
	bpInfo->biHeight = height;
	bpInfo->biPlanes = 1;
	bpInfo->biBitCount = bpp;
	bpInfo->biCompression = (bpp == 32 ? BI_BITFIELDS : BI_RGB);
	bpInfo->biSizeImage = rowbytes * height;
	bpInfo->biXPelsPerMeter = 65535;
	bpInfo->biYPelsPerMeter = 65535;
	bpInfo->biClrUsed = 0;
	bpInfo->biClrImportant = 0;

	for (unsigned int h = 0; h < height; h++) {
		unsigned int pos = 0;
		for (unsigned int w = 0; w < width; w++) {
			bpData[h * rowbytes + pos + 0] = row_pointers[height - h - 1][w * bpp / 8 + 2];
			bpData[h * rowbytes + pos + 1] = row_pointers[height - h - 1][w * bpp / 8 + 1];
			bpData[h * rowbytes + pos + 2] = row_pointers[height - h - 1][w * bpp / 8 + 0];
			if (bpp == 32) {
				bpData[h * rowbytes + pos + 3] = row_pointers[height - h - 1][w * bpp / 8 + 3];
			}
			pos += bpp / 8;
		}
		// Padding
		while (pos % 4) {
			bpData[h * rowbytes + pos] = 0;
			pos++;
		}
	}

	free(row_pointers);
	return 1;
}

int BP_nsml_file_header(x86_reg_t *regs, json_t *bp_info)
{
	// Parameters
	// ----------
	const char *filename = (const char*)json_object_get_immediate(bp_info, regs, "file_name");
	size_t fn_size = json_object_get_immediate(bp_info, regs, "fn_size");
	// ----------

	char *uFilename;
	if (fn_size) {
		uFilename = EnsureUTF8(filename, fn_size);
	}
	else {
		uFilename = EnsureUTF8(filename, strlen(filename));
	}
	CharLowerA(uFilename);

	json_t *new_bp_info = json_copy(bp_info);
	json_object_set_new(new_bp_info, "file_name", json_integer((json_int_t)uFilename));
	int ret = BP_file_header(regs, new_bp_info);
	json_decref(new_bp_info);
	free(uFilename);
	return ret;
}

static void megamari_patch(const file_rep_t *fr, BYTE *buffer, size_t size)
{
	BYTE key = ((fr->offset >> 1) | 8) & 0xFF;
	for (unsigned int i = 0; i < size; i++) {
		buffer[i] ^= key;
	}
}

static void nsml_patch(const file_rep_t *fr, BYTE *buffer, size_t size)
{
	BYTE key = ((fr->offset >> 1) | 0x23) & 0xFF;
	for (unsigned int i = 0; i < size; i++) {
		buffer[i] ^= key;
	}
}

int BP_nsml_read_file(x86_reg_t *regs, json_t *bp_info)
{
	// Parameters
	// ----------
	const char *file_name = (const char*)json_object_get_immediate(bp_info, regs, "file_name");
	// ----------

	json_t *new_bp_info = json_copy(bp_info);
	char *uFilename = nullptr;

	if (file_name) {
		uFilename = EnsureUTF8(file_name, strlen(file_name));
		CharLowerA(uFilename);
		json_object_set_new(new_bp_info, "file_name", json_integer((json_int_t)uFilename));
	}

	if (game_id == TH_MEGAMARI) {
		json_object_set_new(new_bp_info, "post_read", json_integer((json_int_t)megamari_patch));
		json_object_set_new(new_bp_info, "post_patch", json_integer((json_int_t)megamari_patch));
	}
	else {
		json_object_set_new(new_bp_info, "post_read", json_integer((json_int_t)nsml_patch));
		json_object_set_new(new_bp_info, "post_patch", json_integer((json_int_t)nsml_patch));
	}
	int ret = BP_fragmented_read_file(regs, new_bp_info);
	json_decref(new_bp_info);
	free(uFilename);
	return ret;
}

// In th105, relying on the last open file doesn't work. So we'll use the file object instead.
int BP_th105_file_new(x86_reg_t *regs, json_t *bp_info)
{
	// Parameters
	// ----------
	const char *file_name = (const char*)json_object_get_immediate(bp_info, regs, "file_name");
	void *file_object = (void*)json_object_get_immediate(bp_info, regs, "file_object");
	// ----------

	if (!file_name || !file_object) {
		return 1;
	}
	char *uFilename = EnsureUTF8(file_name, strlen(file_name));
	file_rep_t *fr = file_rep_get(uFilename);
	if (fr) {
		file_rep_set_object(fr, file_object);
	}
	free(uFilename);
	return 1;
}

int BP_th105_file_delete(x86_reg_t *regs, json_t *bp_info)
{
	// Parameters
	// ----------
	void *file_object = (void*)json_object_get_immediate(bp_info, regs, "file_object");
	// ----------

	if (!file_object) {
		return 1;
	}
	file_rep_t *fr = file_rep_get_by_object(file_object);
	if (fr) {
		file_rep_set_object(fr, nullptr);
	}
	return 1;
}
<commit_msg>thcrap_tasofro: ignore case when patching files. [V]<commit_after>/**
  * Touhou Community Reliant Automatic Patcher
  * Tasogare Frontier support plugin
  *
  * ----
  *
  * New Super Marisa Land support functions
  */

#include <thcrap.h>
#include "./png.h"
#include "thcrap_tasofro.h"

int patch_cv2(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*);
int patch_bmp(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*);

int nsml_init()
{
	if (game_id == TH_MEGAMARI) {
		patchhook_register("*.bmp", patch_bmp);
	}
	if (game_id == TH_NSML || game_id == TH105) {
		patchhook_register("*.cv2", patch_cv2);
	}
	return 0;
}

int patch_cv2(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*)
{
	BYTE *file_out = (BYTE*)file_inout;
	VLA(char, fn_png, strlen(fn) + 1);
	strcpy(fn_png, fn);
	strcpy(PathFindExtensionA(fn_png), ".png");

	uint32_t width, height;
	uint8_t bpp;
	BYTE** row_pointers = png_image_read(fn_png, &width, &height, &bpp);
	VLA_FREE(fn_png);

	if (!row_pointers) {
		return 0;
	}

	if (17 + width * height * 4 > size_out) {
		log_print("Destination buffer too small!\n");
		free(row_pointers);
		return -1;
	}

	file_out[0] = bpp;
	DWORD *header = (DWORD*)(file_out + 1);
	header[0] = width;
	header[1] = height;
	header[2] = width;
	header[3] = 0;
	for (unsigned int h = 0; h < height; h++) {
		for (unsigned int w = 0; w < width; w++) {
			file_out[17 + h * width * 4 + w * 4 + 0] = row_pointers[h][w * bpp / 8 + 2];
			file_out[17 + h * width * 4 + w * 4 + 1] = row_pointers[h][w * bpp / 8 + 1];
			file_out[17 + h * width * 4 + w * 4 + 2] = row_pointers[h][w * bpp / 8 + 0];
			if (bpp == 32) {
				file_out[17 + h * width * 4 + w * 4 + 3] = row_pointers[h][w * bpp / 8 + 3];
			}
			else {
				file_out[17 + h * width * 4 + w * 4 + 3] = 0xFF;
			}
		}
	}

	free(row_pointers);
	return 1;
}

int patch_bmp(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*)
{
	VLA(char, fn_png, strlen(fn) + 1);
	strcpy(fn_png, fn);
	strcpy(PathFindExtensionA(fn_png), ".png");

	uint32_t width, height, rowbytes;
	uint8_t bpp;
	BYTE** row_pointers = png_image_read(fn_png, &width, &height, &bpp);
	VLA_FREE(fn_png);

	if (!row_pointers) {
		return 0;
	}

	rowbytes = width * bpp / 8;
	if (rowbytes % 4 != 0) {
		rowbytes += 4 - (rowbytes % 4);
	}
	if (size_out < sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + rowbytes * height) {
		log_print("Destination buffer too small!\n");
		free(row_pointers);
		return -1;
	}

	BITMAPFILEHEADER *bpFile = (BITMAPFILEHEADER*)file_inout;
	BITMAPINFOHEADER *bpInfo = (BITMAPINFOHEADER*)(bpFile + 1);
	BYTE *bpData = (BYTE*)(bpInfo + 1);
	bpFile->bfType = 0x4D42;
	bpFile->bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + rowbytes * height;
	bpFile->bfReserved1 = 0;
	bpFile->bfReserved2 = 0;
	bpFile->bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

	bpInfo->biSize = sizeof(BITMAPINFOHEADER);
	bpInfo->biWidth = width;
	bpInfo->biHeight = height;
	bpInfo->biPlanes = 1;
	bpInfo->biBitCount = bpp;
	bpInfo->biCompression = (bpp == 32 ? BI_BITFIELDS : BI_RGB);
	bpInfo->biSizeImage = rowbytes * height;
	bpInfo->biXPelsPerMeter = 65535;
	bpInfo->biYPelsPerMeter = 65535;
	bpInfo->biClrUsed = 0;
	bpInfo->biClrImportant = 0;

	for (unsigned int h = 0; h < height; h++) {
		unsigned int pos = 0;
		for (unsigned int w = 0; w < width; w++) {
			bpData[h * rowbytes + pos + 0] = row_pointers[height - h - 1][w * bpp / 8 + 2];
			bpData[h * rowbytes + pos + 1] = row_pointers[height - h - 1][w * bpp / 8 + 1];
			bpData[h * rowbytes + pos + 2] = row_pointers[height - h - 1][w * bpp / 8 + 0];
			if (bpp == 32) {
				bpData[h * rowbytes + pos + 3] = row_pointers[height - h - 1][w * bpp / 8 + 3];
			}
			pos += bpp / 8;
		}
		// Padding
		while (pos % 4) {
			bpData[h * rowbytes + pos] = 0;
			pos++;
		}
	}

	free(row_pointers);
	return 1;
}

int BP_nsml_file_header(x86_reg_t *regs, json_t *bp_info)
{
	// Parameters
	// ----------
	const char *filename = (const char*)json_object_get_immediate(bp_info, regs, "file_name");
	size_t fn_size = json_object_get_immediate(bp_info, regs, "fn_size");
	// ----------

	char *uFilename;
	if (fn_size) {
		uFilename = EnsureUTF8(filename, fn_size);
	}
	else {
		uFilename = EnsureUTF8(filename, strlen(filename));
	}
	CharLowerA(uFilename);

	json_t *new_bp_info = json_copy(bp_info);
	json_object_set_new(new_bp_info, "file_name", json_integer((json_int_t)uFilename));
	int ret = BP_file_header(regs, new_bp_info);
	json_decref(new_bp_info);
	free(uFilename);
	return ret;
}

static void megamari_patch(const file_rep_t *fr, BYTE *buffer, size_t size)
{
	BYTE key = ((fr->offset >> 1) | 8) & 0xFF;
	for (unsigned int i = 0; i < size; i++) {
		buffer[i] ^= key;
	}
}

static void nsml_patch(const file_rep_t *fr, BYTE *buffer, size_t size)
{
	BYTE key = ((fr->offset >> 1) | 0x23) & 0xFF;
	for (unsigned int i = 0; i < size; i++) {
		buffer[i] ^= key;
	}
}

int BP_nsml_read_file(x86_reg_t *regs, json_t *bp_info)
{
	// Parameters
	// ----------
	const char *file_name = (const char*)json_object_get_immediate(bp_info, regs, "file_name");
	// ----------

	json_t *new_bp_info = json_copy(bp_info);
	char *uFilename = nullptr;

	if (file_name) {
		uFilename = EnsureUTF8(file_name, strlen(file_name));
		CharLowerA(uFilename);
		json_object_set_new(new_bp_info, "file_name", json_integer((json_int_t)uFilename));
	}

	if (game_id == TH_MEGAMARI) {
		json_object_set_new(new_bp_info, "post_read", json_integer((json_int_t)megamari_patch));
		json_object_set_new(new_bp_info, "post_patch", json_integer((json_int_t)megamari_patch));
	}
	else {
		json_object_set_new(new_bp_info, "post_read", json_integer((json_int_t)nsml_patch));
		json_object_set_new(new_bp_info, "post_patch", json_integer((json_int_t)nsml_patch));
	}
	int ret = BP_fragmented_read_file(regs, new_bp_info);
	json_decref(new_bp_info);
	free(uFilename);
	return ret;
}

// In th105, relying on the last open file doesn't work. So we'll use the file object instead.
int BP_th105_file_new(x86_reg_t *regs, json_t *bp_info)
{
	// Parameters
	// ----------
	const char *file_name = (const char*)json_object_get_immediate(bp_info, regs, "file_name");
	void *file_object = (void*)json_object_get_immediate(bp_info, regs, "file_object");
	// ----------

	if (!file_name || !file_object) {
		return 1;
	}
	char *uFilename = EnsureUTF8(file_name, strlen(file_name));
	CharLowerA(uFilename);
	file_rep_t *fr = file_rep_get(uFilename);
	if (fr) {
		file_rep_set_object(fr, file_object);
	}
	free(uFilename);
	return 1;
}

int BP_th105_file_delete(x86_reg_t *regs, json_t *bp_info)
{
	// Parameters
	// ----------
	void *file_object = (void*)json_object_get_immediate(bp_info, regs, "file_object");
	// ----------

	if (!file_object) {
		return 1;
	}
	file_rep_t *fr = file_rep_get_by_object(file_object);
	if (fr) {
		file_rep_set_object(fr, nullptr);
	}
	return 1;
}
<|endoftext|>


<commit_before>#include <stdio.h>

#include <cppuhelper/bootstrap.hxx>

#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/XComponent.hpp>

using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;

int main()
{
    try
    {

        Reference< XSimpleRegistry > r1 =  createSimpleRegistry();
        Reference< XSimpleRegistry > r2 =  createSimpleRegistry();
        r1->open( OUString( RTL_CONSTASCII_USTRINGPARAM( "test1.rdb" ) ), sal_True, sal_False );
        r2->open( OUString( RTL_CONSTASCII_USTRINGPARAM( "test2.rdb" ) ), sal_True, sal_False );
        Reference< XSimpleRegistry > r = createNestedRegistry( );
        Reference< XInitialization > rInit( r, UNO_QUERY );
        Sequence< Any > seq( 2 );
        seq[0] <<= r1;
        seq[1] <<= r2;
        rInit->initialize( seq );

        Reference< XComponentContext > rComp = bootstrap_InitialComponentContext( r );

        Reference< XContentEnumerationAccess > xCtAccess( rComp->getServiceManager(), UNO_QUERY );

        Reference< XEnumeration > rEnum =
            xCtAccess->createContentEnumeration( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.bridge.Bridge" ) ) );

        sal_Int32 n = 0;
        while( rEnum->hasMoreElements() )
        {
            Reference< XServiceInfo > r;
            rEnum->nextElement() >>= r;
            OString o = OUStringToOString( r->getImplementationName() , RTL_TEXTENCODING_ASCII_US );
            printf( "%s\n" , o.getStr() );
            Sequence< OUString > seq = r->getSupportedServiceNames();
            for( int i = 0 ;i < seq.getLength() ; i ++  )
            {
                o = OUStringToOString( seq[i] , RTL_TEXTENCODING_ASCII_US );
                printf( "   %s\n" , o.getStr() );
            }
            n ++;
        }
        // there are two services in two registries !
        OSL_ASSERT( 2 == n );
        if( 2 == n )
        {
            printf( "test passed\n" );
        }

        Reference< XComponent > xComp( rComp, UNO_QUERY );
        xComp->dispose();
        try
        {
            xCtAccess->createContentEnumeration(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "blabla" ) ) );
        }
        catch (DisposedException &)
        {
            printf( "already disposed results in DisposedException: ok.\n" );
            return 0;
        }
        fprintf( stderr, "missing DisposedException!\n" );
        return 1;
    }
    catch ( Exception & e )
    {
        OString o =  OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );
        printf( "%s\n" , o.getStr() );
        OSL_ASSERT( 0 );
        return 1;
    }
}
<commit_msg>INTEGRATION: CWS cd02 (1.3.156); FILE MERGED 2004/11/15 17:29:02 dbo 1.3.156.1: #i24030# general cleanup to make buildable again<commit_after>#include <stdio.h>

#include <sal/main.h>
#include <cppuhelper/bootstrap.hxx>

#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/XComponent.hpp>

using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;

SAL_IMPLEMENT_MAIN()
{
    try
    {

        Reference< XSimpleRegistry > r1 =  createSimpleRegistry();
        Reference< XSimpleRegistry > r2 =  createSimpleRegistry();
        r1->open( OUString( RTL_CONSTASCII_USTRINGPARAM( "test1.rdb" ) ), sal_True, sal_False );
        r2->open( OUString( RTL_CONSTASCII_USTRINGPARAM( "test2.rdb" ) ), sal_True, sal_False );
        Reference< XSimpleRegistry > r = createNestedRegistry( );
        Reference< XInitialization > rInit( r, UNO_QUERY );
        Sequence< Any > seq( 2 );
        seq[0] <<= r1;
        seq[1] <<= r2;
        rInit->initialize( seq );

        Reference< XComponentContext > rComp = bootstrap_InitialComponentContext( r );

        Reference< XContentEnumerationAccess > xCtAccess( rComp->getServiceManager(), UNO_QUERY );

        Reference< XEnumeration > rEnum =
            xCtAccess->createContentEnumeration( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.bridge.Bridge" ) ) );

        sal_Int32 n = 0;
        while( rEnum->hasMoreElements() )
        {
            Reference< XServiceInfo > r;
            rEnum->nextElement() >>= r;
            OString o = OUStringToOString( r->getImplementationName() , RTL_TEXTENCODING_ASCII_US );
            printf( "%s\n" , o.getStr() );
            Sequence< OUString > seq = r->getSupportedServiceNames();
            for( int i = 0 ;i < seq.getLength() ; i ++  )
            {
                o = OUStringToOString( seq[i] , RTL_TEXTENCODING_ASCII_US );
                printf( "   %s\n" , o.getStr() );
            }
            n ++;
        }
        // there are two services in two registries !
        OSL_ASSERT( 2 == n );
        if( 2 == n )
        {
            printf( "test passed\n" );
        }

        Reference< XComponent > xComp( rComp, UNO_QUERY );
        xComp->dispose();
        try
        {
            xCtAccess->createContentEnumeration(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "blabla" ) ) );
        }
        catch (DisposedException &)
        {
            printf( "already disposed results in DisposedException: ok.\n" );
            return 0;
        }
        fprintf( stderr, "missing DisposedException!\n" );
        return 1;
    }
    catch ( Exception & e )
    {
        OString o =  OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );
        printf( "%s\n" , o.getStr() );
        OSL_ASSERT( 0 );
        return 1;
    }
}
<|endoftext|>


<commit_before>// @(#)root/tmva $Id: SdivSqrtSplusB.cxx,v 1.12 2007/04/19 06:53:02 brun Exp $
// Author: Andreas Hoecker, Joerg Stelzer, Helge Voss

/**********************************************************************************
 * Project: TMVA - a Root-integrated toolkit for multivariate data analysis       *
 * Package: TMVA                                                                  *
 * Class  : SdivSqrtSplusB                                                        *
 * Web    : http://tmva.sourceforge.net                                           *
 *                                                                                *
 * Description: Implementation of the SdivSqrtSplusB as separation criterion      *
 *              s / sqrt( s+b )                                                   *
 *                                                                                *
 *                                                                                *
 * Authors (alphabetical):                                                        *
 *      Andreas Hoecker <Andreas.Hocker@cern.ch> - CERN, Switzerland              *
 *      Xavier Prudent  <prudent@lapp.in2p3.fr>  - LAPP, France                   *
 *      Helge Voss      <Helge.Voss@cern.ch>     - MPI-K Heidelberg, Germany      *
 *      Kai Voss        <Kai.Voss@cern.ch>       - U. of Victoria, Canada         *
 *                                                                                *
 * Copyright (c) 2005:                                                            *
 *      CERN, Switzerland,                                                        *
 *      U. of Victoria, Canada,                                                   *
 *      Heidelberg U., Germany,                                                   *
 *      LAPP, Annecy, France                                                      *
 *                                                                                *
 * Redistribution and use in source and binary forms, with or without             *
 * modification, are permitted according to the terms listed in LICENSE           *
 * (http://tmva.sourceforge.net/LICENSE)                                          *
 **********************************************************************************/

#include "TMath.h"
#include "TMVA/SdivSqrtSplusB.h"

ClassImp(TMVA::SdivSqrtSplusB)

//_______________________________________________________________________
Double_t  TMVA::SdivSqrtSplusB::GetSeparationIndex( const Double_t &s, const Double_t &b )
{
   // Index = S/sqrt(S+B)  (statistical significance)
  if (s+b > 0) return s / TMath::Sqrt(s+b);
  else return 0;
}

<commit_msg>Fix coding conventions.<commit_after>// @(#)root/tmva $Id: SdivSqrtSplusB.cxx,v 1.13 2007/04/21 14:20:46 brun Exp $
// Author: Andreas Hoecker, Joerg Stelzer, Helge Voss

/**********************************************************************************
 * Project: TMVA - a Root-integrated toolkit for multivariate data analysis       *
 * Package: TMVA                                                                  *
 * Class  : SdivSqrtSplusB                                                        *
 * Web    : http://tmva.sourceforge.net                                           *
 *                                                                                *
 * Description: Implementation of the SdivSqrtSplusB as separation criterion      *
 *              s / sqrt( s+b )                                                   *
 *                                                                                *
 *                                                                                *
 * Authors (alphabetical):                                                        *
 *      Andreas Hoecker <Andreas.Hocker@cern.ch> - CERN, Switzerland              *
 *      Xavier Prudent  <prudent@lapp.in2p3.fr>  - LAPP, France                   *
 *      Helge Voss      <Helge.Voss@cern.ch>     - MPI-K Heidelberg, Germany      *
 *      Kai Voss        <Kai.Voss@cern.ch>       - U. of Victoria, Canada         *
 *                                                                                *
 * Copyright (c) 2005:                                                            *
 *      CERN, Switzerland,                                                        *
 *      U. of Victoria, Canada,                                                   *
 *      Heidelberg U., Germany,                                                   *
 *      LAPP, Annecy, France                                                      *
 *                                                                                *
 * Redistribution and use in source and binary forms, with or without             *
 * modification, are permitted according to the terms listed in LICENSE           *
 * (http://tmva.sourceforge.net/LICENSE)                                          *
 **********************************************************************************/

#include "TMath.h"
#include "TMVA/SdivSqrtSplusB.h"

ClassImp(TMVA::SdivSqrtSplusB)

//_______________________________________________________________________
Double_t  TMVA::SdivSqrtSplusB::GetSeparationIndex( const Double_t &s, const Double_t &b )
{
   // Index = S/sqrt(S+B)  (statistical significance)
   if (s+b > 0) return s / TMath::Sqrt(s+b);
   else return 0;
}

<|endoftext|>