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

YASK: Yet Another Stencil Kernel
Copyright (c) 2014-2018, Intel Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

* The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

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

// Implement isotropic 3D finite-difference (FD) stencil, nth-order accurate in
// space (where n = 2 * radius) and 2nd-order accurate in time.

#include "Soln.hpp"

class Iso3dfdStencil : public StencilRadiusBase {

protected:

    // Indices & dimensions.
    MAKE_STEP_INDEX(t);           // step in time dim.
    MAKE_DOMAIN_INDEX(x);         // spatial dim.
    MAKE_DOMAIN_INDEX(y);         // spatial dim.
    MAKE_DOMAIN_INDEX(z);         // spatial dim.
    MAKE_MISC_INDEX(r);           // to index the coefficients.

    // Grids.
    MAKE_GRID(pressure, t, x, y, z); // time-varying 3D pressure grid.
    MAKE_GRID(vel, x, y, z);         // constant 3D vel grid.
    MAKE_ARRAY(coeff, r);            // FD coefficients.

public:

    // For this stencil, the 'radius' is the number of FD coefficients on
    // either side of center in each spatial dimension.  For example,
    // radius=8 implements a 16th-order accurate FD stencil.  To obtain the
    // correct result, the 'coeff' array should be initialized with the
    // corresponding central FD coefficients, adjusted for grid spacing.
    // The accuracy in time is fixed at 2nd order.
    Iso3dfdStencil(StencilList& stencils, string suffix="", int radius=8) :
        StencilRadiusBase("iso3dfd" + suffix, stencils, radius) { }
    virtual ~Iso3dfdStencil() { }

    // Define RHS expression for pressure at t+1 based on values from vel and pressure at t.
    virtual GridValue get_next_p() {

        // Start with center value multiplied by coeff 0.
        GridValue next_p = pressure(t, x, y, z) * coeff(0);

        // Add values from x, y, and z axes multiplied by the
        // coeff for the given radius.
        for (int r = 1; r <= _radius; r++) {

            // Add values from axes at radius r.
            next_p += (
                       // x-axis.
                       pressure(t, x-r, y, z) +
                       pressure(t, x+r, y, z) +

                       // y-axis.
                       pressure(t, x, y-r, z) +
                       pressure(t, x, y+r, z) +

                       // z-axis.
                       pressure(t, x, y, z-r) +
                       pressure(t, x, y, z+r)

                       ) * coeff(r);
        }

        // Finish equation, including t-1 and velocity components.
        next_p = (2.0 * pressure(t, x, y, z))
            - pressure(t-1, x, y, z) // subtract pressure from t-1.
            + (next_p * vel(x, y, z));       // add next_p * velocity.

        return next_p;
    }

    // Define equation for pressure at t+1 based on values from vel and pressure at t.
    virtual void define() {

        // Get equation for RHS.
        GridValue next_p = get_next_p();

        // Define the value at t+1 to be equal to next_p.
        // Since this implements the finite-difference method, this
        // is actually an approximation.
        pressure(t+1, x, y, z) EQUALS next_p;
    }
};

REGISTER_STENCIL(Iso3dfdStencil);

// Add a sponge absorption factor.
class Iso3dfdSpongeStencil : public Iso3dfdStencil {
protected:

    // Sponge coefficients.
    // In practice, the interior values would be set to 1.0,
    // and values nearer the boundary would be set to values
    // increasingly approaching 0.0.
    MAKE_ARRAY(cr_x, x);
    MAKE_ARRAY(cr_y, y);
    MAKE_ARRAY(cr_z, z);

public:
    Iso3dfdSpongeStencil(StencilList& stencils, int radius=8) :
        Iso3dfdStencil(stencils, "_sponge", radius) { }
    virtual ~Iso3dfdSpongeStencil() { }

    // Define equation for pressure at t+1 based on values from vel and pressure at t.
    virtual void define() {

        // Get equation for RHS.
        GridValue next_p = get_next_p();

        // Apply sponge absorption.
        next_p *= cr_x(x) * cr_y(y) * cr_z(z);

        // Define the value at t+1 to be equal to next_p.
        pressure(t+1, x, y, z) EQUALS next_p;
    }
};

REGISTER_STENCIL(Iso3dfdSpongeStencil);
<commit_msg>Add URL reference.<commit_after>/*****************************************************************************

YASK: Yet Another Stencil Kernel
Copyright (c) 2014-2018, Intel Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

* The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

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

// Implement isotropic 3D finite-difference (FD) stencil, nth-order accurate in
// space (where n = 2 * radius) and 2nd-order accurate in time.
// See https://software.intel.com/en-us/articles/eight-optimizations-for-3-dimensional-finite-difference-3dfd-code-with-an-isotropic-iso.

#include "Soln.hpp"

class Iso3dfdStencil : public StencilRadiusBase {

protected:

    // Indices & dimensions.
    MAKE_STEP_INDEX(t);           // step in time dim.
    MAKE_DOMAIN_INDEX(x);         // spatial dim.
    MAKE_DOMAIN_INDEX(y);         // spatial dim.
    MAKE_DOMAIN_INDEX(z);         // spatial dim.
    MAKE_MISC_INDEX(r);           // to index the coefficients.

    // Grids.
    MAKE_GRID(pressure, t, x, y, z); // time-varying 3D pressure grid.
    MAKE_GRID(vel, x, y, z);         // constant 3D vel grid (c(x,y,z)^2 * delta_t^2).
    MAKE_ARRAY(coeff, r);            // FD coefficients.

public:

    // For this stencil, the 'radius' is the number of FD coefficients on
    // either side of center in each spatial dimension.  For example,
    // radius=8 implements a 16th-order accurate FD stencil.  To obtain the
    // correct result, the 'coeff' array should be initialized with the
    // corresponding central FD coefficients, adjusted for grid spacing.
    // The accuracy in time is fixed at 2nd order.
    Iso3dfdStencil(StencilList& stencils, string suffix="", int radius=8) :
        StencilRadiusBase("iso3dfd" + suffix, stencils, radius) { }
    virtual ~Iso3dfdStencil() { }

    // Define RHS expression for pressure at t+1 based on values from vel and pressure at t.
    virtual GridValue get_next_p() {

        // Start with center value multiplied by coeff 0.
        GridValue next_p = pressure(t, x, y, z) * coeff(0);

        // Add values from x, y, and z axes multiplied by the
        // coeff for the given radius.
        for (int r = 1; r <= _radius; r++) {

            // Add values from axes at radius r.
            next_p += (
                       // x-axis.
                       pressure(t, x-r, y, z) +
                       pressure(t, x+r, y, z) +

                       // y-axis.
                       pressure(t, x, y-r, z) +
                       pressure(t, x, y+r, z) +

                       // z-axis.
                       pressure(t, x, y, z-r) +
                       pressure(t, x, y, z+r)

                       ) * coeff(r);
        }

        // Finish equation, including t-1 and velocity components.
        next_p = (2.0 * pressure(t, x, y, z))
            - pressure(t-1, x, y, z) // subtract pressure from t-1.
            + (next_p * vel(x, y, z));       // add next_p * velocity.

        return next_p;
    }

    // Define equation for pressure at t+1 based on values from vel and pressure at t.
    virtual void define() {

        // Get equation for RHS.
        GridValue next_p = get_next_p();

        // Define the value at t+1 to be equal to next_p.
        // Since this implements the finite-difference method, this
        // is actually an approximation.
        pressure(t+1, x, y, z) EQUALS next_p;
    }
};

REGISTER_STENCIL(Iso3dfdStencil);

// Add a sponge absorption factor.
class Iso3dfdSpongeStencil : public Iso3dfdStencil {
protected:

    // Sponge coefficients.
    // In practice, the interior values would be set to 1.0,
    // and values nearer the boundary would be set to values
    // increasingly approaching 0.0.
    MAKE_ARRAY(cr_x, x);
    MAKE_ARRAY(cr_y, y);
    MAKE_ARRAY(cr_z, z);

public:
    Iso3dfdSpongeStencil(StencilList& stencils, int radius=8) :
        Iso3dfdStencil(stencils, "_sponge", radius) { }
    virtual ~Iso3dfdSpongeStencil() { }

    // Define equation for pressure at t+1 based on values from vel and pressure at t.
    virtual void define() {

        // Get equation for RHS.
        GridValue next_p = get_next_p();

        // Apply sponge absorption.
        next_p *= cr_x(x) * cr_y(y) * cr_z(z);

        // Define the value at t+1 to be equal to next_p.
        pressure(t+1, x, y, z) EQUALS next_p;
    }
};

REGISTER_STENCIL(Iso3dfdSpongeStencil);
<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

#include "cinder/Capture.h"
#include "cinder/gl/Texture.h"
#include "cinder/gl/GlslProg.h"
#include "cinder/Log.h"
#include "cinder/gl/Fbo.h"

#include "GridTexture.h"
#include "Landscape.h"

#include "cinder/MotionManager.h"

using namespace ci;
using namespace ci::app;
using namespace std;

using namespace soso;

struct TouchInfo {
	TouchInfo() = default;
	TouchInfo( uint32_t iId, const vec2 &iStart, const vec2 &iPosition )
	: id( iId ),
		previous( iStart ),
		position( iPosition )
	{}

  uint32_t		id = 0;
  vec2				previous;
  vec2				position;
};

class SelfieSelfieApp : public App {
public:
	void setup() override;
	void update() override;
	void draw() override;

  void touchesBegan( TouchEvent event ) override;
  void touchesMoved( TouchEvent event ) override;
  void touchesEnded( TouchEvent event ) override;

	void updateCamera();

private:
	CameraPersp				camera;
  CaptureRef				capture;

  GridTextureRef		gridTexture;
  Landscape					landscape;
	gl::BatchRef			cameraImage;

  vector<TouchInfo> touches;
  ci::vec3					cameraOffset;
	float							cameraVelocity = 0.0f;

  bool							drawDebug = false;

};

void SelfieSelfieApp::setup()
{
  CI_LOG_I("Setting up selfie_x_selfie");

  MotionManager::enable();

  GLint size;
  glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
  CI_LOG_I( "Max texture size: " << size );

  auto target = vec3( 5, 0, 0 );
  camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
  camera.setPerspective( 80, getWindowAspectRatio(), 0.1f, 20.0f );

  try {
    CI_LOG_I( "Initializing hardware camera." );
    auto front_facing_camera = ([] {
      auto &devices = Capture::getDevices();
      auto first_device = devices.front();
      for( auto device : devices ) {
        if( device->isFrontFacing() ) {
          return device;
        }
      }
      return first_device;
    }());

    capture = Capture::create( 480, 360, front_facing_camera );
    capture->start();

    CI_LOG_I( "Creating Grid Texture" );
    gridTexture = make_shared<GridTexture>( ivec2( 320, 240 ), 12 );

    CI_LOG_I( "Setting up landscape geometry." );
    landscape.setup();
    landscape.setTextureUnits( 0, 1 );
    landscape.setGridSize( gridTexture->getGridDimensions() );
  }
  catch( ci::Exception &exc ) {
    CI_LOG_E( "Error using device camera: " << exc.what() );
  }

  auto err = gl::getError();
  if( err ) {
    CI_LOG_E( "Post-Setup gl error: " << gl::getErrorString(err) );
  }
}

void SelfieSelfieApp::touchesBegan( TouchEvent event )
{
  for( auto &t : event.getTouches() ) {
    touches.emplace_back( t.getId(), t.getPos(), t.getPos() );
  }

  if( touches.size() == 4 ) {
    drawDebug = ! drawDebug;
  }
}

void SelfieSelfieApp::touchesMoved( TouchEvent event )
{
  for( auto &t : event.getTouches() ) {
    for( auto &s : touches ) {
      if( s.id == t.getId() ) {
				s.previous = s.position;
        s.position = t.getPos();
      }
    }
  }
}

void SelfieSelfieApp::touchesEnded( TouchEvent event )
{
  touches.erase( std::remove_if( touches.begin(), touches.end(), [&event] (const TouchInfo &s) {
    for( auto &t : event.getTouches() ) {
      if (t.getId() == s.id) {
        return true;
      }
    }
    return false;
  }), touches.end() );
}

void SelfieSelfieApp::update()
{
	updateCamera();

  if( capture && capture->checkNewFrame() ) {
    gridTexture->update( *capture->getSurface() );

    auto err = gl::getError();
    if( err ) {
      CI_LOG_E( "Texture copy gl error: " << gl::getErrorString(err) );
    }
  }
}

void SelfieSelfieApp::updateCamera()
{
	if( touches.size() == 1 )
	{
		const auto forward = ([] {
			auto gravity = MotionManager::getGravityDirection();
			if( abs( gravity.x ) > abs( gravity.y ) ) {
				auto x = copysign( 1.0f, gravity.x );
				return vec3( x, 0, 0 );
			}
			else {
				auto y = copysign( 1.0f, gravity.y );
				return vec3( 0, - y, 0 );
			}
		}());

		auto &touch = touches.front();
		auto delta = vec3( touch.position - touch.previous, 0 );
		touch.previous = touch.position;

		auto amount = length( delta );
		auto dir = dot( normalize(delta), forward );

		if( isfinite( amount ) && isfinite( dir ) ) {
			cameraVelocity += amount * dir;
		}
	}

	auto ray = camera.getViewDirection();
	cameraOffset += ray * cameraVelocity * 0.0025f;
	cameraVelocity *= 0.86f;

	auto l = length(cameraOffset);
	auto maximum = 2.9f;
	if( l > maximum ) {
		cameraOffset *= (maximum / l);
	}
	camera.setEyePoint( cameraOffset );

  if( MotionManager::isDataAvailable() ) {
    auto r = MotionManager::getRotation();
    camera.setOrientation( r );
  }
}

void SelfieSelfieApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );

  {
    gl::enableDepthRead();
    gl::enableDepthWrite();
		gl::ScopedGlslProg prog( gl::getStockShader( gl::ShaderDef().texture(gridTexture->getTexture()->getTarget()) ) );

    gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
    gl::ScopedTextureBind tex1( gridTexture->getBlurredTexture(), 1 );
    gl::ScopedMatrices matrices;
    gl::setMatrices( camera );

		landscape.draw( gridTexture->getCurrentIndex() );

		auto mat = translate( vec3( 0, -4.0f, 0 ) );
		auto dims = vec2(gridTexture->getCellDimensions()) / gridTexture->getGridSize();
		auto offset = vec2(gridTexture->getIndexOffset( gridTexture->getCellDimensions(), gridTexture->getCurrentIndex() )) / gridTexture->getGridSize();
		auto rect = Rectf( -1.0f, -1.0f, 1.0f, 1.0f ).scaled( vec2( 1.333f, 1.0f ) ).scaled( 0.2f );
		auto half_pi = (float) M_PI / 2.0f;
		auto xf1 = translate( vec3( - 4.0f, 0.0f, 0.0f ) ) * rotate( - half_pi, vec3( 1, 0, 0 ) ) * rotate( half_pi, vec3( 0, 1, 0 ) );
		auto xf2 = translate( vec3( 4.0f, 0.0f, 0.0f ) ) * rotate( half_pi, vec3( 1, 0, 0 ) ) * rotate( - half_pi, vec3( 0, 1, 0 ) );

		{
			gl::ScopedModelMatrix m;
			gl::multModelMatrix( xf1 );
			gl::drawSolidRect( rect, offset, offset + dims );
		}

		{
			gl::ScopedModelMatrix m;
			gl::multModelMatrix( xf2 );
			gl::drawSolidRect( rect, offset, offset + dims );
		}

  }

  gl::disableDepthRead();

  if( drawDebug && gridTexture )
  {
    gl::setMatricesWindow( getWindowSize() );

    auto rect = Rectf(gridTexture->getTexture()->getBounds());
    auto window_rect = Rectf(getWindowBounds());
    auto window_rect_a = window_rect.scaled( vec2( 0.5f ) );
    auto window_rect_b = window_rect_a + vec2( window_rect_a.getWidth(), 0 );
    gl::draw( gridTexture->getTexture(), rect.getCenteredFit( window_rect_a, false ) );
    gl::draw( gridTexture->getBlurredTexture(), rect.getCenteredFit( window_rect_b, false ) );
  }

  /*
  // For confirming version changes, draw a different colored dot.
  gl::ScopedColor color( Color( 1.0f, 0.0f, 1.0f ) );
  gl::drawSolidCircle( vec2( 20.0f ), 10.0f );
  */

  auto err = gl::getError();
  if( err ) {
    CI_LOG_E( "Draw gl error: " << gl::getErrorString(err) );
  }
}

inline void prepareSettings( app::App::Settings *iSettings )
{
  iSettings->setMultiTouchEnabled();
}

CINDER_APP( SelfieSelfieApp, RendererGl, &prepareSettings )
<commit_msg>Only draw one central portrait.<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

#include "cinder/Capture.h"
#include "cinder/gl/Texture.h"
#include "cinder/gl/GlslProg.h"
#include "cinder/Log.h"
#include "cinder/gl/Fbo.h"

#include "GridTexture.h"
#include "Landscape.h"

#include "cinder/MotionManager.h"

using namespace ci;
using namespace ci::app;
using namespace std;

using namespace soso;

struct TouchInfo {
	TouchInfo() = default;
	TouchInfo( uint32_t iId, const vec2 &iStart, const vec2 &iPosition )
	: id( iId ),
		previous( iStart ),
		position( iPosition )
	{}

  uint32_t		id = 0;
  vec2				previous;
  vec2				position;
};

class SelfieSelfieApp : public App {
public:
	void setup() override;
	void update() override;
	void draw() override;

  void touchesBegan( TouchEvent event ) override;
  void touchesMoved( TouchEvent event ) override;
  void touchesEnded( TouchEvent event ) override;

	void updateCamera();

private:
	CameraPersp				camera;
  CaptureRef				capture;

  GridTextureRef		gridTexture;
  Landscape					landscape;
	gl::BatchRef			cameraImage;

  vector<TouchInfo> touches;
  ci::vec3					cameraOffset;
	float							cameraVelocity = 0.0f;

  bool							drawDebug = false;

};

void SelfieSelfieApp::setup()
{
  CI_LOG_I("Setting up selfie_x_selfie");

  MotionManager::enable();

  GLint size;
  glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
  CI_LOG_I( "Max texture size: " << size );

  auto target = vec3( 5, 0, 0 );
  camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
  camera.setPerspective( 80, getWindowAspectRatio(), 0.1f, 20.0f );

  try {
    CI_LOG_I( "Initializing hardware camera." );
    auto front_facing_camera = ([] {
      auto &devices = Capture::getDevices();
      auto first_device = devices.front();
      for( auto device : devices ) {
        if( device->isFrontFacing() ) {
          return device;
        }
      }
      return first_device;
    }());

    capture = Capture::create( 480, 360, front_facing_camera );
    capture->start();

    CI_LOG_I( "Creating Grid Texture" );
    gridTexture = make_shared<GridTexture>( ivec2( 320, 240 ), 12 );

    CI_LOG_I( "Setting up landscape geometry." );
    landscape.setup();
    landscape.setTextureUnits( 0, 1 );
    landscape.setGridSize( gridTexture->getGridDimensions() );
  }
  catch( ci::Exception &exc ) {
    CI_LOG_E( "Error using device camera: " << exc.what() );
  }

  auto err = gl::getError();
  if( err ) {
    CI_LOG_E( "Post-Setup gl error: " << gl::getErrorString(err) );
  }
}

void SelfieSelfieApp::touchesBegan( TouchEvent event )
{
  for( auto &t : event.getTouches() ) {
    touches.emplace_back( t.getId(), t.getPos(), t.getPos() );
  }

  if( touches.size() == 4 ) {
    drawDebug = ! drawDebug;
  }
}

void SelfieSelfieApp::touchesMoved( TouchEvent event )
{
  for( auto &t : event.getTouches() ) {
    for( auto &s : touches ) {
      if( s.id == t.getId() ) {
				s.previous = s.position;
        s.position = t.getPos();
      }
    }
  }
}

void SelfieSelfieApp::touchesEnded( TouchEvent event )
{
  touches.erase( std::remove_if( touches.begin(), touches.end(), [&event] (const TouchInfo &s) {
    for( auto &t : event.getTouches() ) {
      if (t.getId() == s.id) {
        return true;
      }
    }
    return false;
  }), touches.end() );
}

void SelfieSelfieApp::update()
{
	updateCamera();

  if( capture && capture->checkNewFrame() ) {
    gridTexture->update( *capture->getSurface() );

    auto err = gl::getError();
    if( err ) {
      CI_LOG_E( "Texture copy gl error: " << gl::getErrorString(err) );
    }
  }
}

void SelfieSelfieApp::updateCamera()
{
	if( touches.size() == 1 )
	{
		const auto forward = ([] {
			auto gravity = MotionManager::getGravityDirection();
			if( abs( gravity.x ) > abs( gravity.y ) ) {
				auto x = copysign( 1.0f, gravity.x );
				return vec3( x, 0, 0 );
			}
			else {
				auto y = copysign( 1.0f, gravity.y );
				return vec3( 0, - y, 0 );
			}
		}());

		auto &touch = touches.front();
		auto delta = vec3( touch.position - touch.previous, 0 );
		touch.previous = touch.position;

		auto amount = length( delta );
		auto dir = dot( normalize(delta), forward );

		if( isfinite( amount ) && isfinite( dir ) ) {
			cameraVelocity += amount * dir;
		}
	}

	auto ray = camera.getViewDirection();
	cameraOffset += ray * cameraVelocity * 0.0025f;
	cameraVelocity *= 0.86f;

	auto l = length(cameraOffset);
	auto maximum = 2.9f;
	if( l > maximum ) {
		cameraOffset *= (maximum / l);
	}
	camera.setEyePoint( cameraOffset );

  if( MotionManager::isDataAvailable() ) {
    auto r = MotionManager::getRotation();
    camera.setOrientation( r );
  }
}

void SelfieSelfieApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );

  {
    gl::enableDepthRead();
    gl::enableDepthWrite();
		gl::ScopedGlslProg prog( gl::getStockShader( gl::ShaderDef().texture(gridTexture->getTexture()->getTarget()) ) );

    gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
    gl::ScopedTextureBind tex1( gridTexture->getBlurredTexture(), 1 );
    gl::ScopedMatrices matrices;
    gl::setMatrices( camera );

		landscape.draw( gridTexture->getCurrentIndex() );

		auto mat = translate( vec3( 0, -4.0f, 0 ) );
		auto dims = vec2(gridTexture->getCellDimensions()) / gridTexture->getGridSize();
		auto offset = vec2(gridTexture->getIndexOffset( gridTexture->getCellDimensions(), gridTexture->getCurrentIndex() )) / gridTexture->getGridSize();
		auto rect = Rectf( -1.0f, -1.0f, 1.0f, 1.0f ).scaled( vec2( 1.333f, 1.0f ) ).scaled( 0.2f );
		auto half_pi = (float) M_PI / 2.0f;
		auto xf1 = translate( vec3( - 4.0f, 0.0f, 0.0f ) ) * rotate( - half_pi, vec3( 1, 0, 0 ) ) * rotate( half_pi, vec3( 0, 1, 0 ) );
		auto xf2 = translate( vec3( 4.0f, 0.0f, 0.0f ) ) * rotate( half_pi, vec3( 1, 0, 0 ) ) * rotate( - half_pi, vec3( 0, 1, 0 ) );

		if( false )
		{
			gl::ScopedModelMatrix m;
			gl::multModelMatrix( xf1 );
			gl::drawSolidRect( rect, offset, offset + dims );
		}

		{
			gl::ScopedModelMatrix m;
			gl::multModelMatrix( xf2 );
			gl::drawSolidRect( rect, offset, offset + dims );
		}

  }

  gl::disableDepthRead();

  if( drawDebug && gridTexture )
  {
    gl::setMatricesWindow( getWindowSize() );

    auto rect = Rectf(gridTexture->getTexture()->getBounds());
    auto window_rect = Rectf(getWindowBounds());
    auto window_rect_a = window_rect.scaled( vec2( 0.5f ) );
    auto window_rect_b = window_rect_a + vec2( window_rect_a.getWidth(), 0 );
    gl::draw( gridTexture->getTexture(), rect.getCenteredFit( window_rect_a, false ) );
    gl::draw( gridTexture->getBlurredTexture(), rect.getCenteredFit( window_rect_b, false ) );
  }

  /*
  // For confirming version changes, draw a different colored dot.
  gl::ScopedColor color( Color( 1.0f, 0.0f, 1.0f ) );
  gl::drawSolidCircle( vec2( 20.0f ), 10.0f );
  */

  auto err = gl::getError();
  if( err ) {
    CI_LOG_E( "Draw gl error: " << gl::getErrorString(err) );
  }
}

inline void prepareSettings( app::App::Settings *iSettings )
{
  iSettings->setMultiTouchEnabled();
}

CINDER_APP( SelfieSelfieApp, RendererGl, &prepareSettings )
<|endoftext|>


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

#include "sync/impl/sync_metadata.hpp"

#include "object_schema.hpp"
#include "object_store.hpp"
#include "property.hpp"
#include "results.hpp"
#include "schema.hpp"
#if REALM_PLATFORM_APPLE
#include "impl/apple/keychain_helper.hpp"
#endif

#include <realm/descriptor.hpp>
#include <realm/table.hpp>

namespace realm {

static const char * const c_sync_userMetadata = "UserMetadata";
static const char * const c_sync_marked_for_removal = "marked_for_removal";
static const char * const c_sync_identity = "identity";
static const char * const c_sync_auth_server_url = "auth_server_url";
static const char * const c_sync_user_token = "user_token";
static const char * const c_sync_user_is_admin = "user_is_admin";

static const char * const c_sync_fileActionMetadata = "FileActionMetadata";
static const char * const c_sync_original_name = "original_name";
static const char * const c_sync_new_name = "new_name";
static const char * const c_sync_action = "action";
static const char * const c_sync_url = "url";

namespace {

Property make_nullable_string_property(const char* name)
{
    Property p = {name, PropertyType::String};
    p.is_nullable = true;
    return p;
}

Property make_primary_key_property(const char* name)
{
    Property p = {name, PropertyType::String};
    p.is_indexed = true;
    p.is_primary = true;
    return p;
}

Schema make_schema()
{
    return Schema{
        {c_sync_userMetadata, {
            make_primary_key_property(c_sync_identity),
            {c_sync_marked_for_removal, PropertyType::Bool},
            make_nullable_string_property(c_sync_auth_server_url),
            make_nullable_string_property(c_sync_user_token),
            {c_sync_user_is_admin, PropertyType::Bool},
        }},
        {c_sync_fileActionMetadata, {
            make_primary_key_property(c_sync_original_name),
            {c_sync_action, PropertyType::Int},
            make_nullable_string_property(c_sync_new_name),
            {c_sync_url, PropertyType::String},
            {c_sync_identity, PropertyType::String},
        }},
    };
}

}

#pragma mark - Sync metadata manager

SyncMetadataManager::SyncMetadataManager(std::string path,
                                         bool should_encrypt,
                                         util::Optional<std::vector<char>> encryption_key)
{
    constexpr uint64_t SCHEMA_VERSION = 1;
    std::lock_guard<std::mutex> lock(m_metadata_lock);

    Realm::Config config;
    config.path = std::move(path);
    config.schema = make_schema();
    config.schema_version = SCHEMA_VERSION;
    config.schema_mode = SchemaMode::Automatic;
#if REALM_PLATFORM_APPLE
    if (should_encrypt && !encryption_key) {
        encryption_key = keychain::metadata_realm_encryption_key();
    }
#endif
    if (should_encrypt) {
        if (!encryption_key) {
            throw std::invalid_argument("Metadata Realm encryption was specified, but no encryption key was provided.");
        }
        config.encryption_key = std::move(*encryption_key);
    }

    // Open the Realm.
    SharedRealm realm = Realm::get_shared_realm(config);

    // Get data about the (hardcoded) schemas.
    DescriptorRef descriptor = ObjectStore::table_for_object_type(realm->read_group(),
                                                                  c_sync_userMetadata)->get_descriptor();
    m_user_schema = {
        descriptor->get_column_index(c_sync_identity),
        descriptor->get_column_index(c_sync_marked_for_removal),
        descriptor->get_column_index(c_sync_user_token),
        descriptor->get_column_index(c_sync_auth_server_url),
        descriptor->get_column_index(c_sync_user_is_admin),
    };

    descriptor = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata)->get_descriptor();
    m_file_action_schema = {
        descriptor->get_column_index(c_sync_original_name),
        descriptor->get_column_index(c_sync_new_name),
        descriptor->get_column_index(c_sync_action),
        descriptor->get_column_index(c_sync_url),
        descriptor->get_column_index(c_sync_identity)
    };

    m_metadata_config = std::move(config);
}

Realm::Config SyncMetadataManager::get_configuration() const
{
    std::lock_guard<std::mutex> lock(m_metadata_lock);
    return m_metadata_config;
}

SyncUserMetadataResults SyncMetadataManager::all_unmarked_users() const
{
    return get_users(false);
}

SyncUserMetadataResults SyncMetadataManager::all_users_marked_for_removal() const
{
    return get_users(true);
}

SyncUserMetadataResults SyncMetadataManager::get_users(bool marked) const
{
    // Open the Realm.
    SharedRealm realm = Realm::get_shared_realm(get_configuration());

    TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata);
    Query query = table->where().equal(m_user_schema.idx_marked_for_removal, marked);

    Results results(realm, std::move(query));
    return SyncUserMetadataResults(std::move(results), std::move(realm), m_user_schema);
}

SyncFileActionMetadataResults SyncMetadataManager::all_pending_actions() const
{
    SharedRealm realm = Realm::get_shared_realm(get_configuration());
    TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata);
    Results results(realm, table->where());
    return SyncFileActionMetadataResults(std::move(results), std::move(realm), m_file_action_schema);
}

#pragma mark - Sync user metadata

SyncUserMetadata::SyncUserMetadata(Schema schema, SharedRealm realm, RowExpr row)
: m_invalid(row.get_bool(schema.idx_marked_for_removal))
, m_schema(std::move(schema))
, m_realm(std::move(realm))
, m_row(row)
{ }

SyncUserMetadata::SyncUserMetadata(const SyncMetadataManager& manager, std::string identity, bool make_if_absent)
: m_schema(manager.m_user_schema)
{
    // Open the Realm.
    m_realm = Realm::get_shared_realm(manager.get_configuration());

    // Retrieve or create the row for this object.
    TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata);
    size_t row_idx = table->find_first_string(m_schema.idx_identity, identity);
    if (row_idx == not_found) {
        if (!make_if_absent) {
            m_invalid = true;
            m_realm = nullptr;
            return;
        }
        m_realm->begin_transaction();
        row_idx = table->find_first_string(m_schema.idx_identity, identity);
        if (row_idx == not_found) {
            row_idx = table->add_empty_row();
            table->set_string(m_schema.idx_identity, row_idx, identity);
            table->set_bool(m_schema.idx_user_is_admin, row_idx, false);
            m_realm->commit_transaction();
        } else {
            // Someone beat us to adding this user.
            m_realm->cancel_transaction();
        }
    }
    m_row = table->get(row_idx);
    if (make_if_absent) {
        // User existed in the table, but had been marked for deletion. Unmark it.
        m_realm->begin_transaction();
        table->set_bool(m_schema.idx_marked_for_removal, row_idx, false);
        m_realm->commit_transaction();
        m_invalid = false;
    } else {
        m_invalid = m_row.get_bool(m_schema.idx_marked_for_removal);
    }
}

bool SyncUserMetadata::is_valid() const
{
    return !m_invalid;
}

std::string SyncUserMetadata::identity() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    StringData result = m_row.get_string(m_schema.idx_identity);
    return result;
}

bool SyncUserMetadata::is_admin() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return m_row.get_bool(m_schema.idx_user_is_admin);
}

util::Optional<std::string> SyncUserMetadata::get_optional_string_field(size_t col_idx) const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    StringData result = m_row.get_string(col_idx);
    return result.is_null() ? util::none : util::make_optional(std::string(result));
}

util::Optional<std::string> SyncUserMetadata::server_url() const
{
    return get_optional_string_field(m_schema.idx_auth_server_url);
}

util::Optional<std::string> SyncUserMetadata::user_token() const
{
    return get_optional_string_field(m_schema.idx_user_token);
}

void SyncUserMetadata::set_state(util::Optional<std::string> server_url, util::Optional<std::string> user_token)
{
    if (m_invalid) {
        return;
    }
    REALM_ASSERT_DEBUG(m_realm);
    m_realm->verify_thread();
    m_realm->begin_transaction();
    m_row.set_string(m_schema.idx_user_token, *user_token);
    m_row.set_string(m_schema.idx_auth_server_url, *server_url);
    m_realm->commit_transaction();
}

void SyncUserMetadata::set_is_admin(bool is_admin)
{
    if (m_invalid) {
        return;
    }
    REALM_ASSERT_DEBUG(m_realm);
    m_realm->verify_thread();
    m_realm->begin_transaction();
    m_row.set_bool(m_schema.idx_user_is_admin, is_admin);
    m_realm->commit_transaction();
}

void SyncUserMetadata::mark_for_removal()
{
    if (m_invalid) {
        return;
    }
    m_realm->verify_thread();
    m_realm->begin_transaction();
    m_row.set_bool(m_schema.idx_marked_for_removal, true);
    m_realm->commit_transaction();
}

void SyncUserMetadata::remove()
{
    m_invalid = true;
    m_realm->begin_transaction();
    TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata);
    table->move_last_over(m_row.get_index());
    m_realm->commit_transaction();
    m_realm = nullptr;
}

#pragma mark - File action metadata

util::Optional<SyncFileActionMetadata> SyncFileActionMetadata::metadata_for_path(const std::string& original_name, const SyncMetadataManager& manager)
{
    auto realm = Realm::get_shared_realm(manager.get_configuration());
    auto schema = manager.m_file_action_schema;
    TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata);
    size_t row_idx = table->find_first_string(schema.idx_original_name, original_name);
    if (row_idx == not_found) {
        return none;
    }
    return SyncFileActionMetadata(std::move(schema), std::move(realm), table->get(row_idx));
}

SyncFileActionMetadata::SyncFileActionMetadata(const SyncMetadataManager& manager,
                                               Action action,
                                               const std::string& original_name,
                                               const std::string& url,
                                               const std::string& user_identity,
                                               util::Optional<std::string> new_name)
: m_schema(manager.m_file_action_schema)
{
    size_t raw_action = static_cast<size_t>(action);

    // Open the Realm.
    m_realm = Realm::get_shared_realm(manager.get_configuration());

    // Retrieve or create the row for this object.
    TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_fileActionMetadata);
    m_realm->begin_transaction();
    size_t row_idx = table->find_first_string(m_schema.idx_original_name, original_name);
    if (row_idx == not_found) {
        row_idx = table->add_empty_row();
        table->set_string(m_schema.idx_original_name, row_idx, original_name);
    }
    table->set_string(m_schema.idx_new_name, row_idx, new_name);
    table->set_int(m_schema.idx_action, row_idx, raw_action);
    table->set_string(m_schema.idx_url, row_idx, url);
    table->set_string(m_schema.idx_user_identity, row_idx, user_identity);
    m_realm->commit_transaction();
    m_row = table->get(row_idx);
}

SyncFileActionMetadata::SyncFileActionMetadata(Schema schema, SharedRealm realm, RowExpr row)
: m_schema(std::move(schema))
, m_realm(std::move(realm))
, m_row(row)
{ }

std::string SyncFileActionMetadata::original_name() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return m_row.get_string(m_schema.idx_original_name);
}

util::Optional<std::string> SyncFileActionMetadata::new_name() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    StringData result = m_row.get_string(m_schema.idx_new_name);
    return result.is_null() ? util::none : util::make_optional(std::string(result));
}

SyncFileActionMetadata::Action SyncFileActionMetadata::action() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return static_cast<SyncFileActionMetadata::Action>(m_row.get_int(m_schema.idx_action));
}

std::string SyncFileActionMetadata::url() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return m_row.get_string(m_schema.idx_url);
}

std::string SyncFileActionMetadata::user_identity() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return m_row.get_string(m_schema.idx_user_identity);
}

void SyncFileActionMetadata::remove()
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    m_realm->begin_transaction();
    TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_fileActionMetadata);
    table->move_last_over(m_row.get_index());
    m_realm->commit_transaction();
    m_realm = nullptr;
}

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

#include "sync/impl/sync_metadata.hpp"

#include "object_schema.hpp"
#include "object_store.hpp"
#include "property.hpp"
#include "results.hpp"
#include "schema.hpp"
#if REALM_PLATFORM_APPLE
#include "impl/apple/keychain_helper.hpp"
#endif

#include <realm/descriptor.hpp>
#include <realm/table.hpp>

namespace realm {

static const char * const c_sync_userMetadata = "UserMetadata";
static const char * const c_sync_marked_for_removal = "marked_for_removal";
static const char * const c_sync_identity = "identity";
static const char * const c_sync_auth_server_url = "auth_server_url";
static const char * const c_sync_user_token = "user_token";
static const char * const c_sync_user_is_admin = "user_is_admin";

static const char * const c_sync_fileActionMetadata = "FileActionMetadata";
static const char * const c_sync_original_name = "original_name";
static const char * const c_sync_new_name = "new_name";
static const char * const c_sync_action = "action";
static const char * const c_sync_url = "url";

namespace {

Property make_nullable_string_property(const char* name)
{
    Property p = {name, PropertyType::String};
    p.is_nullable = true;
    return p;
}

Property make_primary_key_property(const char* name)
{
    Property p = {name, PropertyType::String};
    p.is_indexed = true;
    p.is_primary = true;
    return p;
}

Schema make_schema()
{
    return Schema{
        {c_sync_userMetadata, {
            make_primary_key_property(c_sync_identity),
            {c_sync_marked_for_removal, PropertyType::Bool},
            make_nullable_string_property(c_sync_auth_server_url),
            make_nullable_string_property(c_sync_user_token),
            {c_sync_user_is_admin, PropertyType::Bool},
        }},
        {c_sync_fileActionMetadata, {
            make_primary_key_property(c_sync_original_name),
            {c_sync_action, PropertyType::Int},
            make_nullable_string_property(c_sync_new_name),
            {c_sync_url, PropertyType::String},
            {c_sync_identity, PropertyType::String},
        }},
    };
}

}

// MARK: - Sync metadata manager

SyncMetadataManager::SyncMetadataManager(std::string path,
                                         bool should_encrypt,
                                         util::Optional<std::vector<char>> encryption_key)
{
    constexpr uint64_t SCHEMA_VERSION = 1;
    std::lock_guard<std::mutex> lock(m_metadata_lock);

    Realm::Config config;
    config.path = std::move(path);
    config.schema = make_schema();
    config.schema_version = SCHEMA_VERSION;
    config.schema_mode = SchemaMode::Automatic;
#if REALM_PLATFORM_APPLE
    if (should_encrypt && !encryption_key) {
        encryption_key = keychain::metadata_realm_encryption_key();
    }
#endif
    if (should_encrypt) {
        if (!encryption_key) {
            throw std::invalid_argument("Metadata Realm encryption was specified, but no encryption key was provided.");
        }
        config.encryption_key = std::move(*encryption_key);
    }

    // Open the Realm.
    SharedRealm realm = Realm::get_shared_realm(config);

    // Get data about the (hardcoded) schemas.
    DescriptorRef descriptor = ObjectStore::table_for_object_type(realm->read_group(),
                                                                  c_sync_userMetadata)->get_descriptor();
    m_user_schema = {
        descriptor->get_column_index(c_sync_identity),
        descriptor->get_column_index(c_sync_marked_for_removal),
        descriptor->get_column_index(c_sync_user_token),
        descriptor->get_column_index(c_sync_auth_server_url),
        descriptor->get_column_index(c_sync_user_is_admin),
    };

    descriptor = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata)->get_descriptor();
    m_file_action_schema = {
        descriptor->get_column_index(c_sync_original_name),
        descriptor->get_column_index(c_sync_new_name),
        descriptor->get_column_index(c_sync_action),
        descriptor->get_column_index(c_sync_url),
        descriptor->get_column_index(c_sync_identity)
    };

    m_metadata_config = std::move(config);
}

Realm::Config SyncMetadataManager::get_configuration() const
{
    std::lock_guard<std::mutex> lock(m_metadata_lock);
    return m_metadata_config;
}

SyncUserMetadataResults SyncMetadataManager::all_unmarked_users() const
{
    return get_users(false);
}

SyncUserMetadataResults SyncMetadataManager::all_users_marked_for_removal() const
{
    return get_users(true);
}

SyncUserMetadataResults SyncMetadataManager::get_users(bool marked) const
{
    // Open the Realm.
    SharedRealm realm = Realm::get_shared_realm(get_configuration());

    TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata);
    Query query = table->where().equal(m_user_schema.idx_marked_for_removal, marked);

    Results results(realm, std::move(query));
    return SyncUserMetadataResults(std::move(results), std::move(realm), m_user_schema);
}

SyncFileActionMetadataResults SyncMetadataManager::all_pending_actions() const
{
    SharedRealm realm = Realm::get_shared_realm(get_configuration());
    TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata);
    Results results(realm, table->where());
    return SyncFileActionMetadataResults(std::move(results), std::move(realm), m_file_action_schema);
}

// MARK: - Sync user metadata

SyncUserMetadata::SyncUserMetadata(Schema schema, SharedRealm realm, RowExpr row)
: m_invalid(row.get_bool(schema.idx_marked_for_removal))
, m_schema(std::move(schema))
, m_realm(std::move(realm))
, m_row(row)
{ }

SyncUserMetadata::SyncUserMetadata(const SyncMetadataManager& manager, std::string identity, bool make_if_absent)
: m_schema(manager.m_user_schema)
{
    // Open the Realm.
    m_realm = Realm::get_shared_realm(manager.get_configuration());

    // Retrieve or create the row for this object.
    TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata);
    size_t row_idx = table->find_first_string(m_schema.idx_identity, identity);
    if (row_idx == not_found) {
        if (!make_if_absent) {
            m_invalid = true;
            m_realm = nullptr;
            return;
        }
        m_realm->begin_transaction();
        row_idx = table->find_first_string(m_schema.idx_identity, identity);
        if (row_idx == not_found) {
            row_idx = table->add_empty_row();
            table->set_string(m_schema.idx_identity, row_idx, identity);
            table->set_bool(m_schema.idx_user_is_admin, row_idx, false);
            m_realm->commit_transaction();
        } else {
            // Someone beat us to adding this user.
            m_realm->cancel_transaction();
        }
    }
    m_row = table->get(row_idx);
    if (make_if_absent) {
        // User existed in the table, but had been marked for deletion. Unmark it.
        m_realm->begin_transaction();
        table->set_bool(m_schema.idx_marked_for_removal, row_idx, false);
        m_realm->commit_transaction();
        m_invalid = false;
    } else {
        m_invalid = m_row.get_bool(m_schema.idx_marked_for_removal);
    }
}

bool SyncUserMetadata::is_valid() const
{
    return !m_invalid;
}

std::string SyncUserMetadata::identity() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    StringData result = m_row.get_string(m_schema.idx_identity);
    return result;
}

bool SyncUserMetadata::is_admin() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return m_row.get_bool(m_schema.idx_user_is_admin);
}

util::Optional<std::string> SyncUserMetadata::get_optional_string_field(size_t col_idx) const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    StringData result = m_row.get_string(col_idx);
    return result.is_null() ? util::none : util::make_optional(std::string(result));
}

util::Optional<std::string> SyncUserMetadata::server_url() const
{
    return get_optional_string_field(m_schema.idx_auth_server_url);
}

util::Optional<std::string> SyncUserMetadata::user_token() const
{
    return get_optional_string_field(m_schema.idx_user_token);
}

void SyncUserMetadata::set_state(util::Optional<std::string> server_url, util::Optional<std::string> user_token)
{
    if (m_invalid) {
        return;
    }
    REALM_ASSERT_DEBUG(m_realm);
    m_realm->verify_thread();
    m_realm->begin_transaction();
    m_row.set_string(m_schema.idx_user_token, *user_token);
    m_row.set_string(m_schema.idx_auth_server_url, *server_url);
    m_realm->commit_transaction();
}

void SyncUserMetadata::set_is_admin(bool is_admin)
{
    if (m_invalid) {
        return;
    }
    REALM_ASSERT_DEBUG(m_realm);
    m_realm->verify_thread();
    m_realm->begin_transaction();
    m_row.set_bool(m_schema.idx_user_is_admin, is_admin);
    m_realm->commit_transaction();
}

void SyncUserMetadata::mark_for_removal()
{
    if (m_invalid) {
        return;
    }
    m_realm->verify_thread();
    m_realm->begin_transaction();
    m_row.set_bool(m_schema.idx_marked_for_removal, true);
    m_realm->commit_transaction();
}

void SyncUserMetadata::remove()
{
    m_invalid = true;
    m_realm->begin_transaction();
    TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata);
    table->move_last_over(m_row.get_index());
    m_realm->commit_transaction();
    m_realm = nullptr;
}

// MARK: - File action metadata

util::Optional<SyncFileActionMetadata> SyncFileActionMetadata::metadata_for_path(const std::string& original_name, const SyncMetadataManager& manager)
{
    auto realm = Realm::get_shared_realm(manager.get_configuration());
    auto schema = manager.m_file_action_schema;
    TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata);
    size_t row_idx = table->find_first_string(schema.idx_original_name, original_name);
    if (row_idx == not_found) {
        return none;
    }
    return SyncFileActionMetadata(std::move(schema), std::move(realm), table->get(row_idx));
}

SyncFileActionMetadata::SyncFileActionMetadata(const SyncMetadataManager& manager,
                                               Action action,
                                               const std::string& original_name,
                                               const std::string& url,
                                               const std::string& user_identity,
                                               util::Optional<std::string> new_name)
: m_schema(manager.m_file_action_schema)
{
    size_t raw_action = static_cast<size_t>(action);

    // Open the Realm.
    m_realm = Realm::get_shared_realm(manager.get_configuration());

    // Retrieve or create the row for this object.
    TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_fileActionMetadata);
    m_realm->begin_transaction();
    size_t row_idx = table->find_first_string(m_schema.idx_original_name, original_name);
    if (row_idx == not_found) {
        row_idx = table->add_empty_row();
        table->set_string(m_schema.idx_original_name, row_idx, original_name);
    }
    table->set_string(m_schema.idx_new_name, row_idx, new_name);
    table->set_int(m_schema.idx_action, row_idx, raw_action);
    table->set_string(m_schema.idx_url, row_idx, url);
    table->set_string(m_schema.idx_user_identity, row_idx, user_identity);
    m_realm->commit_transaction();
    m_row = table->get(row_idx);
}

SyncFileActionMetadata::SyncFileActionMetadata(Schema schema, SharedRealm realm, RowExpr row)
: m_schema(std::move(schema))
, m_realm(std::move(realm))
, m_row(row)
{ }

std::string SyncFileActionMetadata::original_name() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return m_row.get_string(m_schema.idx_original_name);
}

util::Optional<std::string> SyncFileActionMetadata::new_name() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    StringData result = m_row.get_string(m_schema.idx_new_name);
    return result.is_null() ? util::none : util::make_optional(std::string(result));
}

SyncFileActionMetadata::Action SyncFileActionMetadata::action() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return static_cast<SyncFileActionMetadata::Action>(m_row.get_int(m_schema.idx_action));
}

std::string SyncFileActionMetadata::url() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return m_row.get_string(m_schema.idx_url);
}

std::string SyncFileActionMetadata::user_identity() const
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    return m_row.get_string(m_schema.idx_user_identity);
}

void SyncFileActionMetadata::remove()
{
    REALM_ASSERT(m_realm);
    m_realm->verify_thread();
    m_realm->begin_transaction();
    TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_fileActionMetadata);
    table->move_last_over(m_row.get_index());
    m_realm->commit_transaction();
    m_realm = nullptr;
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ximpstyl.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:12:42 $
 *
 *  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 _XIMPSTYLE_HXX
#define _XIMPSTYLE_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _SDXMLIMP_IMPL_HXX
#include "sdxmlimp_impl.hxx"
#endif

#ifndef _XIMPPAGE_HXX
#include "ximppage.hxx"
#endif

#ifndef _XMLOFF_XMLSTYLE_HXX
#include <xmloff/xmlstyle.hxx>
#endif

#ifndef _COM_SUN_STAR_VIEW_PAPERORIENTATION_HPP_
#include <com/sun/star/view/PaperOrientation.hpp>
#endif

class SvNumberFormatter;
class SvXMLNumFmtHelper;

//////////////////////////////////////////////////////////////////////////////
// special style:style context inside style:page-master context

class SdXMLPageMasterStyleContext: public SvXMLStyleContext
{
    sal_Int32                   mnBorderBottom;
    sal_Int32                   mnBorderLeft;
    sal_Int32                   mnBorderRight;
    sal_Int32                   mnBorderTop;
    sal_Int32                   mnWidth;
    sal_Int32                   mnHeight;
    com::sun::star::view::PaperOrientation meOrientation;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    TYPEINFO();

    SdXMLPageMasterStyleContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    virtual ~SdXMLPageMasterStyleContext();

    sal_Int32 GetBorderBottom() const { return mnBorderBottom; }
    sal_Int32 GetBorderLeft() const { return mnBorderLeft; }
    sal_Int32 GetBorderRight() const { return mnBorderRight; }
    sal_Int32 GetBorderTop() const { return mnBorderTop; }
    sal_Int32 GetWidth() const { return mnWidth; }
    sal_Int32 GetHeight() const { return mnHeight; }
    com::sun::star::view::PaperOrientation GetOrientation() const { return meOrientation; }
};

//////////////////////////////////////////////////////////////////////////////
// style:page-master context

class SdXMLPageMasterContext: public SvXMLStyleContext
{
    rtl::OUString               msName;
    SdXMLPageMasterStyleContext*mpPageMasterStyle;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    TYPEINFO();

    SdXMLPageMasterContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    virtual ~SdXMLPageMasterContext();

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList );

    const rtl::OUString& GetName() const { return msName; }
    const SdXMLPageMasterStyleContext* GetPageMasterStyle() const { return mpPageMasterStyle; }
};

//////////////////////////////////////////////////////////////////////////////
// style:masterpage context

class SdXMLMasterPageContext: public SdXMLGenericPageContext
{
    rtl::OUString               msPageMasterName;
    rtl::OUString               msName;
    rtl::OUString               msDisplayName;
    rtl::OUString               msStyleName;

public:
    TYPEINFO();

    SdXMLMasterPageContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList,
        com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);
    virtual ~SdXMLMasterPageContext();

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void EndElement();

    const rtl::OUString& GetPageMasterName() const { return msPageMasterName; }
    const rtl::OUString& GetEncodedName() const { return msName; }
    const rtl::OUString& GetDisplayName() const { return msDisplayName; }

};
DECLARE_LIST(ImpMasterPageList, SdXMLMasterPageContext*)

//////////////////////////////////////////////////////////////////////////////
// presentation:placeholder context

class SdXMLPresentationPlaceholderContext: public SvXMLImportContext
{
    rtl::OUString               msName;
    sal_Int32                   mnX;
    sal_Int32                   mnY;
    sal_Int32                   mnWidth;
    sal_Int32                   mnHeight;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    SdXMLPresentationPlaceholderContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    virtual ~SdXMLPresentationPlaceholderContext();

    const rtl::OUString& GetName() const { return msName; }
    sal_Int32 GetX() const { return mnX; }
    sal_Int32 GetY() const { return mnY; }
    sal_Int32 GetWidth() const { return mnWidth; }
    sal_Int32 GetHeight() const { return mnHeight; }
};
DECLARE_LIST(ImpPlaceholderList, SdXMLPresentationPlaceholderContext*)

//////////////////////////////////////////////////////////////////////////////
// style:presentation-page-layout context

class SdXMLPresentationPageLayoutContext: public SvXMLStyleContext
{
    rtl::OUString               msName;
    ImpPlaceholderList          maList;
    sal_uInt16                  mnTypeId;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    TYPEINFO();

    SdXMLPresentationPageLayoutContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    virtual ~SdXMLPresentationPageLayoutContext();

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void EndElement();
    sal_uInt16 GetTypeId() const { return mnTypeId; }
};

//////////////////////////////////////////////////////////////////////////////
// office:styles context

class SdXMLStylesContext : public SvXMLStylesContext
{
    UniReference< SvXMLImportPropertyMapper > xPresImpPropMapper;
    sal_Bool                    mbIsAutoStyle;
    SvXMLNumFmtHelper*          mpNumFmtHelper;
    SvNumberFormatter*          mpNumFormatter;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

    void ImpSetGraphicStyles() const;
    void ImpSetGraphicStyles( com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xPageStyles,
        sal_uInt16 nFamily, const UniString& rPrefix) const;

protected:
    virtual SvXMLStyleContext* CreateStyleChildContext(
        sal_uInt16 nPrefix,
        const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);

    virtual SvXMLStyleContext *CreateStyleStyleChildContext(
        sal_uInt16 nFamily,
        sal_uInt16 nPrefix,
        const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);

    virtual SvXMLStyleContext *CreateDefaultStyleStyleChildContext(
        sal_uInt16 nFamily, sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
public:
    TYPEINFO();

    SdXMLStylesContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList,
        sal_Bool bIsAutoStyle);
    virtual ~SdXMLStylesContext();

    virtual sal_uInt16 GetFamily( const rtl::OUString& rFamily ) const;
    virtual void EndElement();
    virtual UniReference< SvXMLImportPropertyMapper > GetImportPropertyMapper(sal_uInt16 nFamily) const;

    void SetMasterPageStyles(SdXMLMasterPageContext& rMaster) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > getPageLayouts() const;
};

//////////////////////////////////////////////////////////////////////////////
// office:master-styles context
//
class SdXMLMasterStylesContext : public SvXMLImportContext
{
    ImpMasterPageList           maMasterPageList;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    TYPEINFO();

    SdXMLMasterStylesContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName);
    virtual ~SdXMLMasterStylesContext();

    virtual SvXMLImportContext* CreateChildContext(
        sal_uInt16 nPrefix,
        const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList );

    const ImpMasterPageList& GetMasterPageList() const { return maMasterPageList; }
};

//////////////////////////////////////////////////////////////////////////////
// <pres:header-decl>, <pres:footer-decl> and <pres:date-time-decl>

class SdXMLHeaderFooterDeclContext : public SvXMLStyleContext
{
public:
    SdXMLHeaderFooterDeclContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
        const ::rtl::OUString& rLName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual BOOL IsTransient() const;
    virtual void EndElement();
    virtual void Characters( const ::rtl::OUString& rChars );

private:
    ::rtl::OUString maStrName;
    ::rtl::OUString maStrText;
    ::rtl::OUString maStrDateTimeFormat;
    sal_Bool        mbFixed;
};

#endif  //  _XIMPSTYLE_HXX
<commit_msg>INTEGRATION: CWS impresstables2 (1.12.112); FILE MERGED 2007/08/01 14:16:08 cl 1.12.112.2: RESYNC: (1.12-1.13); FILE MERGED 2007/07/26 17:10:57 cl 1.12.112.1: #i68103# working on tables in draw<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ximpstyl.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 10:39:52 $
 *
 *  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 _XIMPSTYLE_HXX
#define _XIMPSTYLE_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _SDXMLIMP_IMPL_HXX
#include "sdxmlimp_impl.hxx"
#endif

#ifndef _XIMPPAGE_HXX
#include "ximppage.hxx"
#endif

#ifndef _XMLOFF_XMLSTYLE_HXX
#include <xmloff/xmlstyle.hxx>
#endif

#ifndef _COM_SUN_STAR_VIEW_PAPERORIENTATION_HPP_
#include <com/sun/star/view/PaperOrientation.hpp>
#endif

class SvNumberFormatter;
class SvXMLNumFmtHelper;

//////////////////////////////////////////////////////////////////////////////
// special style:style context inside style:page-master context

class SdXMLPageMasterStyleContext: public SvXMLStyleContext
{
    sal_Int32                   mnBorderBottom;
    sal_Int32                   mnBorderLeft;
    sal_Int32                   mnBorderRight;
    sal_Int32                   mnBorderTop;
    sal_Int32                   mnWidth;
    sal_Int32                   mnHeight;
    com::sun::star::view::PaperOrientation meOrientation;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    TYPEINFO();

    SdXMLPageMasterStyleContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    virtual ~SdXMLPageMasterStyleContext();

    sal_Int32 GetBorderBottom() const { return mnBorderBottom; }
    sal_Int32 GetBorderLeft() const { return mnBorderLeft; }
    sal_Int32 GetBorderRight() const { return mnBorderRight; }
    sal_Int32 GetBorderTop() const { return mnBorderTop; }
    sal_Int32 GetWidth() const { return mnWidth; }
    sal_Int32 GetHeight() const { return mnHeight; }
    com::sun::star::view::PaperOrientation GetOrientation() const { return meOrientation; }
};

//////////////////////////////////////////////////////////////////////////////
// style:page-master context

class SdXMLPageMasterContext: public SvXMLStyleContext
{
    rtl::OUString               msName;
    SdXMLPageMasterStyleContext*mpPageMasterStyle;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    TYPEINFO();

    SdXMLPageMasterContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    virtual ~SdXMLPageMasterContext();

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList );

    const rtl::OUString& GetName() const { return msName; }
    const SdXMLPageMasterStyleContext* GetPageMasterStyle() const { return mpPageMasterStyle; }
};

//////////////////////////////////////////////////////////////////////////////
// style:masterpage context

class SdXMLMasterPageContext: public SdXMLGenericPageContext
{
    rtl::OUString               msPageMasterName;
    rtl::OUString               msName;
    rtl::OUString               msDisplayName;
    rtl::OUString               msStyleName;

public:
    TYPEINFO();

    SdXMLMasterPageContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList,
        com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);
    virtual ~SdXMLMasterPageContext();

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void EndElement();

    const rtl::OUString& GetPageMasterName() const { return msPageMasterName; }
    const rtl::OUString& GetEncodedName() const { return msName; }
    const rtl::OUString& GetDisplayName() const { return msDisplayName; }

};
DECLARE_LIST(ImpMasterPageList, SdXMLMasterPageContext*)

//////////////////////////////////////////////////////////////////////////////
// presentation:placeholder context

class SdXMLPresentationPlaceholderContext: public SvXMLImportContext
{
    rtl::OUString               msName;
    sal_Int32                   mnX;
    sal_Int32                   mnY;
    sal_Int32                   mnWidth;
    sal_Int32                   mnHeight;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    SdXMLPresentationPlaceholderContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    virtual ~SdXMLPresentationPlaceholderContext();

    const rtl::OUString& GetName() const { return msName; }
    sal_Int32 GetX() const { return mnX; }
    sal_Int32 GetY() const { return mnY; }
    sal_Int32 GetWidth() const { return mnWidth; }
    sal_Int32 GetHeight() const { return mnHeight; }
};
DECLARE_LIST(ImpPlaceholderList, SdXMLPresentationPlaceholderContext*)

//////////////////////////////////////////////////////////////////////////////
// style:presentation-page-layout context

class SdXMLPresentationPageLayoutContext: public SvXMLStyleContext
{
    rtl::OUString               msName;
    ImpPlaceholderList          maList;
    sal_uInt16                  mnTypeId;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    TYPEINFO();

    SdXMLPresentationPageLayoutContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    virtual ~SdXMLPresentationPageLayoutContext();

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix, const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void EndElement();
    sal_uInt16 GetTypeId() const { return mnTypeId; }
};

//////////////////////////////////////////////////////////////////////////////
// office:styles context

class SdXMLStylesContext : public SvXMLStylesContext
{
    UniReference< SvXMLImportPropertyMapper > xPresImpPropMapper;
    sal_Bool                    mbIsAutoStyle;
    SvXMLNumFmtHelper*          mpNumFmtHelper;
    SvNumberFormatter*          mpNumFormatter;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

    void ImpSetGraphicStyles() const;
    void ImpSetCellStyles() const;
    void ImpSetGraphicStyles( com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xPageStyles,
        sal_uInt16 nFamily, const UniString& rPrefix) const;

protected:
    virtual SvXMLStyleContext* CreateStyleChildContext(
        sal_uInt16 nPrefix,
        const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);

    virtual SvXMLStyleContext *CreateStyleStyleChildContext(
        sal_uInt16 nFamily,
        sal_uInt16 nPrefix,
        const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);

    virtual SvXMLStyleContext *CreateDefaultStyleStyleChildContext(
        sal_uInt16 nFamily, sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
public:
    TYPEINFO();

    SdXMLStylesContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList,
        sal_Bool bIsAutoStyle);
    virtual ~SdXMLStylesContext();

    virtual sal_uInt16 GetFamily( const rtl::OUString& rFamily ) const;
    virtual void EndElement();
    virtual UniReference< SvXMLImportPropertyMapper > GetImportPropertyMapper(sal_uInt16 nFamily) const;

    void SetMasterPageStyles(SdXMLMasterPageContext& rMaster) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > getPageLayouts() const;
};

//////////////////////////////////////////////////////////////////////////////
// office:master-styles context
//
class SdXMLMasterStylesContext : public SvXMLImportContext
{
    ImpMasterPageList           maMasterPageList;

    const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
    SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }

public:
    TYPEINFO();

    SdXMLMasterStylesContext(
        SdXMLImport& rImport,
        sal_uInt16 nPrfx,
        const rtl::OUString& rLName);
    virtual ~SdXMLMasterStylesContext();

    virtual SvXMLImportContext* CreateChildContext(
        sal_uInt16 nPrefix,
        const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList );

    const ImpMasterPageList& GetMasterPageList() const { return maMasterPageList; }
};

//////////////////////////////////////////////////////////////////////////////
// <pres:header-decl>, <pres:footer-decl> and <pres:date-time-decl>

class SdXMLHeaderFooterDeclContext : public SvXMLStyleContext
{
public:
    SdXMLHeaderFooterDeclContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
        const ::rtl::OUString& rLName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual BOOL IsTransient() const;
    virtual void EndElement();
    virtual void Characters( const ::rtl::OUString& rChars );

private:
    ::rtl::OUString maStrName;
    ::rtl::OUString maStrText;
    ::rtl::OUString maStrDateTimeFormat;
    sal_Bool        mbFixed;
};

#endif  //  _XIMPSTYLE_HXX
<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_BASEFUNCTIONSET_FEM_LOCALFUNCTIONS_HH
#define DUNE_DETAILED_DISCRETIZATIONS_BASEFUNCTIONSET_FEM_LOCALFUNCTIONS_HH

#include <vector>

#include "interface.hh"

namespace Dune {
namespace Detailed {
namespace Discretizations {

// forward, to be used in the traits and to allow for specialization
template< class BaseFunctionSetMapImp >
class BaseFunctionSetFemLocalfunctionsWrapper;

template< class BaseFunctionSetMapImp >
class BaseFunctionSetFemLocalfunctionsWrapperTraits
{
public:
  typedef BaseFunctionSetFemLocalfunctionsWrapper< BaseFunctionSetMapImp >  derived_type;
  typedef typename BaseFunctionSetMapImp::BaseFunctionSetType               BackendType;
  typedef typename BackendType::EntityType        EntityType;
  typedef typename BackendType::DomainFieldType   DomainFieldType;
  static const unsigned int                       dimDomain = BackendType::dimDomain;
  typedef typename BackendType::DomainType        DomainType;
  typedef typename BackendType::RangeFieldType    RangeFieldType;
  static const unsigned int                       dimRange = BackendType::dimRange;
  typedef typename BackendType::RangeType         RangeType;
  typedef typename BackendType::JacobianRangeType JacobianRangeType;
};

template< class BaseFunctionSetMapImp >
class BaseFunctionSetFemLocalfunctionsWrapper
  : public BaseFunctionSetInterface< BaseFunctionSetFemLocalfunctionsWrapperTraits< BaseFunctionSetMapImp > >
{
public:
  typedef BaseFunctionSetFemLocalfunctionsWrapperTraits< BaseFunctionSetMapImp > Traits;
  typedef typename Traits::BackendType  BackendType;
  typedef typename Traits::EntityType   EntityType;
  typedef typename Traits::DomainFieldType  DomainFieldType;
  static const unsigned int                 dimDomain = Traits::dimDomain;
  typedef typename Traits::DomainType       DomainType;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRange = Traits::dimRange;
  typedef typename Traits::RangeType      RangeType;
  typedef typename Traits::JacobianRangeType  JacobianRangeType;

  BaseFunctionSetFemLocalfunctionsWrapper(const BaseFunctionSetMapImp& baseFunctionSetMap, const EntityType& en)
    : baseFunctionSetMap_(baseFunctionSetMap)
    , entity_(en)
    , backend_(baseFunctionSetMap_.find(entity_))
  {}

  const EntityType& entity() const
  {
    return entity_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return backend_.size();
  }

  size_t order() const
  {
    return baseFunctionSetMap_.getOrder(entity_);
  }

  void evaluate(const DomainType& x, std::vector< RangeType >& ret) const
  {
    backend_.evaluateAll(x, ret);
  }

  void jacobian(const DomainType& x, std::vector< JacobianRangeType >& ret) const
  {
    backend_.jacobianAll(x, entity_.geometry().jacobianInverseTransposed(x), ret);
  }

private:
  const BaseFunctionSetMapImp& baseFunctionSetMap_;
  const EntityType& entity_;
  const BackendType backend_;
}; // class BaseFunctionSetFemLocalfunctionsWrapper

} // namespace Discretizations
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_BASEFUNCTIONSET_FEM_LOCALFUNCTIONS_HH
<commit_msg>[basefunctionsetfemlocalfunctionswrapper] -> [basefunctionset.femlocalfunctionswrapper]<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_BASEFUNCTIONSET_FEM_LOCALFUNCTIONS_HH
#define DUNE_DETAILED_DISCRETIZATIONS_BASEFUNCTIONSET_FEM_LOCALFUNCTIONS_HH

#include <vector>

#include "interface.hh"

namespace Dune {
namespace Detailed {
namespace Discretizations {
namespace BaseFunctionSet {

// forward, to be used in the traits and to allow for specialization
template< class BaseFunctionSetMapImp >
class FemLocalfunctionsWrapper;

template< class BaseFunctionSetMapImp >
class FemLocalfunctionsWrapperTraits
{
public:
  typedef FemLocalfunctionsWrapper< BaseFunctionSetMapImp >  derived_type;
  typedef typename BaseFunctionSetMapImp::BaseFunctionSetType               BackendType;
  typedef typename BackendType::EntityType        EntityType;
  typedef typename BackendType::DomainFieldType   DomainFieldType;
  static const unsigned int                       dimDomain = BackendType::dimDomain;
  typedef typename BackendType::DomainType        DomainType;
  typedef typename BackendType::RangeFieldType    RangeFieldType;
  static const unsigned int                       dimRange = BackendType::dimRange;
  typedef typename BackendType::RangeType         RangeType;
  typedef typename BackendType::JacobianRangeType JacobianRangeType;
};

template< class BaseFunctionSetMapImp >
class FemLocalfunctionsWrapper
  : public BaseFunctionSetInterface< FemLocalfunctionsWrapperTraits< BaseFunctionSetMapImp > >
{
public:
  typedef FemLocalfunctionsWrapperTraits< BaseFunctionSetMapImp > Traits;
  typedef typename Traits::BackendType  BackendType;
  typedef typename Traits::EntityType   EntityType;
  typedef typename Traits::DomainFieldType  DomainFieldType;
  static const unsigned int                 dimDomain = Traits::dimDomain;
  typedef typename Traits::DomainType       DomainType;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRange = Traits::dimRange;
  typedef typename Traits::RangeType      RangeType;
  typedef typename Traits::JacobianRangeType  JacobianRangeType;

  FemLocalfunctionsWrapper(const BaseFunctionSetMapImp& baseFunctionSetMap, const EntityType& en)
    : baseFunctionSetMap_(baseFunctionSetMap)
    , entity_(en)
    , backend_(baseFunctionSetMap_.find(entity_))
  {}

  const EntityType& entity() const
  {
    return entity_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return backend_.size();
  }

  size_t order() const
  {
    return baseFunctionSetMap_.getOrder(entity_);
  }

  void evaluate(const DomainType& x, std::vector< RangeType >& ret) const
  {
    assert(ret.size() >= backend_.size());
    backend_.evaluateAll(x, ret);
  }

  void jacobian(const DomainType& x, std::vector< JacobianRangeType >& ret) const
  {
    assert(ret.size() >= backend_.size());
    backend_.jacobianAll(x, entity_.geometry().jacobianInverseTransposed(x), ret);
  }

private:
  const BaseFunctionSetMapImp& baseFunctionSetMap_;
  const EntityType& entity_;
  const BackendType backend_;
}; // class FemLocalfunctionsWrapper

} // namespace BaseFunctionSet
} // namespace Discretizations
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_BASEFUNCTIONSET_FEM_LOCALFUNCTIONS_HH
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: txtparai.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2007-07-31 17:36:04 $
 *
 *  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 _XMLOFF_TEXTPARAI_HXX_
#define _XMLOFF_TEXTPARAI_HXX_

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

class XMLHints_Impl;
namespace com { namespace sun { namespace star {
namespace text {  class XTextRange; }
namespace xml { namespace sax { class XAttributeList; } }
} } }

#define CONV_FROM_STAR_BATS 1
#define CONV_FROM_STAR_MATH 2
#define CONV_STAR_FONT_FLAGS_VALID 4

class XMLParaContext : public SvXMLImportContext
{
    ::com::sun::star::uno::Reference <
        ::com::sun::star::text::XTextRange > xStart;    // xub_StrLen nStart;
    ::rtl::OUString             sStyleName;
    ::rtl::OUString             sId;
    sal_Int8                nOutlineLevel;
    XMLHints_Impl           *pHints;
    // --> OD 2007-07-25 #i73509#
    sal_Bool                mbOutlineLevelAttrFound;
    // <--
    sal_Bool                bIgnoreLeadingSpace;
    sal_Bool                bHeading;
    sal_Bool                bIsListHeader;
    sal_Bool                bIsRestart;
    sal_Int16               nStartValue;
    sal_uInt8               nStarFontsConvFlags;

public:

    TYPEINFO();

    XMLParaContext( SvXMLImport& rImport,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            sal_Bool bHeading );

    virtual ~XMLParaContext();

    virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
            const ::rtl::OUString& rLocalName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    virtual void Characters( const ::rtl::OUString& rChars );

};

class XMLNumberedParaContext : public SvXMLImportContext
{
public:

    TYPEINFO();

    XMLNumberedParaContext( SvXMLImport& rImport,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName );

    virtual ~XMLNumberedParaContext();

    virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
            const ::rtl::OUString& rLocalName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    virtual void Characters( const ::rtl::OUString& rChars );

};

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

#include <com/sun/star/uno/Reference.h>
#include <xmloff/xmlictxt.hxx>

class XMLHints_Impl;
namespace com { namespace sun { namespace star {
namespace text {  class XTextRange; }
namespace xml { namespace sax { class XAttributeList; } }
} } }

#define CONV_FROM_STAR_BATS 1
#define CONV_FROM_STAR_MATH 2
#define CONV_STAR_FONT_FLAGS_VALID 4

class XMLParaContext : public SvXMLImportContext
{
    ::com::sun::star::uno::Reference <
        ::com::sun::star::text::XTextRange > xStart;    // xub_StrLen nStart;
    ::rtl::OUString             sStyleName;
    ::rtl::OUString             sId;
    sal_Int8                nOutlineLevel;
    XMLHints_Impl           *pHints;
    // --> OD 2007-07-25 #i73509#
    sal_Bool                mbOutlineLevelAttrFound;
    // <--
    sal_Bool                bIgnoreLeadingSpace;
    sal_Bool                bHeading;
    sal_Bool                bIsListHeader;
    sal_Bool                bIsRestart;
    sal_Int16               nStartValue;
    sal_uInt8               nStarFontsConvFlags;

public:

    TYPEINFO();

    XMLParaContext( SvXMLImport& rImport,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            sal_Bool bHeading );

    virtual ~XMLParaContext();

    virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
            const ::rtl::OUString& rLocalName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    virtual void Characters( const ::rtl::OUString& rChars );

};

class XMLNumberedParaContext : public SvXMLImportContext
{
public:

    TYPEINFO();

    XMLNumberedParaContext( SvXMLImport& rImport,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName );

    virtual ~XMLNumberedParaContext();

    virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
            const ::rtl::OUString& rLocalName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    virtual void Characters( const ::rtl::OUString& rChars );

};

#endif
<|endoftext|>


<commit_before>/*
 * 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.
 *
 * Written (W) 2011 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/base/init.h>
#include <shogun/features/SparseFeatures.h>
#include <shogun/features/Subset.h>

using namespace shogun;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

const int32_t num_vectors=6;
const int32_t dim_features=6;

void check_transposed(CSparseFeatures<int32_t>* features)
{
	CSparseFeatures<int32_t>* transposed=features->get_transposed();
	CSparseFeatures<int32_t>* double_transposed=transposed->get_transposed();

	for (index_t i=0; i<features->get_num_vectors(); ++i)
	{
		int32_t len;
		bool free_1, free_2;
		SGSparseVectorEntry<int32_t>* orig_vec=
				features->get_sparse_feature_vector(i, len, free_1);
		SGSparseVectorEntry<int32_t>* new_vec=
				double_transposed->get_sparse_feature_vector(i, len, free_2);

		for (index_t j=0; j<len; j++)
			ASSERT(orig_vec[j].entry==new_vec[j].entry);

		if (free_1)
			delete orig_vec;

		if (free_2)
			delete new_vec;

	}

	SG_UNREF(transposed);
	SG_UNREF(double_transposed);
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);
	const int32_t num_subset_idx=CMath::random(1, num_vectors);

	/* create feature data matrix */
	SGMatrix<int32_t> data(dim_features, num_vectors);

	/* fill matrix with random data */
	for (index_t i=0; i<num_vectors*dim_features; ++i)
		data.matrix[i]=CMath::random(1, 9);

	/* create sparse features */
	CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data);

	/* print dense feature matrix */
	CMath::display_matrix(data.matrix, data.num_rows, data.num_cols,
			"dense feature matrix");

	/* create subset indices */
	SGVector<index_t> subset_idx(CMath::randperm(num_subset_idx),
			num_subset_idx);

	/* print subset indices */
	CMath::display_vector(subset_idx.vector, subset_idx.vlen, "subset indices");

	/* apply subset to features */
	SG_SPRINT("\n-------------------\n"
	"applying subset to features\n"
	"-------------------\n");
	features->set_subset(new CSubset(subset_idx));

	/* do some stuff do check and output */
	ASSERT(features->get_num_vectors()==num_subset_idx);
	SG_SPRINT("features->get_num_vectors(): %d\n", features->get_num_vectors());

	/* check get_Transposed method */
	SG_SPRINT("checking transpose...");
	check_transposed(features);
	SG_SPRINT("does work\n");

	for (index_t i=0; i<features->get_num_vectors(); ++i)
	{
		int32_t len;
		bool free;
		SGSparseVectorEntry<int32_t>* vec=features->get_sparse_feature_vector(i,
				len, free);
		SG_SPRINT("sparse_vector[%d]=", i);
		for (index_t j=0; j<len; ++j)
		{
			SG_SPRINT("%d", vec[j].entry);
			if (j<len-1)
				SG_SPRINT(",");
		}

		SG_SPRINT("\n");

		for (index_t j=0; j<len; ++j)
			ASSERT(
					vec[j].entry==data.matrix[features->subset_idx_conversion( i)*num_vectors+j]);

		if (free)
			delete vec;
	}

	/* remove features subset */
	SG_SPRINT("\n-------------------\n"
	"removing subset from features\n"
	"-------------------\n");
	features->remove_subset();

	/* do some stuff do check and output */
	ASSERT(features->get_num_vectors()==num_vectors);
	SG_SPRINT("features->get_num_vectors(): %d\n", features->get_num_vectors());

	/* check get_Transposed method */
	SG_SPRINT("checking transpose...");
	check_transposed(features);
	SG_SPRINT("does work\n");

	for (index_t i=0; i<features->get_num_vectors(); ++i)
	{
		int32_t len;
		bool free;
		SGSparseVectorEntry<int32_t>* vec=features->get_sparse_feature_vector(i,
				len, free);
		SG_SPRINT("sparse_vector[%d]=", i);
		for (index_t j=0; j<len; ++j)
		{
			SG_SPRINT("%d", vec[j].entry);
			if (j<len-1)
				SG_SPRINT(",");
		}

		SG_SPRINT("\n");

		for (index_t j=0; j<len; ++j)
			ASSERT(vec[j].entry==data.matrix[i*num_vectors+j]);

		if (free)
			delete vec;
	}

	SG_UNREF(features);
	delete[] data.matrix;

	SG_SPRINT("\nEND\n");
	exit_shogun();

	return 0;
}
<commit_msg>make usage of free_sparse_feature_vector method<commit_after>/*
 * 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.
 *
 * Written (W) 2011 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/base/init.h>
#include <shogun/features/SparseFeatures.h>
#include <shogun/features/Subset.h>

using namespace shogun;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

const int32_t num_vectors=6;
const int32_t dim_features=6;

void check_transposed(CSparseFeatures<int32_t>* features)
{
	CSparseFeatures<int32_t>* transposed=features->get_transposed();
	CSparseFeatures<int32_t>* double_transposed=transposed->get_transposed();

	for (index_t i=0; i<features->get_num_vectors(); ++i)
	{
		int32_t len;
		bool free_1, free_2;
		SGSparseVectorEntry<int32_t>* orig_vec=
				features->get_sparse_feature_vector(i, len, free_1);
		SGSparseVectorEntry<int32_t>* new_vec=
				double_transposed->get_sparse_feature_vector(i, len, free_2);

		for (index_t j=0; j<len; j++)
			ASSERT(orig_vec[j].entry==new_vec[j].entry);

		features->free_sparse_feature_vector(orig_vec, i, free_1);
		double_transposed->free_sparse_feature_vector(new_vec, i, free_2);
	}

	SG_UNREF(transposed);
	SG_UNREF(double_transposed);
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);
	const int32_t num_subset_idx=CMath::random(1, num_vectors);

	/* create feature data matrix */
	SGMatrix<int32_t> data(dim_features, num_vectors);

	/* fill matrix with random data */
	for (index_t i=0; i<num_vectors*dim_features; ++i)
		data.matrix[i]=CMath::random(1, 9);

	/* create sparse features */
	CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data);

	/* print dense feature matrix */
	CMath::display_matrix(data.matrix, data.num_rows, data.num_cols,
			"dense feature matrix");

	/* create subset indices */
	SGVector<index_t> subset_idx(CMath::randperm(num_subset_idx),
			num_subset_idx);

	/* print subset indices */
	CMath::display_vector(subset_idx.vector, subset_idx.vlen, "subset indices");

	/* apply subset to features */
	SG_SPRINT("\n-------------------\n"
	"applying subset to features\n"
	"-------------------\n");
	features->set_subset(new CSubset(subset_idx));

	/* do some stuff do check and output */
	ASSERT(features->get_num_vectors()==num_subset_idx);
	SG_SPRINT("features->get_num_vectors(): %d\n", features->get_num_vectors());

	/* check get_Transposed method */
	SG_SPRINT("checking transpose...");
	check_transposed(features);
	SG_SPRINT("does work\n");

	for (index_t i=0; i<features->get_num_vectors(); ++i)
	{
		int32_t len;
		bool free;
		SGSparseVectorEntry<int32_t>* vec=features->get_sparse_feature_vector(i,
				len, free);
		SG_SPRINT("sparse_vector[%d]=", i);
		for (index_t j=0; j<len; ++j)
		{
			SG_SPRINT("%d", vec[j].entry);
			if (j<len-1)
				SG_SPRINT(",");
		}

		SG_SPRINT("\n");

		for (index_t j=0; j<len; ++j)
			ASSERT(
					vec[j].entry==data.matrix[features->subset_idx_conversion( i)*num_vectors+j]);

		features->free_sparse_feature_vector(vec, i, free);
	}

	/* remove features subset */
	SG_SPRINT("\n-------------------\n"
	"removing subset from features\n"
	"-------------------\n");
	features->remove_subset();

	/* do some stuff do check and output */
	ASSERT(features->get_num_vectors()==num_vectors);
	SG_SPRINT("features->get_num_vectors(): %d\n", features->get_num_vectors());

	/* check get_Transposed method */
	SG_SPRINT("checking transpose...");
	check_transposed(features);
	SG_SPRINT("does work\n");

	for (index_t i=0; i<features->get_num_vectors(); ++i)
	{
		int32_t len;
		bool free;
		SGSparseVectorEntry<int32_t>* vec=features->get_sparse_feature_vector(i,
				len, free);
		SG_SPRINT("sparse_vector[%d]=", i);
		for (index_t j=0; j<len; ++j)
		{
			SG_SPRINT("%d", vec[j].entry);
			if (j<len-1)
				SG_SPRINT(",");
		}

		SG_SPRINT("\n");

		for (index_t j=0; j<len; ++j)
			ASSERT(vec[j].entry==data.matrix[i*num_vectors+j]);

		features->free_sparse_feature_vector(vec, i, free);
	}

	SG_UNREF(features);
	delete[] data.matrix;

	SG_SPRINT("\nEND\n");
	exit_shogun();

	return 0;
}
<|endoftext|>