<commit_before>/*
 * Copyright 2015 Nicolas Pope
 */

#include "dharc/sense.hpp"

#include <iostream>

#include <fcntl.h>              /* low-level i/o */
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

#include <asm/types.h>          /* for videodev2.h */

#include <linux/videodev2.h>

using dharc::Sense;
using dharc::Node;
using std::cout;

int fd = -1;

#define CLEAR(x) memset (&(x), 0, sizeof (x))

constexpr size_t width = 320;
constexpr size_t height = 240;
constexpr size_t size() { return width * height; }

struct buffer
{
    void *start;
    size_t length;
};

buffer *buffers;

float fbuffer[size()];
const char *dev_name = "/dev/video0";

static void errno_exit(const char *s)
{
    fprintf(stderr, "%s error %d, %s\n", s, errno, strerror(errno));

    exit(EXIT_FAILURE);
}

static int xioctl(int fd, int request, void *arg)
{
    int r;

    do
    {
        r = ioctl(fd, request, arg);
    }
    while (-1 == r && EINTR == errno);

    return r;
}

int read_frame(void)
{
	struct v4l2_buffer buf;

    CLEAR(buf);

    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_USERPTR;

    if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf))
    {
        switch (errno)
        {
        case EAGAIN:
            return 0;

        case EIO:
            /* Could ignore EIO, see spec. */

            /* fall through */

        default:
            errno_exit("VIDIOC_DQBUF");
        }
    }

    //for (i = 0; i < n_buffers; ++i)
     //buf.m.userptr == (unsigned long)buffers[0].start
     //buf.length == buffers[0].length)
            //break;

    //assert(i < n_buffers);

    // process_image((void *)buf.m.userptr);

    if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
        errno_exit("VIDIOC_QBUF");

	return 1;
}

static void init_userp(unsigned int buffer_size)
{
    struct v4l2_requestbuffers req;
    unsigned int page_size;

    page_size = getpagesize();
    buffer_size = (buffer_size + page_size - 1) & ~(page_size - 1);

    CLEAR(req);

    req.count = 1;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    req.memory = V4L2_MEMORY_USERPTR;

    if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req))
    {
        if (EINVAL == errno)
        {
            fprintf(stderr, "%s does not support "
                    "user pointer i/o\n", dev_name);
            exit(EXIT_FAILURE);
        }
        else
        {
            errno_exit("VIDIOC_REQBUFS");
        }
    }

    buffers = (buffer*)calloc(1, sizeof(*buffers));

    if (!buffers)
    {
        fprintf(stderr, "Out of memory\n");
        exit(EXIT_FAILURE);
    }

    //for (n_buffers = 0; n_buffers < 4; ++n_buffers)
    //{
        buffers[0].length = buffer_size;
        buffers[0].start = memalign( /* boundary */ page_size,
                                            buffer_size);

        /*if (!buffers[n_buffers].start)
        {
            fprintf(stderr, "Out of memory\n");
            exit(EXIT_FAILURE);
        }*/
    //}
}

void init_device(void)
{
    struct v4l2_capability cap;
    struct v4l2_cropcap cropcap;
    struct v4l2_crop crop;
    struct v4l2_format fmt;
    // unsigned int min;

    if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap))
    {
        if (EINVAL == errno)
        {
            fprintf(stderr, "%s is no V4L2 device\n", dev_name);
            exit(EXIT_FAILURE);
        }
        else
        {
            errno_exit("VIDIOC_QUERYCAP");
        }
    }

    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE))
    {
        fprintf(stderr, "%s is no video capture device\n", dev_name);
        exit(EXIT_FAILURE);
    }

    if (!(cap.capabilities & V4L2_CAP_STREAMING))
    {
        fprintf(stderr, "%s does not support streaming i/o\n", dev_name);
        exit(EXIT_FAILURE);
    }

    /* Select video input, video standard and tune here. */

    CLEAR(cropcap);

    cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap))
    {
        crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        crop.c = cropcap.defrect;   /* reset to default */

        if (-1 == xioctl(fd, VIDIOC_S_CROP, &crop))
        {
            switch (errno)
            {
            case EINVAL:
                /* Cropping not supported. */
                break;
            default:
                /* Errors ignored. */
                break;
            }
        }
    }
    else
    {
        /* Errors ignored. */
    }

    CLEAR(fmt);

    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fmt.fmt.pix.width = width;
    fmt.fmt.pix.height = height;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
    fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;

    if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt))
        errno_exit("VIDIOC_S_FMT");

    /* Note VIDIOC_S_FMT may change width and height. */

    /* Buggy driver paranoia. */
    /*min = fmt.fmt.pix.width * 2;
    if (fmt.fmt.pix.bytesperline < min)
        fmt.fmt.pix.bytesperline = min;
    min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
    if (fmt.fmt.pix.sizeimage < min)
        fmt.fmt.pix.sizeimage = min;*/

    //if (fmt.fmt.pix.width != 320)
    //    WIDTH = fmt.fmt.pix.width;

   // if (fmt.fmt.pix.height != HEIGHT)
   //     HEIGHT = fmt.fmt.pix.height;

	init_userp(fmt.fmt.pix.sizeimage);
}
void stop_capturing(void)
{
    enum v4l2_buf_type type;

    type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (-1 == xioctl(fd, VIDIOC_STREAMOFF, &type))
        errno_exit("VIDIOC_STREAMOFF");
}

void start_capturing(void)
{
    enum v4l2_buf_type type;

    struct v4l2_buffer buf;

    CLEAR(buf);

    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_USERPTR;
    buf.index = 0;
    buf.m.userptr = (unsigned long)buffers[0].start;
    buf.length = buffers[0].length;

    if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
        errno_exit("VIDIOC_QBUF");

    type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
        errno_exit("VIDIOC_STREAMON");
}

void uninit_device(void)
{
    free(buffers[0].start);
    free(buffers);
}

void close_device()
{
    if (-1 == close(fd))
        errno_exit("close");

    fd = -1;
}

void open_device()
{
    struct stat st;

    if (-1 == stat(dev_name, &st))
    {
        fprintf(stderr, "Cannot identify '%s': %d, %s\n",
                dev_name, errno, strerror(errno));
        exit(EXIT_FAILURE);
    }

    if (!S_ISCHR(st.st_mode))
    {
        fprintf(stderr, "%s is no device\n", dev_name);
        exit(EXIT_FAILURE);
    }

    fd = open(dev_name, O_RDWR /* required */  | O_NONBLOCK, 0);

    if (-1 == fd)
    {
        fprintf(stderr, "Cannot open '%s': %d, %s\n",
                dev_name, errno, strerror(errno));
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char *argv[]) {
	Sense sense("localhost", 7878);

	Node cam_f, cam_l;
	sense.makeHarcs(320 * 240, cam_f, cam_l);

	open_device();
	init_device();
	start_capturing();

	vector<float> data;
	data.resize(320 * 240);

	while (true) {
		fd_set fds;
        struct timeval tv;
        int r;

        FD_ZERO(&fds);
        FD_SET(fd, &fds);

        /* Timeout. */
        tv.tv_sec = 2;
        tv.tv_usec = 0;

        r = select(fd + 1, &fds, NULL, NULL, &tv);

        if (-1 == r)
        {
            if (EINTR == errno)
                continue;

            errno_exit("select");
        }

        if (0 == r)
        {
            fprintf(stderr, "select timeout\n");
            exit(EXIT_FAILURE);
        }

		read_frame();
		for (auto i = 0U; i < data.size(); ++i) {
			unsigned char y = *((char*)buffers[0].start + (2*i));
			data[i] = 1.0f / (255.0f - static_cast<float>(y));
		}
		sense.activate(cam_f, cam_l, data);
	}

	stop_capturing();
	uninit_device();
	close_device();

	return 0;
}

<commit_msg>Monitor shows harc follows<commit_after>/*
 * Copyright 2015 Nicolas Pope
 */

#include "dharc/sense.hpp"

#include <iostream>

#include <fcntl.h>              /* low-level i/o */
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

#include <SDL/SDL.h>

#include <asm/types.h>          /* for videodev2.h */

#include <linux/videodev2.h>

using dharc::Sense;
using dharc::Node;
using std::cout;

int fd = -1;

#define CLEAR(x) memset (&(x), 0, sizeof (x))

constexpr size_t width = 320;
constexpr size_t height = 240;
constexpr size_t size() { return width * height; }

struct buffer
{
    void *start;
    size_t length;
};

buffer *buffers;

float fbuffer[size()];
const char *dev_name = "/dev/video0";

static void errno_exit(const char *s)
{
    fprintf(stderr, "%s error %d, %s\n", s, errno, strerror(errno));

    exit(EXIT_FAILURE);
}

static int xioctl(int fd, int request, void *arg)
{
    int r;

    do
    {
        r = ioctl(fd, request, arg);
    }
    while (-1 == r && EINTR == errno);

    return r;
}

int read_frame(void)
{
	struct v4l2_buffer buf;

    CLEAR(buf);

    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_USERPTR;

    if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf))
    {
        switch (errno)
        {
        case EAGAIN:
            return 0;

        case EIO:
            /* Could ignore EIO, see spec. */

            /* fall through */

        default:
            errno_exit("VIDIOC_DQBUF");
        }
    }

    //for (i = 0; i < n_buffers; ++i)
     //buf.m.userptr == (unsigned long)buffers[0].start
     //buf.length == buffers[0].length)
            //break;

    //assert(i < n_buffers);

    // process_image((void *)buf.m.userptr);

    if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
        errno_exit("VIDIOC_QBUF");

	return 1;
}

static void init_userp(unsigned int buffer_size)
{
    struct v4l2_requestbuffers req;
    unsigned int page_size;

    page_size = getpagesize();
    buffer_size = (buffer_size + page_size - 1) & ~(page_size - 1);

    CLEAR(req);

    req.count = 1;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    req.memory = V4L2_MEMORY_USERPTR;

    if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req))
    {
        if (EINVAL == errno)
        {
            fprintf(stderr, "%s does not support "
                    "user pointer i/o\n", dev_name);
            exit(EXIT_FAILURE);
        }
        else
        {
            errno_exit("VIDIOC_REQBUFS");
        }
    }

    buffers = (buffer*)calloc(1, sizeof(*buffers));

    if (!buffers)
    {
        fprintf(stderr, "Out of memory\n");
        exit(EXIT_FAILURE);
    }

    //for (n_buffers = 0; n_buffers < 4; ++n_buffers)
    //{
        buffers[0].length = buffer_size;
        buffers[0].start = memalign( /* boundary */ page_size,
                                            buffer_size);

        /*if (!buffers[n_buffers].start)
        {
            fprintf(stderr, "Out of memory\n");
            exit(EXIT_FAILURE);
        }*/
    //}
}

void init_device(void)
{
    struct v4l2_capability cap;
    struct v4l2_cropcap cropcap;
    struct v4l2_crop crop;
    struct v4l2_format fmt;
    // unsigned int min;

    if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap))
    {
        if (EINVAL == errno)
        {
            fprintf(stderr, "%s is no V4L2 device\n", dev_name);
            exit(EXIT_FAILURE);
        }
        else
        {
            errno_exit("VIDIOC_QUERYCAP");
        }
    }

    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE))
    {
        fprintf(stderr, "%s is no video capture device\n", dev_name);
        exit(EXIT_FAILURE);
    }

    if (!(cap.capabilities & V4L2_CAP_STREAMING))
    {
        fprintf(stderr, "%s does not support streaming i/o\n", dev_name);
        exit(EXIT_FAILURE);
    }

    /* Select video input, video standard and tune here. */

    CLEAR(cropcap);

    cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap))
    {
        crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        crop.c = cropcap.defrect;   /* reset to default */

        if (-1 == xioctl(fd, VIDIOC_S_CROP, &crop))
        {
            switch (errno)
            {
            case EINVAL:
                /* Cropping not supported. */
                break;
            default:
                /* Errors ignored. */
                break;
            }
        }
    }
    else
    {
        /* Errors ignored. */
    }

    CLEAR(fmt);

    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fmt.fmt.pix.width = width;
    fmt.fmt.pix.height = height;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
    fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;

    if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt))
        errno_exit("VIDIOC_S_FMT");

    /* Note VIDIOC_S_FMT may change width and height. */

    /* Buggy driver paranoia. */
    /*min = fmt.fmt.pix.width * 2;
    if (fmt.fmt.pix.bytesperline < min)
        fmt.fmt.pix.bytesperline = min;
    min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
    if (fmt.fmt.pix.sizeimage < min)
        fmt.fmt.pix.sizeimage = min;*/

    //if (fmt.fmt.pix.width != 320)
    //    WIDTH = fmt.fmt.pix.width;

   // if (fmt.fmt.pix.height != HEIGHT)
   //     HEIGHT = fmt.fmt.pix.height;

	init_userp(fmt.fmt.pix.sizeimage);
}
void stop_capturing(void)
{
    enum v4l2_buf_type type;

    type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (-1 == xioctl(fd, VIDIOC_STREAMOFF, &type))
        errno_exit("VIDIOC_STREAMOFF");
}

void start_capturing(void)
{
    enum v4l2_buf_type type;

    struct v4l2_buffer buf;

    CLEAR(buf);

    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_USERPTR;
    buf.index = 0;
    buf.m.userptr = (unsigned long)buffers[0].start;
    buf.length = buffers[0].length;

    if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
        errno_exit("VIDIOC_QBUF");

    type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
        errno_exit("VIDIOC_STREAMON");
}

void uninit_device(void)
{
    free(buffers[0].start);
    free(buffers);
}

void close_device()
{
    if (-1 == close(fd))
        errno_exit("close");

    fd = -1;
}

void open_device()
{
    struct stat st;

    if (-1 == stat(dev_name, &st))
    {
        fprintf(stderr, "Cannot identify '%s': %d, %s\n",
                dev_name, errno, strerror(errno));
        exit(EXIT_FAILURE);
    }

    if (!S_ISCHR(st.st_mode))
    {
        fprintf(stderr, "%s is no device\n", dev_name);
        exit(EXIT_FAILURE);
    }

    fd = open(dev_name, O_RDWR /* required */  | O_NONBLOCK, 0);

    if (-1 == fd)
    {
        fprintf(stderr, "Cannot open '%s': %d, %s\n",
                dev_name, errno, strerror(errno));
        exit(EXIT_FAILURE);
    }
}

int sdl_filter(const SDL_Event * event)
{
    return event->type == SDL_QUIT;
}

#define mask32(BYTE) (*(uint32_t *)(uint8_t [4]){ [BYTE] = 0xff })

int main(int argc, char *argv[]) {
	Sense sense("localhost", 7878);

	Node cam_f, cam_l;
	sense.makeHarcs(320 * 240, cam_f, cam_l);

	atexit(SDL_Quit);
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
        return 1;

    SDL_WM_SetCaption("Dharc Sense Camera", NULL);

	uint8_t *buffer_sdl;
	SDL_Surface *data_sf;
    buffer_sdl = (uint8_t*)malloc(width*height*3);

    SDL_SetVideoMode(width, height, 24, SDL_HWSURFACE);

    data_sf = SDL_CreateRGBSurfaceFrom(buffer_sdl, width, height,
                                       24, width * 3,
                                       mask32(0), mask32(1), mask32(2), 0);

    SDL_SetEventFilter(sdl_filter);

	open_device();
	init_device();
	start_capturing();

	vector<float> data;
	data.resize(320 * 240);

	while (true) {
		fd_set fds;
        struct timeval tv;
        int r;

        FD_ZERO(&fds);
        FD_SET(fd, &fds);

        /* Timeout. */
        tv.tv_sec = 2;
        tv.tv_usec = 0;

        r = select(fd + 1, &fds, NULL, NULL, &tv);

        if (-1 == r)
        {
            if (EINTR == errno)
                continue;

            errno_exit("select");
        }

        if (0 == r)
        {
            fprintf(stderr, "select timeout\n");
            exit(EXIT_FAILURE);
        }

		read_frame();
		for (auto i = 0U; i < data.size(); ++i) {
			unsigned char y = *((char*)buffers[0].start + (2*i));
			buffer_sdl[i*3] = y;
			buffer_sdl[(i*3)+1] = y;
			buffer_sdl[(i*3)+2] = y;
			data[i] = 1.0f / (255.0f - static_cast<float>(y));
		}
		sense.activate(cam_f, cam_l, data);

		SDL_Surface *screen = SDL_GetVideoSurface();
		if (SDL_BlitSurface(data_sf, NULL, screen, NULL) == 0)
		    SDL_UpdateRect(screen, 0, 0, 0, 0);
	}

	stop_capturing();
	uninit_device();
	close_device();

	return 0;
}

<|endoftext|>


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

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplicationRegistry.h"
#include "itksys/SystemTools.hxx"

namespace otb
{
namespace Wrapper
{

ApplicationRegistry::ApplicationRegistry()
{
}

ApplicationRegistry::~ApplicationRegistry()
{
}

void
ApplicationRegistry::SetApplicationPath(std::string newpath)
{
  std::ostringstream putEnvPath;
  putEnvPath << "ITK_AUTOLOAD_PATH=" << newpath;

  // do NOT use putenv() directly, since the string memory must be managed carefully
  itksys::SystemTools::PutEnv(putEnvPath.str().c_str());

  // Reload factories to take into account new path
  itk::ObjectFactoryBase::ReHash();
}

void
ApplicationRegistry::AddApplicationPath(std::string newpath)
{
  std::ostringstream putEnvPath;
  putEnvPath << "ITK_AUTOLOAD_PATH=";

  const char* currentEnv = itksys::SystemTools::GetEnv("ITK_AUTOLOAD_PATH");
  if (currentEnv)
    {
    putEnvPath << currentEnv << ":";
    }
  putEnvPath << newpath;

  // do NOT use putenv() directly, since the string memory must be managed carefully
  itksys::SystemTools::PutEnv(putEnvPath.str().c_str());

  // Reload factories to take into account new path
  itk::ObjectFactoryBase::ReHash();

}

Application::Pointer
ApplicationRegistry::CreateApplication(const std::string& name)
{
  ApplicationPointer appli;

  std::list<ApplicationPointer> possibleApp;
  std::list<LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("otbWrapperApplication");

  // Downcast and Sanity check
  for (std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i != allobjects.end(); ++i)
    {
    Application* io = dynamic_cast<Application*> (i->GetPointer());
    if (io)
      {
      possibleApp.push_back(io);
      }
    else
      {
      otbMsgDevMacro( << "Error ApplicationRegistry factory did not return an Application: " << (*i)->GetNameOfClass() << std::endl );
      }
    }

  // Return the app with the desired name
  for(std::list<ApplicationPointer>::iterator k = possibleApp.begin();
      k != possibleApp.end(); ++k)
    {
    if ( (*k)->GetName() == name )
      {
      return *k;
      }
    }

  return appli;
}

std::vector<std::string>
ApplicationRegistry::GetAvailableApplications()
{
  ApplicationPointer appli;

  std::list<ApplicationPointer> possibleApp;
  std::list<LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("otbWrapperApplication");

  // Downcast and Sanity check
  for (std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i != allobjects.end(); ++i)
    {
    Application* io = dynamic_cast<Application*> (i->GetPointer());
    if (io)
      {
      possibleApp.push_back(io);
      }
    else
      {
      otbMsgDevMacro( "Error ApplicationRegistry factory did not return an Application: " << (*i)->GetNameOfClass() << std::endl );
      }
    }

  // Return the app list
  std::vector<std::string> availableApp;
  for(std::list<ApplicationPointer>::iterator k = possibleApp.begin();
      k != possibleApp.end(); ++k)
    {
    availableApp.push_back((*k)->GetName());
    }
  return availableApp;
}

} // end namespace Wrapper
} //end namespace otb
<commit_msg>ENH: prevent multiple apparition of one unique application in the availble applciation<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplicationRegistry.h"
#include "itksys/SystemTools.hxx"

namespace otb
{
namespace Wrapper
{

ApplicationRegistry::ApplicationRegistry()
{
}

ApplicationRegistry::~ApplicationRegistry()
{
}

void
ApplicationRegistry::SetApplicationPath(std::string newpath)
{
  std::ostringstream putEnvPath;
  putEnvPath << "ITK_AUTOLOAD_PATH=" << newpath;

  // do NOT use putenv() directly, since the string memory must be managed carefully
  itksys::SystemTools::PutEnv(putEnvPath.str().c_str());

  // Reload factories to take into account new path
  itk::ObjectFactoryBase::ReHash();
}

void
ApplicationRegistry::AddApplicationPath(std::string newpath)
{
  std::ostringstream putEnvPath;
  putEnvPath << "ITK_AUTOLOAD_PATH=";

  const char* currentEnv = itksys::SystemTools::GetEnv("ITK_AUTOLOAD_PATH");
  if (currentEnv)
    {
    putEnvPath << currentEnv << ":";
    }
  putEnvPath << newpath;

  // do NOT use putenv() directly, since the string memory must be managed carefully
  itksys::SystemTools::PutEnv(putEnvPath.str().c_str());

  // Reload factories to take into account new path
  itk::ObjectFactoryBase::ReHash();

}

Application::Pointer
ApplicationRegistry::CreateApplication(const std::string& name)
{
  ApplicationPointer appli;

  std::list<ApplicationPointer> possibleApp;
  std::list<LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("otbWrapperApplication");

  // Downcast and Sanity check
  for (std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i != allobjects.end(); ++i)
    {
    Application* io = dynamic_cast<Application*> (i->GetPointer());
    if (io)
      {
      possibleApp.push_back(io);
      }
    else
      {
      otbMsgDevMacro( << "Error ApplicationRegistry factory did not return an Application: " << (*i)->GetNameOfClass() << std::endl );
      }
    }

  // Return the app with the desired name
  for(std::list<ApplicationPointer>::iterator k = possibleApp.begin();
      k != possibleApp.end(); ++k)
    {
    if ( (*k)->GetName() == name )
      {
      return *k;
      }
    }

  return appli;
}

std::vector<std::string>
ApplicationRegistry::GetAvailableApplications()
{
  ApplicationPointer appli;

  std::list<ApplicationPointer> possibleApp;
  std::list<LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("otbWrapperApplication");

  // Downcast and Sanity check
  for (std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i != allobjects.end(); ++i)
    {
    Application* io = dynamic_cast<Application*> (i->GetPointer());
    if (io)
      {
      possibleApp.push_back(io);
      }
    else
      {
      otbMsgDevMacro( "Error ApplicationRegistry factory did not return an Application: " << (*i)->GetNameOfClass() << std::endl );
      }
    }

  // Return the app list
  std::vector<std::string> availableApp;
  for(std::list<ApplicationPointer>::iterator k = possibleApp.begin();
      k != possibleApp.end(); ++k)
    {
    availableApp.push_back((*k)->GetName());
    }
  // If the ITK_AUTOLOAD_PATH contains
  // several times the same path, application will appears several
  // times in the list.To be cleaner, we erase multiple
  std::vector<std::string>::iterator it;
  it = std::unique(availableApp.begin(), availableApp.end());
  availableApp.resize( it - availableApp.begin() );

  return availableApp;
}

} // end namespace Wrapper
} //end namespace otb
<|endoftext|>


<commit_before>/* Copyright (c) 2013 Quanta Research Cambridge, Inc
 *
 * 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.
 */
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <semaphore.h>
#include "StdDmaIndication.h"

#include "DmaConfigProxy.h"
#include "GeneratedTypes.h"
#include "PerfIndicationWrapper.h"
#include "PerfRequestProxy.h"

sem_t copy_sem;

PerfRequestProxy *device = 0;
DmaConfigProxy *dma = 0;

PortalAlloc *srcAlloc;
PortalAlloc *dstAlloc;
unsigned int *srcBuffer = 0;
unsigned int *dstBuffer = 0;
int numWords;
size_t test_sz  = (1 << 20) *sizeof(unsigned int);
size_t alloc_sz = test_sz;
unsigned int finishedCount;
unsigned int ref_srcAlloc;
unsigned int ref_dstAlloc;

bool memcmp_fail = false;
unsigned int memcmp_count = 0;
unsigned int start_count = 0;
unsigned int copy_size = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s ", prefix);
    for (int i = 0; i < len ; i++) {
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
	if (i % 32 == 31)
	  fprintf(stderr, "\n");
    }
    fprintf(stderr, "\n");
}

class PerfIndication : public PerfIndicationWrapper
{

public:
  PerfIndication(const char* devname, unsigned int addrbits) : PerfIndicationWrapper(devname,addrbits){}
  PerfIndication(unsigned int id) : PerfIndicationWrapper(id){}

  virtual void started(unsigned long words){
    // fprintf(stderr, "started: words=%ld\n", words);
    start_count += 1;
    if (copy_size == 0) sem_post(&copy_sem);
  }
  virtual void readWordResult ( unsigned long v ){
    dump("readWordResult: ", (char*)&v, sizeof(v));
  }
  virtual void done(unsigned long v) {
    finishedCount += 1;
    sem_post(&copy_sem);
  }
  virtual void rData ( unsigned long long v ){
    dump("rData: ", (char*)&v, sizeof(v));
  }
  virtual void readReq(unsigned long v){
    //fprintf(stderr, "readReq %lx\n", v);
  }
  virtual void writeReq(unsigned long v){
    //fprintf(stderr, "writeReq %lx\n", v);
  }
  virtual void writeAck(unsigned long v){
    //fprintf(stderr, "writeAck %lx\n", v);
  }
  virtual void reportStateDbg(unsigned long srcGen, unsigned long streamRdCnt,
			      unsigned long streamWrCnt, unsigned long writeInProg,
			      unsigned long dataMismatch){
    fprintf(stderr, "Perf::reportStateDbg: srcGen=%ld, streamRdCnt=%ld, streamWrCnt=%ld, writeInProg=%ld, dataMismatch=%ld\n",
	    srcGen, streamRdCnt, streamWrCnt, writeInProg, dataMismatch);
  }
};
PerfIndication *deviceIndication = 0;
DmaIndication *dmaIndication = 0;

// we can use the data synchronization barrier instead of flushing the
// cache only because the ps7 is configured to run in buffered-write mode
//
// an opc2 of '4' and CRm of 'c10' encodes "CP15DSB, Data Synchronization Barrier
// operation". this is a legal instruction to execute in non-privileged mode (mdk)
//
// #define DATA_SYNC_BARRIER   __asm __volatile( "MCR p15, 0, %0, c7, c10, 4" ::  "r" (0) );

long long deltatime( struct timeval start, struct timeval stop)
{
  long long diff = ((long long) (stop.tv_sec - start.tv_sec)) * 1000000;
  diff = diff + ((long long) (stop.tv_usec - start.tv_usec));
  return (diff);
}

int dotest(unsigned size, unsigned repeatCount)
{
  struct timeval start, stop;
  unsigned loops = 1;
  unsigned int i;
  long long interval;
  fprintf(stderr, "repeat %d size %d loop ", repeatCount, size);
  for(;;) {
    finishedCount = 0;
    copy_size = size;
    fprintf(stderr, " %d", loops);
    gettimeofday(&start, NULL);
    for (i = 0; i < loops; i += 1) {
      device->startCopy(ref_dstAlloc, ref_srcAlloc, numWords, repeatCount);
      sem_wait(&copy_sem);
    }
    gettimeofday(&stop, NULL);
    interval = deltatime(start, stop);
    if (interval >= 500000) break;
    loops <<= 1;
  }
  fprintf(stderr, "\n  block size %d microseconds %lld\n", size*16, interval / loops);
}

void printportalalloc(char *name, PortalAlloc *p)
{
  int i;
  fprintf(stderr, "%s\n", name);
  fprintf(stderr, "size %ld\n", p->header.size);
  fprintf(stderr, "fd %d\n", p->header.fd);
  fprintf(stderr, "numEntries %d\n", p->header.numEntries);
  for (i = 0; i < p->header.numEntries; i += 1)
    {
      fprintf(stderr, " entry %d (%lx, %lx)\n", i, p->entries[i].dma_address,
	      p->entries[i].length);
    }
}

int main(int argc, const char **argv)
{
  unsigned int srcGen = 0;

  fprintf(stderr, "%s %s\n", __DATE__, __TIME__);

  device = new PerfRequestProxy(IfcNames_PerfRequest);
  dma = new DmaConfigProxy(IfcNames_DmaConfig);

  deviceIndication = new PerfIndication(IfcNames_PerfIndication);
  dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);

  fprintf(stderr, "Main::allocating memory...\n");

  dma->alloc(alloc_sz, &srcAlloc);
  dma->alloc(alloc_sz, &dstAlloc);
  printportalalloc("srcAlloc", srcAlloc);
  printportalalloc("dstAlloc", dstAlloc);

  srcBuffer = (unsigned int *)mmap(0, alloc_sz, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, srcAlloc->header.fd, 0);
  dstBuffer = (unsigned int *)mmap(0, alloc_sz, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, dstAlloc->header.fd, 0);

  pthread_t tid;
  fprintf(stderr, "creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
    fprintf(stderr, "error creating exec thread\n");
    exit(1);
  }

  dma->dCacheFlushInval(srcAlloc, srcBuffer);
  dma->dCacheFlushInval(dstAlloc, dstBuffer);
  fprintf(stderr, "Main::flush and invalidate complete\n");

  ref_srcAlloc = dma->reference(srcAlloc);
  ref_dstAlloc = dma->reference(dstAlloc);
  fprintf(stderr, "ref_srcAlloc %d\n", ref_srcAlloc);
  fprintf(stderr, "ref_dstAlloc %d\n", ref_dstAlloc);
  //fprintf(stderr, "Main::starting mempcy numWords:%d\n", 0);

  //dotest(0);
  for (repeatCount = 1; repeatCount <= 16; repeatCount <<= 1) {
    fprintf(stderr, "Main::starting mempcy repeatCount:%d\n", repeatCount);
    for (numWords = 16; numWords < (1 << 16); numWords <<= 1){

      //fprintf(stderr, "Main::starting mempcy numWords:%d\n", numWords);

      dotest(numWords, repeatCount);
    }

  device->getStateDbg();
  fprintf(stderr, "Main::exiting\n");
}
<commit_msg>fix syntax errors<commit_after>/* Copyright (c) 2013 Quanta Research Cambridge, Inc
 *
 * 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.
 */
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <semaphore.h>
#include "StdDmaIndication.h"

#include "DmaConfigProxy.h"
#include "GeneratedTypes.h"
#include "PerfIndicationWrapper.h"
#include "PerfRequestProxy.h"

sem_t copy_sem;

PerfRequestProxy *device = 0;
DmaConfigProxy *dma = 0;

PortalAlloc *srcAlloc;
PortalAlloc *dstAlloc;
unsigned int *srcBuffer = 0;
unsigned int *dstBuffer = 0;
int numWords;
size_t test_sz  = (1 << 20) *sizeof(unsigned int);
size_t alloc_sz = test_sz;
unsigned int finishedCount;
unsigned int ref_srcAlloc;
unsigned int ref_dstAlloc;

bool memcmp_fail = false;
unsigned int memcmp_count = 0;
unsigned int start_count = 0;
unsigned int copy_size = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s ", prefix);
    for (int i = 0; i < len ; i++) {
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
	if (i % 32 == 31)
	  fprintf(stderr, "\n");
    }
    fprintf(stderr, "\n");
}

class PerfIndication : public PerfIndicationWrapper
{

public:
  PerfIndication(const char* devname, unsigned int addrbits) : PerfIndicationWrapper(devname,addrbits){}
  PerfIndication(unsigned int id) : PerfIndicationWrapper(id){}

  virtual void started(unsigned long words){
    // fprintf(stderr, "started: words=%ld\n", words);
    start_count += 1;
    if (copy_size == 0) sem_post(&copy_sem);
  }
  virtual void readWordResult ( unsigned long v ){
    dump("readWordResult: ", (char*)&v, sizeof(v));
  }
  virtual void done(unsigned long v) {
    finishedCount += 1;
    sem_post(&copy_sem);
  }
  virtual void rData ( unsigned long long v ){
    dump("rData: ", (char*)&v, sizeof(v));
  }
  virtual void readReq(unsigned long v){
    //fprintf(stderr, "readReq %lx\n", v);
  }
  virtual void writeReq(unsigned long v){
    //fprintf(stderr, "writeReq %lx\n", v);
  }
  virtual void writeAck(unsigned long v){
    //fprintf(stderr, "writeAck %lx\n", v);
  }
  virtual void reportStateDbg(unsigned long srcGen, unsigned long streamRdCnt,
			      unsigned long streamWrCnt, unsigned long writeInProg,
			      unsigned long dataMismatch){
    fprintf(stderr, "Perf::reportStateDbg: srcGen=%ld, streamRdCnt=%ld, streamWrCnt=%ld, writeInProg=%ld, dataMismatch=%ld\n",
	    srcGen, streamRdCnt, streamWrCnt, writeInProg, dataMismatch);
  }
};
PerfIndication *deviceIndication = 0;
DmaIndication *dmaIndication = 0;

// we can use the data synchronization barrier instead of flushing the
// cache only because the ps7 is configured to run in buffered-write mode
//
// an opc2 of '4' and CRm of 'c10' encodes "CP15DSB, Data Synchronization Barrier
// operation". this is a legal instruction to execute in non-privileged mode (mdk)
//
// #define DATA_SYNC_BARRIER   __asm __volatile( "MCR p15, 0, %0, c7, c10, 4" ::  "r" (0) );

long long deltatime( struct timeval start, struct timeval stop)
{
  long long diff = ((long long) (stop.tv_sec - start.tv_sec)) * 1000000;
  diff = diff + ((long long) (stop.tv_usec - start.tv_usec));
  return (diff);
}

int dotest(unsigned size, unsigned repeatCount)
{
  struct timeval start, stop;
  unsigned loops = 1;
  unsigned int i;
  long long interval;
  fprintf(stderr, "repeat %d size %d loop ", repeatCount, size);
  for(;;) {
    finishedCount = 0;
    copy_size = size;
    fprintf(stderr, " %d", loops);
    gettimeofday(&start, NULL);
    for (i = 0; i < loops; i += 1) {
      device->startCopy(ref_dstAlloc, ref_srcAlloc, numWords, repeatCount);
      sem_wait(&copy_sem);
    }
    gettimeofday(&stop, NULL);
    interval = deltatime(start, stop);
    if (interval >= 500000) break;
    loops <<= 1;
  }
  fprintf(stderr, "\n  block size %d microseconds %lld\n", size*16, interval / loops);
}

void printportalalloc(char *name, PortalAlloc *p)
{
  int i;
  fprintf(stderr, "%s\n", name);
  fprintf(stderr, "size %ld\n", p->header.size);
  fprintf(stderr, "fd %d\n", p->header.fd);
  fprintf(stderr, "numEntries %d\n", p->header.numEntries);
  for (i = 0; i < p->header.numEntries; i += 1)
    {
      fprintf(stderr, " entry %d (%lx, %lx)\n", i, p->entries[i].dma_address,
	      p->entries[i].length);
    }
}

int main(int argc, const char **argv)
{
  unsigned int srcGen = 0;
  unsigned repeatCount = 0;

  fprintf(stderr, "%s %s\n", __DATE__, __TIME__);

  device = new PerfRequestProxy(IfcNames_PerfRequest);
  dma = new DmaConfigProxy(IfcNames_DmaConfig);

  deviceIndication = new PerfIndication(IfcNames_PerfIndication);
  dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);

  fprintf(stderr, "Main::allocating memory...\n");

  dma->alloc(alloc_sz, &srcAlloc);
  dma->alloc(alloc_sz, &dstAlloc);
  printportalalloc("srcAlloc", srcAlloc);
  printportalalloc("dstAlloc", dstAlloc);

  srcBuffer = (unsigned int *)mmap(0, alloc_sz, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, srcAlloc->header.fd, 0);
  dstBuffer = (unsigned int *)mmap(0, alloc_sz, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, dstAlloc->header.fd, 0);

  pthread_t tid;
  fprintf(stderr, "creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
    fprintf(stderr, "error creating exec thread\n");
    exit(1);
  }

  dma->dCacheFlushInval(srcAlloc, srcBuffer);
  dma->dCacheFlushInval(dstAlloc, dstBuffer);
  fprintf(stderr, "Main::flush and invalidate complete\n");

  ref_srcAlloc = dma->reference(srcAlloc);
  ref_dstAlloc = dma->reference(dstAlloc);
  fprintf(stderr, "ref_srcAlloc %d\n", ref_srcAlloc);
  fprintf(stderr, "ref_dstAlloc %d\n", ref_dstAlloc);
  //fprintf(stderr, "Main::starting mempcy numWords:%d\n", 0);

  //dotest(0);
  for (repeatCount = 1; repeatCount <= 16; repeatCount <<= 1) {
    fprintf(stderr, "Main::starting mempcy repeatCount:%d\n", repeatCount);
    for (numWords = 16; numWords < (1 << 16); numWords <<= 1){

      //fprintf(stderr, "Main::starting mempcy numWords:%d\n", numWords);

      dotest(numWords, repeatCount);
    }
  }

  device->getStateDbg();
  fprintf(stderr, "Main::exiting\n");
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request_context.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_test.h"

namespace {

const wchar_t kTestUrlSwitch[] = L"test-url";

// A test to help determine if any nodes have been leaked as a result of
// visiting a given URL.  If enabled in WebCore, the number of leaked nodes
// can be printed upon termination.  This is only enabled in debug builds, so
// it only makes sense to run this using a debug build.
//
// It will load a URL, visit about:blank, and then perform garbage collection.
// The number of remaining (potentially leaked) nodes will be printed on exit.
class NodeLeakTest : public TestShellTest {
 public:
  virtual void SetUp() {
    CommandLine parsed_command_line;

    std::wstring js_flags =
      parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
    CommandLine::AppendSwitch(&js_flags, L"expose-gc");
    webkit_glue::SetJavaScriptFlags(js_flags);
    // Expose GCController to JavaScript as well.
    webkit_glue::SetShouldExposeGCController(true);

    std::wstring cache_path =
        parsed_command_line.GetSwitchValue(test_shell::kCacheDir);
    if (cache_path.empty()) {
      PathService::Get(base::DIR_EXE, &cache_path);
      file_util::AppendToPath(&cache_path, L"cache");
    }

    if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
      const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
          test_shell::kTestShellTimeOut);
      int timeout_ms = static_cast<int>(StringToInt64(timeout_str.c_str()));
      if (timeout_ms > 0)
        TestShell::SetFileTestTimeout(timeout_ms);
    }

    // Optionally use playback mode (for instance if running automated tests).
    net::HttpCache::Mode mode =
        parsed_command_line.HasSwitch(test_shell::kPlaybackMode) ?
        net::HttpCache::PLAYBACK : net::HttpCache::NORMAL;
    SimpleResourceLoaderBridge::Init(
        new TestShellRequestContext(cache_path, mode));

    TestShellTest::SetUp();
  }

  virtual void TearDown() {
    TestShellTest::TearDown();

    SimpleResourceLoaderBridge::Shutdown();
  }

  void NavigateToURL(const std::wstring& test_url) {
    test_shell_->LoadURL(test_url.c_str());
    test_shell_->WaitTestFinished();

    // Depends on TestShellTests::TearDown to load blank page and
    // the TestShell destructor to call garbage collection.
  }
};

}  // namespace

TEST_F(NodeLeakTest, TestURL) {
  CommandLine parsed_command_line;

  if (parsed_command_line.HasSwitch(kTestUrlSwitch)) {
    NavigateToURL(parsed_command_line.GetSwitchValue(kTestUrlSwitch).c_str());
  }
}

<commit_msg>Missed a usage of TestShellRequestContext.  This one is allowed to behave as before.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request_context.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_test.h"

namespace {

const wchar_t kTestUrlSwitch[] = L"test-url";

// A test to help determine if any nodes have been leaked as a result of
// visiting a given URL.  If enabled in WebCore, the number of leaked nodes
// can be printed upon termination.  This is only enabled in debug builds, so
// it only makes sense to run this using a debug build.
//
// It will load a URL, visit about:blank, and then perform garbage collection.
// The number of remaining (potentially leaked) nodes will be printed on exit.
class NodeLeakTest : public TestShellTest {
 public:
  virtual void SetUp() {
    CommandLine parsed_command_line;

    std::wstring js_flags =
      parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
    CommandLine::AppendSwitch(&js_flags, L"expose-gc");
    webkit_glue::SetJavaScriptFlags(js_flags);
    // Expose GCController to JavaScript as well.
    webkit_glue::SetShouldExposeGCController(true);

    std::wstring cache_path =
        parsed_command_line.GetSwitchValue(test_shell::kCacheDir);
    if (cache_path.empty()) {
      PathService::Get(base::DIR_EXE, &cache_path);
      file_util::AppendToPath(&cache_path, L"cache");
    }

    if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
      const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
          test_shell::kTestShellTimeOut);
      int timeout_ms = static_cast<int>(StringToInt64(timeout_str.c_str()));
      if (timeout_ms > 0)
        TestShell::SetFileTestTimeout(timeout_ms);
    }

    // Optionally use playback mode (for instance if running automated tests).
    net::HttpCache::Mode mode =
        parsed_command_line.HasSwitch(test_shell::kPlaybackMode) ?
        net::HttpCache::PLAYBACK : net::HttpCache::NORMAL;
    SimpleResourceLoaderBridge::Init(
        new TestShellRequestContext(cache_path, mode, false));

    TestShellTest::SetUp();
  }

  virtual void TearDown() {
    TestShellTest::TearDown();

    SimpleResourceLoaderBridge::Shutdown();
  }

  void NavigateToURL(const std::wstring& test_url) {
    test_shell_->LoadURL(test_url.c_str());
    test_shell_->WaitTestFinished();

    // Depends on TestShellTests::TearDown to load blank page and
    // the TestShell destructor to call garbage collection.
  }
};

}  // namespace

TEST_F(NodeLeakTest, TestURL) {
  CommandLine parsed_command_line;

  if (parsed_command_line.HasSwitch(kTestUrlSwitch)) {
    NavigateToURL(parsed_command_line.GetSwitchValue(kTestUrlSwitch).c_str());
  }
}

<|endoftext|>


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

#include <iostream>
#include <cstdlib>

#include "RtMidi.h"

#include "ctlra.h"
#include "devices/ni_maschine_mikro_mk2.h"
#include "sequencer.h"

static volatile uint32_t done;
static struct ctlra_dev_t* dev;

static Sequencer *sequencer;

#define MODE_GROUP   0
#define MODE_PADS    1
#define MODE_PATTERN 2

struct col_t
{
	uint8_t green;
	uint8_t blue;
	uint8_t red;
};
static const struct col_t grp_col[] = {
	{0x00, 0x92,  254},
	{0xf9, 0x21, 0x00},
	{0x00, 0xf0, 0x00},
	{0x00, 0x00, 0xf0},
	{0xf0, 0xf0, 0xb0},
	{0x3f, 0x3f, 0xf0},
	{0xf0, 0x00, 0xf0},
	{0x00, 0xef, 0xd5},
	/* dark */
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
};

uint32_t col_dim(const struct col_t *col, float bri)
{
	struct col_t c;
	c.red   = col->red   * bri;
	c.green = col->green * bri;
	c.blue  = col->blue  * bri;
	uint32_t intCol = *(uint32_t *)&c;
	return intCol;
}

static struct mm_t
{
	/* 0 Group   : Selects active group
	 * 1 Pads    : Plays different midi notes
	 * 2 Pattern : Sequence a single note
	 */
	uint8_t mode;
	uint8_t mode_prev;
	uint8_t shift_pressed;

	/* GROUP */
	uint8_t grp_id; /* 0 - 7, selected group */

	/* Pads */
	uint8_t pads_pressed[16];

	/* Pattern */
	uint8_t pattern_pad_id; /* the pad that this pattern is playing */
} mm_static;

void demo_feedback_func(struct ctlra_dev_t *dev, void *d)
{
	/* group, pads, sequencer modes */
	struct mm_t *mm = &mm_static;
	const struct col_t *col = &grp_col[mm->grp_id];
	switch(mm->mode) {
	case MODE_PATTERN: {
		for(int i = 0; i < 16; i++) {
			int on = sequencer_get_step(sequencer, i);
			ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 + i,
					    col_dim(col, on ? 1.0 : 0.00));
		}
		int step = sequencer_get_current_step( sequencer );
		int on = sequencer_get_step(sequencer, step % 16);
		ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 + step,
				    on ?  0x007f7f7f : 0x000f0f0f );
		break;
		}
	case MODE_GROUP:
		for(int i = 0; i < 16; i++) {
			ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 + i,
					    col_dim(&grp_col[i],
						    i == mm->grp_id ? 1.0 : 0.05));
		}
		break;
	case MODE_PADS:
		for(int i = 0; i < 16; i++) {
			ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 + i,
					    col_dim(&grp_col[mm->grp_id],
						    mm->pads_pressed[i] ? 1.0 : 0.02));
		}
		break;
	}

	ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_MODE,
			    mm->mode == MODE_PADS ? 0xffffffff : 0x3);
	ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PATTERN,
			    mm->mode == MODE_PATTERN ? 0xffffffff : 0x3);

	ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_GROUP,
			    col_dim(&grp_col[mm->grp_id], 1.0));

	ctlra_dev_light_flush(dev, 1);
}

void demo_event_func(struct ctlra_dev_t* dev,
                     uint32_t num_events,
                     struct ctlra_event_t** events,
                     void *userdata)
{
	struct mm_t *mm = &mm_static;
	/* See below, a RtMidiOut instance is passed as the device's
	 * userdata pointer when registering the event_func */
	RtMidiOut *midiout = (RtMidiOut *)userdata;

	std::vector<unsigned char> message(3);

	for(uint32_t i = 0; i < num_events; i++) {
		const char *pressed = 0;
		struct ctlra_event_t *e = events[i];
		int pr = 0;
		switch(e->type) {
		case CTLRA_EVENT_BUTTON:
			message[0] = e->button.pressed ? 0x90 : 0x80;
			message[1] = 60 + e->button.id;
			message[2] = e->button.pressed ? 0x70 : 0;
			midiout->sendMessage( &message );
			printf("button %d\n", e->button.id);
			pr = e->button.pressed;
			switch(e->button.id) {
			case  7: mm->shift_pressed = pr; break;
			case 22: mm->mode = MODE_PATTERN; break;
			case 23: mm->mode = MODE_PADS; break;
			case 8: /* Group */
				if(pr) {
					mm->mode_prev = mm->mode;
					mm->mode = 0;
				} else {
					mm->mode = mm->mode_prev;
				}
				break;
			}
			break;

		case CTLRA_EVENT_ENCODER:
			break;

		case CTLRA_EVENT_SLIDER:
			message[0] = 0xb0;
			message[1] = e->slider.id;
			message[2] = int(e->slider.value * 127.f);
			midiout->sendMessage( &message );
			break;

		case CTLRA_EVENT_GRID:
			pr = e->grid.pressed;
			if(mm->mode == MODE_GROUP) {
				/* select new group here */
				if(e->grid.pressed && e->grid.pos < 8) {
					mm->grp_id = e->grid.pos;
				}
			}
			if(mm->mode == MODE_PATTERN && pr) {
				if(mm->shift_pressed)
					mm->pattern_pad_id = e->grid.pos;
				else
					sequencer_toggle_step(sequencer, e->grid.pos);
			}
			mm->pads_pressed[e->grid.pos] = e->grid.pressed;
			break;
		default:
			break;
		};
	}

	ctlra_dev_light_flush(dev, 0);
}

void sighndlr(int signal)
{
	done = 1;
	printf("\n");
}

void remove_dev_func(struct ctlra_dev_t *dev, int unexpected_removal,
		     void *userdata)
{
	RtMidiOut *midiout = (RtMidiOut *)userdata;
	delete midiout;
}

int accept_dev_func(const struct ctlra_dev_info_t *info,
                    ctlra_event_func *event_func,
                    ctlra_feedback_func *feedback_func,
                    ctlra_remove_dev_func *remove_func,
                    void **userdata_for_event_func,
                    void *userdata)
{
	printf("daemon: accepting %s %s\n", info->vendor, info->device);

	*event_func = demo_event_func;
	*feedback_func = demo_feedback_func;
	*remove_func = remove_dev_func;

	/* MIDI output */
	RtMidiOut *midiout = new RtMidiOut(RtMidi::UNSPECIFIED, "Ctlra");
	unsigned int nPorts = midiout->getPortCount();
	if ( nPorts == 0 ) {
		std::cout << "No ports available!\n";
		return 0;
	}

	try {
		midiout->openVirtualPort(info->device);
	} catch (...) {
		printf("CtlrError: failed to open virtual midi port\n");
		return -1;
	}
	*userdata_for_event_func = midiout;

	return 1;
}

void seqEventCb(int frame, int note, int velocity, void* user_data )
{
	printf("%s: %d, %d : %d\n", __func__, frame, note, velocity);
}

#define SR 48000

int main()
{
	signal(SIGINT, sighndlr);

	sequencer = sequencer_new(SR);
	sequencer_set_callback(sequencer, seqEventCb, 0x0);
	sequencer_set_length(sequencer, SR * 1.2);
	sequencer_set_num_steps(sequencer, 16);
	sequencer_toggle_step(sequencer, 0);
	sequencer_toggle_step(sequencer, 4);
	sequencer_toggle_step(sequencer, 10);
	sequencer_toggle_step(sequencer, 12);

	mm_static.mode = MODE_PATTERN;

	struct ctlra_t *ctlra = ctlra_create(NULL);
	int num_devs = ctlra_probe(ctlra, accept_dev_func, 0x0);

	uint32_t sleep = SR / 128;

	while(!done) {
		ctlra_idle_iter(ctlra);
		sequencer_process( sequencer, 128 );
		usleep(1000 * 1000 / sleep);
	}

	ctlra_exit(ctlra);

	return 0;
}
<commit_msg>examples/seq: add 16 sequencers<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>

#include <iostream>
#include <cstdlib>

#include "RtMidi.h"

#include "ctlra.h"
#include "devices/ni_maschine_mikro_mk2.h"
#include "sequencer.h"

static volatile uint32_t done;
static struct ctlra_dev_t* dev;

static Sequencer *sequencers[16];

#define MODE_GROUP   0
#define MODE_PADS    1
#define MODE_PATTERN 2

void *midi_out_void;

struct col_t
{
	uint8_t green;
	uint8_t blue;
	uint8_t red;
};
static const struct col_t grp_col[] = {
	{0x00, 0x92,  254},
	{0xf9, 0x21, 0x00},
	{0x00, 0xf0, 0x00},
	{0x00, 0x00, 0xf0},
	{0xf0, 0xf0, 0xb0},
	{0x3f, 0x3f, 0xf0},
	{0xf0, 0x00, 0xf0},
	{0x00, 0xef, 0xd5},
	/* dark */
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
	{0x00, 0x00, 0x00},
};

uint32_t col_dim(const struct col_t *col, float bri)
{
	struct col_t c;
	c.red   = col->red   * bri;
	c.green = col->green * bri;
	c.blue  = col->blue  * bri;
	uint32_t intCol = *(uint32_t *)&c;
	return intCol;
}

static struct mm_t
{
	/* 0 Group   : Selects active group
	 * 1 Pads    : Plays different midi notes
	 * 2 Pattern : Sequence a single note
	 */
	uint8_t mode;
	uint8_t mode_prev;
	uint8_t shift_pressed;

	/* GROUP */
	uint8_t grp_id; /* 0 - 7, selected group */

	/* Pads */
	uint8_t pads_pressed[16];
	uint8_t pads_seq_play[16];

	/* Pattern */
	uint8_t pattern_pad_id; /* the pad that this pattern is playing */
} mm_static;

void demo_feedback_func(struct ctlra_dev_t *dev, void *d)
{
	/* group, pads, sequencer modes */
	struct mm_t *mm = &mm_static;
	const struct col_t *col = &grp_col[mm->grp_id];
	struct Sequencer *sequencer = sequencers[mm->pattern_pad_id];

	switch(mm->mode) {
	case MODE_PATTERN: {
		for(int i = 0; i < 16; i++) {
			int on = sequencer_get_step(sequencer, i);
			ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 + i,
					    col_dim(col, on ? 1.0 : 0.00));
		}
		int step = sequencer_get_current_step( sequencer );
		int on = sequencer_get_step(sequencer, step % 16);
		ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 + step,
				    on ?  0x007f7f7f : 0x000f0f0f );
		if(mm->shift_pressed) {
		ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 +
				    mm->pattern_pad_id, 0x00ffffff);
		}
		break;
		}
	case MODE_GROUP:
		for(int i = 0; i < 16; i++) {
			ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 + i,
					    col_dim(&grp_col[i],
						    i == mm->grp_id ? 1.0 : 0.05));
		}
		break;
	case MODE_PADS:
		/* pressed pads (manually - hence overrides */
		for(int i = 0; i < 16; i++) {
			ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 + i,
					    col_dim(&grp_col[mm->grp_id],
						    mm->pads_pressed[i] ? 1.0 : 0.02));
		}
		/* sequencer playbacks */
		for(int i = 0; i < 16; i++) {
			if(mm->pads_seq_play[i])
				ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_1 + i, 0xffffffff);
		}
		break;
	}

	ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PAD_MODE,
			    mm->mode == MODE_PADS ? 0xffffffff : 0x3);
	ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_PATTERN,
			    mm->mode == MODE_PATTERN ? 0xffffffff : 0x3);

	ctlra_dev_light_set(dev, NI_MASCHINE_MIKRO_MK2_LED_GROUP,
			    col_dim(&grp_col[mm->grp_id], 1.0));

	ctlra_dev_light_flush(dev, 1);
}

void demo_event_func(struct ctlra_dev_t* dev,
                     uint32_t num_events,
                     struct ctlra_event_t** events,
                     void *userdata)
{
	struct mm_t *mm = &mm_static;
	/* See below, a RtMidiOut instance is passed as the device's
	 * userdata pointer when registering the event_func */
	RtMidiOut *midiout = (RtMidiOut *)userdata;
	struct Sequencer *sequencer = sequencers[mm->pattern_pad_id];

	std::vector<unsigned char> message(3);

	for(uint32_t i = 0; i < num_events; i++) {
		const char *pressed = 0;
		struct ctlra_event_t *e = events[i];
		int pr = 0;
		switch(e->type) {
		case CTLRA_EVENT_BUTTON:
			message[0] = e->button.pressed ? 0x90 : 0x80;
			message[1] = 60 + e->button.id;
			message[2] = e->button.pressed ? 0x70 : 0;
			midiout->sendMessage( &message );
			printf("button %d\n", e->button.id);
			pr = e->button.pressed;
			switch(e->button.id) {
			case  7: mm->shift_pressed = pr; break;
			case 22: mm->mode = MODE_PATTERN; break;
			case 23: mm->mode = MODE_PADS; break;
			case 8: /* Group */
				if(pr) {
					mm->mode_prev = mm->mode;
					mm->mode = 0;
				} else {
					mm->mode = mm->mode_prev;
				}
				break;
			}
			break;

		case CTLRA_EVENT_ENCODER:
			break;

		case CTLRA_EVENT_SLIDER:
			message[0] = 0xb0;
			message[1] = e->slider.id;
			message[2] = int(e->slider.value * 127.f);
			midiout->sendMessage( &message );
			break;

		case CTLRA_EVENT_GRID:
			pr = e->grid.pressed;
			if(mm->mode == MODE_GROUP) {
				/* select new group here */
				if(e->grid.pressed && e->grid.pos < 8) {
					mm->grp_id = e->grid.pos;
				}
			}
			if(mm->mode == MODE_PATTERN && pr) {
				if(mm->shift_pressed) {
					mm->pattern_pad_id = e->grid.pos;
					//printf("new pattern pad id %d\n", mm->pattern_pad_id);
				}
				else
					sequencer_toggle_step(sequencer, e->grid.pos);
			}
			if(mm->mode == MODE_PADS && pr) {
				message[0] = 0x90;
				message[1] = 36 + 16 - e->grid.pos;
				message[2] = int(e->grid.pressed * 107.f);
				midiout->sendMessage( &message );
			}
			mm->pads_pressed[e->grid.pos] = e->grid.pressed;
			break;
		default:
			break;
		};
	}

	ctlra_dev_light_flush(dev, 0);
}

void sighndlr(int signal)
{
	done = 1;
	printf("\n");
}

void remove_dev_func(struct ctlra_dev_t *dev, int unexpected_removal,
		     void *userdata)
{
	RtMidiOut *midiout = (RtMidiOut *)userdata;
	delete midiout;
}

int accept_dev_func(const struct ctlra_dev_info_t *info,
                    ctlra_event_func *event_func,
                    ctlra_feedback_func *feedback_func,
                    ctlra_remove_dev_func *remove_func,
                    void **userdata_for_event_func,
                    void *userdata)
{
	printf("daemon: accepting %s %s\n", info->vendor, info->device);

	*event_func = demo_event_func;
	*feedback_func = demo_feedback_func;
	*remove_func = remove_dev_func;

	/* MIDI output */
	RtMidiOut *midiout = new RtMidiOut(RtMidi::UNSPECIFIED, "Ctlra");
	unsigned int nPorts = midiout->getPortCount();
	if ( nPorts == 0 ) {
		std::cout << "No ports available!\n";
		return 0;
	}

	try {
		midiout->openVirtualPort(info->device);
	} catch (...) {
		printf("CtlrError: failed to open virtual midi port\n");
		return -1;
	}
	*userdata_for_event_func = midiout;

	midi_out_void = midiout;

	return 1;
}

void seqEventCb(int frame, int note, int velocity, void* user_data )
{
	printf("%s: %d, %d : %d\n", __func__, frame, note, velocity);
	memset(mm_static.pads_seq_play, 0, sizeof(mm_static.pads_seq_play));
	mm_static.pads_seq_play[note] = velocity;

	RtMidiOut *midiout = (RtMidiOut *)midi_out_void;
	std::vector<unsigned char> message(3);
	message[0] = 0x90;
	message[1] = 36 + note;
	message[2] = velocity;
	midiout->sendMessage( &message );
}

#define SR 48000

int main()
{
	signal(SIGINT, sighndlr);

	for(int i = 0; i < 16; i++) {
		struct Sequencer *sequencer = sequencer_new(SR);
		sequencer_set_callback(sequencer, seqEventCb, 0x0);
		sequencer_set_length(sequencer, SR * 1.2);
		sequencer_set_num_steps(sequencer, 16);
		sequencer_set_note(sequencer, i);
		sequencers[i] = sequencer;
	}

	mm_static.mode = MODE_PATTERN;

	struct ctlra_t *ctlra = ctlra_create(NULL);
	int num_devs = ctlra_probe(ctlra, accept_dev_func, 0x0);

	uint32_t sleep = SR / 128;

	while(!done) {
		ctlra_idle_iter(ctlra);
		for(int i = 0; i < 16; i++) {
			struct Sequencer *sequencer = sequencers[i];
			sequencer_process( sequencer, 128 );
		}
		usleep(1000 * 1000 / sleep);
	}

	ctlra_exit(ctlra);

	return 0;
}
<|endoftext|>


<commit_before>//=============================================================================================================
/**
* @file     main.cpp
* @author   Jana Kiesel <jana.kiesel@tu-ilmenau.de>
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     November, 2015
* @section  LICENSE
*
* Copyright (C) 2015, Jana Kiesel, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    Example to test the warp class
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

//#include <fstream>
#include <iostream>
#include <cstdlib>
#include <time.h>

#include <utils/warp.h>
#include <fiff/fiff.h>
#include <fiff/fiff_dig_point_set.h>
#include <mne/mne_bem.h>

#include <QFile>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace UTILSLIB;
using namespace FIFFLIB;

using namespace std;

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/

#define MAXBUFSIZE  ((int) 1e6)

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

//    Matrix<double,6,3> sLm;
//    sLm <<  1,1,1,
//            2,1,1,
//            3,1,1,
//            1,2,1,
//            2,2,1,
//            3,2,1;
//    std::cout << "Here is the matrix sLm:" << std::endl << sLm << std::endl;

//    Matrix<double,6,3> dLm;
//    dLm <<  1,1,2,
//            2,1,3,
//            3,1,2,
//            1,2,2,
//            2,2,3,
//            3,2,2;

//    Matrix<double,16,3> sVert;
//    sVert <<1.0,0.5,1,
//            1.5,0.5,1,
//            2.0,0.5,1,
//            2.3,0.5,1,
//            2.7,0.5,1,
//            3.0,0.5,1,
//            3.5,0.5,1,
//            4.0,0.5,1,
//            1.0,1,1,
//            1.5,1,1,
//            2.0,1,1,
//            2.3,1,1,
//            2.7,1,1,
//            3.0,1,1,
//            3.5,1,1,
//            4.0,1,1;;

    //
    // Read Electrode Positions from fiff raw
    //
//    QFile t_fileRaw("./MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
//    FiffRawData raw(t_fileRaw);
//    QList<FiffChInfo> ChannelInfo= raw.info.chs;

//    QList<QVector<double>> tempElecInfo;
//    QList<QString> ElecChanName;
//    for (int i=0; i<ChannelInfo.length();i++)
//    {
//        if (ChannelInfo[i].kind==2)
//        {
//            QVector<double> temp;
//            ElecChanName.append(ChannelInfo[i].ch_name);
//            temp.append(ChannelInfo[i].loc(0,0));
//            temp.append(ChannelInfo[i].loc(1,0));
//            temp.append(ChannelInfo[i].loc(2,0));
//            tempElecInfo.append(temp);
//        }
//    }
//    MatrixXd ElecPos(tempElecInfo.length(),3);
//    for (int i=0; i<tempElecInfo.length();i++)
//    {
//        ElecPos(i,0)=tempElecInfo[i][0];
//        ElecPos(i,1)=tempElecInfo[i][1];
//        ElecPos(i,2)=tempElecInfo[i][2];
//    }

    //
    // Read Electrode Positions from fiff (digitizer points)
    //

    QFile t_fileElec("./MNE-sample-data/warping/AVG4-0Years_GSN128.fif");
//    QList<FiffDigPoint> dig = FiffDigPoint::read(t_fileElec);
    FiffDigPointSet digset(t_fileElec);

        QList<QVector<float>> tempElecInfo;
        QList<int> ElecChanName;
        for (int i = 0; i < digset.size(); ++i)
        {
            if (digset[i].kind == 3)
            {
                QVector<float> temp;
                ElecChanName.append(digset[i].ident);
                temp.append(digset[i].r[0]);
                temp.append(digset[i].r[1]);
                temp.append(digset[i].r[2]);
                tempElecInfo.append(temp);
            }
        }
        MatrixXf ElecPos(tempElecInfo.length(), 3);
        for (int i = 0; i < tempElecInfo.length(); ++i)
        {
            ElecPos(i,0) = tempElecInfo[i][0];
            ElecPos(i,1) = tempElecInfo[i][1];
            ElecPos(i,2) = tempElecInfo[i][2];
        }

//    std::cout << "Here is the matrix ElecPos:" << std::endl << ElecPos << std::endl;

    //
    // read electrode positions from Database
    //
//    QString electrodeFileName= "./MNE-sample-data/MriDatabase/FirstYear/Sources/Electrodes/AVG3-0Months_10-5_Electrodes.txt";
//    Matrix<double, Dynamic ,3> ElecPos = test.readsLm(electrodeFileName);
//    std::cout << "Here is the matrix ElecPos:" << std::endl << ElecPos << std::endl;

    //
    //Read BEM from fiff
    //
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif");
//    MNELIB::MNEBem t_Bem (t_fileBem) ;

    //
    // Read Transformation
    //

    QFile t_fileTrans("./MNE-sample-data/warping/AVG4-0Years_GSN128-trans.fif");
    FiffCoordTrans t_Trans (t_fileTrans);
    ElecPos=t_Trans.apply_trans(ElecPos);

//    //
//    // prepare warp
//    //
//    MatrixXd sLm=ElecPos;
//    MatrixXd random(ElecPos.rows(),3);
//    srand(time(NULL));
//    for (int i=0;i<ElecPos.rows();i++)
//    {

//        for (int j=0; j<3;j++)
//        {
//            random(i,j)=rand();
//            random(i,j)/=RAND_MAX;
//            random(i,j)*=0.06;
//            random(i,j)-=0.03;
//            //            random(i,j)=0.005*(rand()/RAND_MAX);
//        }
//    }
////    std::cout << "Here are the first row of the matrix random:" << std::endl << random.topRows(9) << std::endl;
//    MatrixXd dLm=sLm+random;
//    MNELIB::MNEBemSurface skin=t_Bem[0];
//    MatrixXd sVert=skin.rr.cast<double>();

//    std::cout << "Here are the first row of the matrix skin.rr bevor warp:" << std::endl << skin.rr.topRows(9) << std::endl;

//    //
//    // calculate Warp
//    //
//    Warp test;
//    MatrixXd wVert(sVert.rows(),3);
//    wVert = test.calculate(sLm, dLm, sVert);

//    //
//    // WRITE NEW VERTICES BACK TO BEM
//    //
//    skin.rr=wVert.cast<float>();
//    skin.addVertexNormals();

//    std::cout << "Here are the first row of the matrix skin.rr after warp:" << std::endl << skin.rr.topRows(9) << std::endl;
////    std::cout << "Here is the first row of the final matrix skin.tris:" << std::endl << skin.tris.topRows(9) << std::endl;
////    std::cout << "Here is the last row of the final matrix skin.tris:" << std::endl << skin.tris.bottomRows(1) << std::endl;

//    MNELIB::MNEBem t_BemWarpedA;
//    t_BemWarpedA<<skin;
//    QFile t_fileBemWarped("./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem-warped.fif");
//    t_BemWarpedA.write(t_fileBemWarped);
//    t_fileBemWarped.close();

//    MNELIB::MNEBem t_BemWarpedB (t_fileBemWarped) ;
//    MNELIB::MNEBemSurface skinWarped=t_BemWarpedB[0];
    return a.exec();
}

<commit_msg>[LIB-49] Clean up testWarp/main.cpp<commit_after>//=============================================================================================================
/**
* @file     main.cpp
* @author   Jana Kiesel <jana.kiesel@tu-ilmenau.de>
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     November, 2015
* @section  LICENSE
*
* Copyright (C) 2015, Jana Kiesel, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    Example to test the warp class
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

//#include <fstream>
#include <iostream>
#include <cstdlib>
#include <time.h>

#include <utils/warp.h>
#include <fiff/fiff.h>
#include <fiff/fiff_dig_point_set.h>
#include <mne/mne_bem.h>

#include <QFile>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace UTILSLIB;
using namespace FIFFLIB;

using namespace std;

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/

#define MAXBUFSIZE  ((int) 1e6)

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //
    // Destination Landmarks:
    //

    // Read Electrode Positions from fiff raw
//    QFile t_fileRaw("./MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
//    FiffRawData raw(t_fileRaw);
//    QList<FiffChInfo> ChannelInfo= raw.info.chs;

//    QList<QVector<double>> tempElecInfo;
//    QList<QString> ElecChanName;
//    for (int i=0; i<ChannelInfo.length();i++)
//    {
//        if (ChannelInfo[i].kind==2)
//        {
//            QVector<double> temp;
//            ElecChanName.append(ChannelInfo[i].ch_name);
//            temp.append(ChannelInfo[i].loc(0,0));
//            temp.append(ChannelInfo[i].loc(1,0));
//            temp.append(ChannelInfo[i].loc(2,0));
//            tempElecInfo.append(temp);
//        }
//    }
//    MatrixXd ElecPos(tempElecInfo.length(),3);
//    for (int i=0; i<tempElecInfo.length();i++)
//    {
//        ElecPos(i,0)=tempElecInfo[i][0];
//        ElecPos(i,1)=tempElecInfo[i][1];
//        ElecPos(i,2)=tempElecInfo[i][2];
//    }

    //Read Electrode Positions from fiff (digitizer points)
//    QFile t_fileElec("./MNE-sample-data/warping/AVG4-0Years_GSN128.fif");
    QFile t_fileElec("D:/Studium/Master/Masterarbeit/Daten/4889503/ID_4889503_act/bem/4889503-5120-5120-5120-bem.fif");

    FiffDigPointSet digset(t_fileElec);

        QList<QVector<float>> tempElecInfo;
        QList<int> ElecChanName;
        for (int i = 0; i < digset.size(); ++i)
        {
            if (digset[i].kind == 3)
            {
                QVector<float> temp;
                ElecChanName.append(digset[i].ident);
                temp.append(digset[i].r[0]);
                temp.append(digset[i].r[1]);
                temp.append(digset[i].r[2]);
                tempElecInfo.append(temp);
            }
        }
        MatrixXf ElecPos(tempElecInfo.length(), 3);
        for (int i = 0; i < tempElecInfo.length(); ++i)
        {
            ElecPos(i,0) = tempElecInfo[i][0];
            ElecPos(i,1) = tempElecInfo[i][1];
            ElecPos(i,2) = tempElecInfo[i][2];
        }

//    std::cout << "Here is the matrix ElecPos:" << std::endl << ElecPos << std::endl;

    //
    // source Landmarks:
    //

    // read average electrode positions from Database
    //    QString electrodeFileName= "./MNE-sample-data/MriDatabase/FirstYear/Sources/Electrodes/AVG3-0Months_10-5_Electrodes.txt";
//    Matrix<double, Dynamic ,3> ElecPos = test.readsLm(electrodeFileName);
//    std::cout << "Here is the matrix ElecPos:" << std::endl << ElecPos << std::endl;

    //
    // Source Bem:
    //

    // Read BEM from fiff
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif");
//    MNELIB::MNEBem t_Bem (t_fileBem) ;

    //
    // Read and apply Transformation of source landmarks (source)
    //

    QFile t_fileTrans("./MNE-sample-data/warping/AVG4-0Years_GSN128-trans.fif");
    FiffCoordTrans t_Trans (t_fileTrans);
    ElecPos=t_Trans.apply_trans(ElecPos);

//    //
//    // calculate Warp
//    //
//    Warp test;
//    MatrixXd wVert(sVert.rows(),3);
//    wVert = test.calculate(sLm, dLm, sVert);

//    //
//    // WRITE NEW VERTICES BACK TO BEM
//    //
//    skin.rr=wVert.cast<float>();
//    skin.addVertexNormals();

//    std::cout << "Here are the first row of the matrix skin.rr after warp:" << std::endl << skin.rr.topRows(9) << std::endl;
////    std::cout << "Here is the first row of the final matrix skin.tris:" << std::endl << skin.tris.topRows(9) << std::endl;
////    std::cout << "Here is the last row of the final matrix skin.tris:" << std::endl << skin.tris.bottomRows(1) << std::endl;

//    MNELIB::MNEBem t_BemWarpedA;
//    t_BemWarpedA<<skin;
//    QFile t_fileBemWarped("./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem-warped.fif");
//    t_BemWarpedA.write(t_fileBemWarped);
//    t_fileBemWarped.close();

//    MNELIB::MNEBem t_BemWarpedB (t_fileBemWarped) ;
//    MNELIB::MNEBemSurface skinWarped=t_BemWarpedB[0];
    return a.exec();
}
<|endoftext|>


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

#ifndef UNOTOOLS_INC_UNOTOOLS_DESKTOPTERMINATIONOBSERVER_HXX
#define UNOTOOLS_INC_UNOTOOLS_DESKTOPTERMINATIONOBSERVER_HXX

/** === begin UNO includes === **/
/** === end UNO includes === **/

//........................................................................
namespace utl
{
//........................................................................

    //====================================================================
    //= ITerminationListener
    //====================================================================
    /** non-UNO version of the <type scope="com.sun.star.frame">XTerminateListener</type>
    */
    class ITerminationListener
    {
    public:
        virtual bool    queryTermination() const = 0;
        virtual void    notifyTermination() = 0;
    };

    //====================================================================
    //= DesktopTerminationObserver
    //====================================================================
    /** a class which allows non-UNO components to observe the desktop (aka application)
        for it's shutdown
    */
    class DesktopTerminationObserver
    {
    public:
        /** registers a listener which should be notified when the desktop terminates
            (which means the application is shutting down)
        */
        static void    registerTerminationListener( ITerminationListener* _pListener );

        /** revokes a termination listener
        */
        static void    revokeTerminationListener( ITerminationListener* _pListener );

    private:
        DesktopTerminationObserver();   // never implemented, only static methods
    };

//........................................................................
} // namespace utl
//........................................................................

#endif // UNOTOOLS_INC_UNOTOOLS_DESKTOPTERMINATIONOBSERVER_HXX

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

#ifndef UNOTOOLS_INC_UNOTOOLS_DESKTOPTERMINATIONOBSERVER_HXX
#define UNOTOOLS_INC_UNOTOOLS_DESKTOPTERMINATIONOBSERVER_HXX

/** === begin UNO includes === **/
/** === end UNO includes === **/

//........................................................................
namespace utl
{
//........................................................................

    //====================================================================
    //= ITerminationListener
    //====================================================================
    /** non-UNO version of the <type scope="com.sun.star.frame">XTerminateListener</type>
    */
    class ITerminationListener
    {
    public:
        virtual bool    queryTermination() const = 0;
        virtual void    notifyTermination() = 0;
    };

    //====================================================================
    //= DesktopTerminationObserver
    //====================================================================
    /** a class which allows non-UNO components to observe the desktop (aka application)
        for it's shutdown
    */
    class UNOTOOLS_DLLPUBLIC DesktopTerminationObserver
    {
    public:
        /** registers a listener which should be notified when the desktop terminates
            (which means the application is shutting down)
        */
        static void    registerTerminationListener( ITerminationListener* _pListener );

        /** revokes a termination listener
        */
        static void    revokeTerminationListener( ITerminationListener* _pListener );

    private:
        DesktopTerminationObserver();   // never implemented, only static methods
    };

//........................................................................
} // namespace utl
//........................................................................

#endif // UNOTOOLS_INC_UNOTOOLS_DESKTOPTERMINATIONOBSERVER_HXX

<|endoftext|>