<commit_before>/*
 * Asynchronous local file access.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_file.hxx"
#include "istream_buffer.hxx"
#include "buffered_io.hxx"
#include "fd_util.h"
#include "gerrno.h"
#include "fb_pool.hxx"
#include "util/Cast.hxx"

#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <limits.h>

#include <event.h>

#ifndef O_CLOEXEC
enum {
    O_CLOEXEC = 0,
};
#endif

/**
 * If EAGAIN occurs (on NFS), we try again after 100ms.  We can't
 * check EV_READ, because the kernel always indicates VFS files as
 * "readable without blocking".
 */
static const struct timeval file_retry_timeout = {
    .tv_sec = 0,
    .tv_usec = 100000,
};

struct file {
    struct istream stream;
    int fd;

    enum istream_direct fd_type;

    /**
     * A timer to retry reading after EAGAIN.
     */
    struct event event;

    off_t rest;
    struct fifo_buffer *buffer;
    const char *path;
};

static void
file_close(struct file *file)
{
    if (file->fd >= 0) {
        evtimer_del(&file->event);

        close(file->fd);
        file->fd = -1;
    }
}

static void
file_destroy(struct file *file)
{
    file_close(file);

    if (file->buffer != nullptr) {
        fb_pool_free(file->buffer);
        file->buffer = nullptr;
    }
}

static void
file_abort(struct file *file, GError *error)
{
    file_destroy(file);

    istream_deinit_abort(&file->stream, error);
}

/**
 * @return the number of bytes still in the buffer
 */
static size_t
istream_file_invoke_data(struct file *file)
{
    return istream_buffer_consume(&file->stream, file->buffer);
}

static void
istream_file_eof_detected(struct file *file)
{
    assert(file->fd >= 0);

    file_destroy(file);

    istream_deinit_eof(&file->stream);
}

static inline size_t
istream_file_max_read(const struct file *file)
{
    if (file->rest != (off_t)-1 && file->rest < (off_t)INT_MAX)
        return (size_t)file->rest;
    else
        return INT_MAX;
}

static void
istream_file_try_data(struct file *file)
{
    size_t rest = 0;

    if (file->buffer == nullptr) {
        if (file->rest != 0)
            file->buffer = fb_pool_alloc();
    } else {
        const size_t available = fifo_buffer_available(file->buffer);
        if (available > 0) {
            rest = istream_file_invoke_data(file);
            if (rest == available)
                /* not a single byte was consumed: we may have been
                   closed, and we must bail out now */
                return;
        }
    }

    if (file->rest == 0) {
        if (rest == 0)
            istream_file_eof_detected(file);
        return;
    }

    ssize_t nbytes = read_to_buffer(file->fd, file->buffer,
                                    istream_file_max_read(file));
    if (nbytes == 0) {
        if (file->rest == (off_t)-1) {
            file->rest = 0;
            if (rest == 0)
                istream_file_eof_detected(file);
        } else {
            GError *error =
                g_error_new(g_file_error_quark(), 0,
                            "premature end of file in '%s'", file->path);
            file_abort(file, error);
        }
        return;
    } else if (nbytes == -1) {
        GError *error =
            g_error_new(errno_quark(), errno,
                        "failed to read from '%s': %s",
                        file->path, strerror(errno));
        file_abort(file, error);
        return;
    } else if (nbytes > 0 && file->rest != (off_t)-1) {
        file->rest -= (off_t)nbytes;
        assert(file->rest >= 0);
    }

    assert(!fifo_buffer_empty(file->buffer));

    rest = istream_file_invoke_data(file);
    if (rest == 0 && file->rest == 0)
        istream_file_eof_detected(file);
}

static void
istream_file_try_direct(struct file *file)
{
    assert(file->stream.handler->direct != nullptr);

    /* first consume the rest of the buffer */
    if (file->buffer != nullptr && istream_file_invoke_data(file) > 0)
        return;

    if (file->rest == 0) {
        istream_file_eof_detected(file);
        return;
    }

    ssize_t nbytes = istream_invoke_direct(&file->stream,
                                           file->fd_type, file->fd,
                                           istream_file_max_read(file));
    if (nbytes == ISTREAM_RESULT_CLOSED)
        /* this stream was closed during the direct() callback */
        return;

    if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) {
        /* -2 means the callback wasn't able to consume any data right
           now */
        if (nbytes > 0 && file->rest != (off_t)-1) {
            file->rest -= (off_t)nbytes;
            assert(file->rest >= 0);
            if (file->rest == 0)
                istream_file_eof_detected(file);
        }
    } else if (nbytes == ISTREAM_RESULT_EOF) {
        if (file->rest == (off_t)-1) {
            istream_file_eof_detected(file);
        } else {
            GError *error =
                g_error_new(g_file_error_quark(), 0,
                            "premature end of file in '%s'", file->path);
            file_abort(file, error);
        }
    } else if (errno == EAGAIN) {
        /* this should only happen for splice(SPLICE_F_NONBLOCK) from
           NFS files - unfortunately we cannot use EV_READ here, so we
           just install a timer which retries after 100ms */

        evtimer_add(&file->event, &file_retry_timeout);
    } else {
        /* XXX */
        GError *error =
            g_error_new(errno_quark(), errno,
                        "failed to read from '%s': %s",
                        file->path, strerror(errno));
        file_abort(file, error);
    }
}

static void
file_try_read(struct file *file)
{
    if (istream_check_direct(&file->stream, file->fd_type))
        istream_file_try_direct(file);
    else
        istream_file_try_data(file);
}

static void
file_event_callback(gcc_unused int fd, gcc_unused short event,
                    void *ctx)
{
    struct file *file = (struct file *)ctx;

    file_try_read(file);
}

/*
 * istream implementation
 *
 */

static inline struct file *
istream_to_file(struct istream *istream)
{
    return &ContainerCast2(*istream, &file::stream);
}

static off_t
istream_file_available(struct istream *istream, bool partial)
{
    struct file *file = istream_to_file(istream);
    off_t available = 0;

    if (file->rest != (off_t)-1)
        available = file->rest;
    else if (!partial)
        return (off_t)-1;
    else
        available = 0;

    if (file->buffer != nullptr)
        available += fifo_buffer_available(file->buffer);

    return available;
}

static off_t
istream_file_skip(struct istream *istream, off_t length)
{
    struct file *file = istream_to_file(istream);

    evtimer_del(&file->event);

    if (file->rest == (off_t)-1)
        return (off_t)-1;

    if (length == 0)
        return 0;

    if (file->buffer != nullptr)
        /* clear the buffer; later we could optimize this function by
           flushing only the skipped number of bytes */
        fifo_buffer_clear(file->buffer);

    if (length >= file->rest) {
        /* skip beyond EOF */

        length = file->rest;
        file->rest = 0;
    } else {
        /* seek the file descriptor */

        off_t ret = lseek(file->fd, length, SEEK_CUR);
        if (ret < 0)
            return -1;
        file->rest -= length;
    }

    return length;
}

static void
istream_file_read(struct istream *istream)
{
    struct file *file = istream_to_file(istream);

    assert(file->stream.handler != nullptr);

    evtimer_del(&file->event);

    file_try_read(file);
}

static int
istream_file_as_fd(struct istream *istream)
{
    struct file *file = istream_to_file(istream);
    int fd = file->fd;

    evtimer_del(&file->event);
    istream_deinit(&file->stream);

    return fd;
}

static void
istream_file_close(struct istream *istream)
{
    struct file *file = istream_to_file(istream);

    file_destroy(file);

    istream_deinit(&file->stream);
}

static const struct istream_class istream_file = {
    .available = istream_file_available,
    .skip = istream_file_skip,
    .read = istream_file_read,
    .as_fd = istream_file_as_fd,
    .close = istream_file_close,
};

/*
 * constructor and public methods
 *
 */

struct istream *
istream_file_fd_new(struct pool *pool, const char *path,
                    int fd, enum istream_direct fd_type, off_t length)
{
    struct file *file;

    assert(fd >= 0);
    assert(length >= -1);

    file = (struct file*)istream_new(pool, &istream_file, sizeof(*file));
    file->fd = fd;
    file->fd_type = fd_type;
    file->rest = length;
    file->buffer = nullptr;
    file->path = path;

    evtimer_set(&file->event, file_event_callback, file);

    return istream_struct_cast(&file->stream);
}

struct istream *
istream_file_stat_new(struct pool *pool, const char *path, struct stat *st,
                      GError **error_r)
{
    assert(path != nullptr);
    assert(st != nullptr);

    int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0);
    if (fd < 0) {
        set_error_errno(error_r);
        g_prefix_error(error_r, "Failed to open %s: ", path);
        return nullptr;
    }

    if (fstat(fd, st) < 0) {
        set_error_errno(error_r);
        g_prefix_error(error_r, "Failed to stat %s: ", path);
        close(fd);
        return nullptr;
    }

    enum istream_direct fd_type = ISTREAM_FILE;
    off_t size = st->st_size;

    if (S_ISCHR(st->st_mode)) {
        fd_type = ISTREAM_CHARDEV;
        size = -1;
    }

    return istream_file_fd_new(pool, path, fd, fd_type, size);
}

struct istream *
istream_file_new(struct pool *pool, const char *path, off_t length,
                 GError **error_r)
{
    assert(length >= -1);

    int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0);
    if (fd < 0) {
        set_error_errno(error_r);
        g_prefix_error(error_r, "Failed to open %s: ", path);
        return nullptr;
    }

    return istream_file_fd_new(pool, path, fd, ISTREAM_FILE, length);
}

int
istream_file_fd(struct istream *istream)
{
    assert(istream != nullptr);
    assert(istream->cls == &istream_file);

    struct file *file = istream_to_file(istream);

    assert(file->fd >= 0);

    return file->fd;
}

bool
istream_file_set_range(struct istream *istream, off_t start, off_t end)
{
    assert(istream != nullptr);
    assert(istream->cls == &istream_file);
    assert(start >= 0);
    assert(end >= start);

    struct file *file = istream_to_file(istream);
    assert(file->fd >= 0);
    assert(file->rest >= 0);
    assert(file->buffer == nullptr);
    assert(end <= file->rest);

    if (start > 0 && lseek(file->fd, start, SEEK_CUR) < 0)
        return false;

    file->rest = end - start;
    return true;
}
<commit_msg>istream_file: remove unused fallback macro O_CLOEXEC<commit_after>/*
 * Asynchronous local file access.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_file.hxx"
#include "istream_buffer.hxx"
#include "buffered_io.hxx"
#include "fd_util.h"
#include "gerrno.h"
#include "fb_pool.hxx"
#include "util/Cast.hxx"

#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <limits.h>

#include <event.h>

/**
 * If EAGAIN occurs (on NFS), we try again after 100ms.  We can't
 * check EV_READ, because the kernel always indicates VFS files as
 * "readable without blocking".
 */
static const struct timeval file_retry_timeout = {
    .tv_sec = 0,
    .tv_usec = 100000,
};

struct file {
    struct istream stream;
    int fd;

    enum istream_direct fd_type;

    /**
     * A timer to retry reading after EAGAIN.
     */
    struct event event;

    off_t rest;
    struct fifo_buffer *buffer;
    const char *path;
};

static void
file_close(struct file *file)
{
    if (file->fd >= 0) {
        evtimer_del(&file->event);

        close(file->fd);
        file->fd = -1;
    }
}

static void
file_destroy(struct file *file)
{
    file_close(file);

    if (file->buffer != nullptr) {
        fb_pool_free(file->buffer);
        file->buffer = nullptr;
    }
}

static void
file_abort(struct file *file, GError *error)
{
    file_destroy(file);

    istream_deinit_abort(&file->stream, error);
}

/**
 * @return the number of bytes still in the buffer
 */
static size_t
istream_file_invoke_data(struct file *file)
{
    return istream_buffer_consume(&file->stream, file->buffer);
}

static void
istream_file_eof_detected(struct file *file)
{
    assert(file->fd >= 0);

    file_destroy(file);

    istream_deinit_eof(&file->stream);
}

static inline size_t
istream_file_max_read(const struct file *file)
{
    if (file->rest != (off_t)-1 && file->rest < (off_t)INT_MAX)
        return (size_t)file->rest;
    else
        return INT_MAX;
}

static void
istream_file_try_data(struct file *file)
{
    size_t rest = 0;

    if (file->buffer == nullptr) {
        if (file->rest != 0)
            file->buffer = fb_pool_alloc();
    } else {
        const size_t available = fifo_buffer_available(file->buffer);
        if (available > 0) {
            rest = istream_file_invoke_data(file);
            if (rest == available)
                /* not a single byte was consumed: we may have been
                   closed, and we must bail out now */
                return;
        }
    }

    if (file->rest == 0) {
        if (rest == 0)
            istream_file_eof_detected(file);
        return;
    }

    ssize_t nbytes = read_to_buffer(file->fd, file->buffer,
                                    istream_file_max_read(file));
    if (nbytes == 0) {
        if (file->rest == (off_t)-1) {
            file->rest = 0;
            if (rest == 0)
                istream_file_eof_detected(file);
        } else {
            GError *error =
                g_error_new(g_file_error_quark(), 0,
                            "premature end of file in '%s'", file->path);
            file_abort(file, error);
        }
        return;
    } else if (nbytes == -1) {
        GError *error =
            g_error_new(errno_quark(), errno,
                        "failed to read from '%s': %s",
                        file->path, strerror(errno));
        file_abort(file, error);
        return;
    } else if (nbytes > 0 && file->rest != (off_t)-1) {
        file->rest -= (off_t)nbytes;
        assert(file->rest >= 0);
    }

    assert(!fifo_buffer_empty(file->buffer));

    rest = istream_file_invoke_data(file);
    if (rest == 0 && file->rest == 0)
        istream_file_eof_detected(file);
}

static void
istream_file_try_direct(struct file *file)
{
    assert(file->stream.handler->direct != nullptr);

    /* first consume the rest of the buffer */
    if (file->buffer != nullptr && istream_file_invoke_data(file) > 0)
        return;

    if (file->rest == 0) {
        istream_file_eof_detected(file);
        return;
    }

    ssize_t nbytes = istream_invoke_direct(&file->stream,
                                           file->fd_type, file->fd,
                                           istream_file_max_read(file));
    if (nbytes == ISTREAM_RESULT_CLOSED)
        /* this stream was closed during the direct() callback */
        return;

    if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) {
        /* -2 means the callback wasn't able to consume any data right
           now */
        if (nbytes > 0 && file->rest != (off_t)-1) {
            file->rest -= (off_t)nbytes;
            assert(file->rest >= 0);
            if (file->rest == 0)
                istream_file_eof_detected(file);
        }
    } else if (nbytes == ISTREAM_RESULT_EOF) {
        if (file->rest == (off_t)-1) {
            istream_file_eof_detected(file);
        } else {
            GError *error =
                g_error_new(g_file_error_quark(), 0,
                            "premature end of file in '%s'", file->path);
            file_abort(file, error);
        }
    } else if (errno == EAGAIN) {
        /* this should only happen for splice(SPLICE_F_NONBLOCK) from
           NFS files - unfortunately we cannot use EV_READ here, so we
           just install a timer which retries after 100ms */

        evtimer_add(&file->event, &file_retry_timeout);
    } else {
        /* XXX */
        GError *error =
            g_error_new(errno_quark(), errno,
                        "failed to read from '%s': %s",
                        file->path, strerror(errno));
        file_abort(file, error);
    }
}

static void
file_try_read(struct file *file)
{
    if (istream_check_direct(&file->stream, file->fd_type))
        istream_file_try_direct(file);
    else
        istream_file_try_data(file);
}

static void
file_event_callback(gcc_unused int fd, gcc_unused short event,
                    void *ctx)
{
    struct file *file = (struct file *)ctx;

    file_try_read(file);
}

/*
 * istream implementation
 *
 */

static inline struct file *
istream_to_file(struct istream *istream)
{
    return &ContainerCast2(*istream, &file::stream);
}

static off_t
istream_file_available(struct istream *istream, bool partial)
{
    struct file *file = istream_to_file(istream);
    off_t available = 0;

    if (file->rest != (off_t)-1)
        available = file->rest;
    else if (!partial)
        return (off_t)-1;
    else
        available = 0;

    if (file->buffer != nullptr)
        available += fifo_buffer_available(file->buffer);

    return available;
}

static off_t
istream_file_skip(struct istream *istream, off_t length)
{
    struct file *file = istream_to_file(istream);

    evtimer_del(&file->event);

    if (file->rest == (off_t)-1)
        return (off_t)-1;

    if (length == 0)
        return 0;

    if (file->buffer != nullptr)
        /* clear the buffer; later we could optimize this function by
           flushing only the skipped number of bytes */
        fifo_buffer_clear(file->buffer);

    if (length >= file->rest) {
        /* skip beyond EOF */

        length = file->rest;
        file->rest = 0;
    } else {
        /* seek the file descriptor */

        off_t ret = lseek(file->fd, length, SEEK_CUR);
        if (ret < 0)
            return -1;
        file->rest -= length;
    }

    return length;
}

static void
istream_file_read(struct istream *istream)
{
    struct file *file = istream_to_file(istream);

    assert(file->stream.handler != nullptr);

    evtimer_del(&file->event);

    file_try_read(file);
}

static int
istream_file_as_fd(struct istream *istream)
{
    struct file *file = istream_to_file(istream);
    int fd = file->fd;

    evtimer_del(&file->event);
    istream_deinit(&file->stream);

    return fd;
}

static void
istream_file_close(struct istream *istream)
{
    struct file *file = istream_to_file(istream);

    file_destroy(file);

    istream_deinit(&file->stream);
}

static const struct istream_class istream_file = {
    .available = istream_file_available,
    .skip = istream_file_skip,
    .read = istream_file_read,
    .as_fd = istream_file_as_fd,
    .close = istream_file_close,
};

/*
 * constructor and public methods
 *
 */

struct istream *
istream_file_fd_new(struct pool *pool, const char *path,
                    int fd, enum istream_direct fd_type, off_t length)
{
    struct file *file;

    assert(fd >= 0);
    assert(length >= -1);

    file = (struct file*)istream_new(pool, &istream_file, sizeof(*file));
    file->fd = fd;
    file->fd_type = fd_type;
    file->rest = length;
    file->buffer = nullptr;
    file->path = path;

    evtimer_set(&file->event, file_event_callback, file);

    return istream_struct_cast(&file->stream);
}

struct istream *
istream_file_stat_new(struct pool *pool, const char *path, struct stat *st,
                      GError **error_r)
{
    assert(path != nullptr);
    assert(st != nullptr);

    int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0);
    if (fd < 0) {
        set_error_errno(error_r);
        g_prefix_error(error_r, "Failed to open %s: ", path);
        return nullptr;
    }

    if (fstat(fd, st) < 0) {
        set_error_errno(error_r);
        g_prefix_error(error_r, "Failed to stat %s: ", path);
        close(fd);
        return nullptr;
    }

    enum istream_direct fd_type = ISTREAM_FILE;
    off_t size = st->st_size;

    if (S_ISCHR(st->st_mode)) {
        fd_type = ISTREAM_CHARDEV;
        size = -1;
    }

    return istream_file_fd_new(pool, path, fd, fd_type, size);
}

struct istream *
istream_file_new(struct pool *pool, const char *path, off_t length,
                 GError **error_r)
{
    assert(length >= -1);

    int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0);
    if (fd < 0) {
        set_error_errno(error_r);
        g_prefix_error(error_r, "Failed to open %s: ", path);
        return nullptr;
    }

    return istream_file_fd_new(pool, path, fd, ISTREAM_FILE, length);
}

int
istream_file_fd(struct istream *istream)
{
    assert(istream != nullptr);
    assert(istream->cls == &istream_file);

    struct file *file = istream_to_file(istream);

    assert(file->fd >= 0);

    return file->fd;
}

bool
istream_file_set_range(struct istream *istream, off_t start, off_t end)
{
    assert(istream != nullptr);
    assert(istream->cls == &istream_file);
    assert(start >= 0);
    assert(end >= start);

    struct file *file = istream_to_file(istream);
    assert(file->fd >= 0);
    assert(file->rest >= 0);
    assert(file->buffer == nullptr);
    assert(end <= file->rest);

    if (start > 0 && lseek(file->fd, start, SEEK_CUR) < 0)
        return false;

    file->rest = end - start;
    return true;
}
<|endoftext|>


<commit_before>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/***********************************************************************************
**
** GLShader.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "stdafx.h"
//----------------------------------------------------------------------------------
CDeathShader g_DeathShader;
CColorizerShader g_ColorizerShader;
CColorizerShader g_FontColorizerShader;
CColorizerShader g_LightColorizerShader;
//----------------------------------------------------------------------------------
void UnuseShader()
{
	WISPFUN_DEBUG("c_uns_sdr");
	glUseProgramObjectARB(0);
	ShaderColorTable = 0;
	g_ShaderDrawMode = 0;
}
//----------------------------------------------------------------------------------
//-----------------------------------CGLShader--------------------------------------
//----------------------------------------------------------------------------------
CGLShader::CGLShader()
{
	WISPFUN_DEBUG("c32_f1");
}
//----------------------------------------------------------------------------------
bool CGLShader::Init(const char *vertexShaderData, const char *fragmentShaderData)
{
	if (vertexShaderData != NULL && fragmentShaderData != NULL)
	{
		m_Shader = glCreateProgramObjectARB();

		m_VertexShader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
		glShaderSourceARB(m_VertexShader, 1, (const GLcharARB**)&vertexShaderData, NULL);
		glCompileShaderARB(m_VertexShader);
		glAttachObjectARB(m_Shader, m_VertexShader);

		m_FragmentShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
		glShaderSourceARB(m_FragmentShader, 1, (const GLcharARB**)&fragmentShaderData, NULL);
		glCompileShaderARB(m_FragmentShader);
		glAttachObjectARB(m_Shader, m_FragmentShader);

		glLinkProgramARB(m_Shader);
		glValidateProgramARB(m_Shader);
	}

	return (m_Shader != 0);
}
//----------------------------------------------------------------------------------
CGLShader::~CGLShader()
{
	WISPFUN_DEBUG("c32_f2");
	if (m_Shader != 0)
	{
		glDeleteObjectARB(m_Shader);
		m_Shader = 0;
	}

	if (m_VertexShader != 0)
	{
		glDeleteObjectARB(m_VertexShader);
		m_VertexShader = 0;
	}

	if (m_FragmentShader != 0)
	{
		glDeleteObjectARB(m_FragmentShader);
		m_FragmentShader = 0;
	}

	m_TexturePointer = 0;
}
//----------------------------------------------------------------------------------
bool CGLShader::Use()
{
	WISPFUN_DEBUG("c32_f3");
	UnuseShader();

	bool result = false;

	if (m_Shader != 0)
	{
		glUseProgramObjectARB(m_Shader);
		result = true;
	}

	return result;
}
//----------------------------------------------------------------------------------
void CGLShader::Pause()
{
	WISPFUN_DEBUG("c32_f4");
	glUseProgramObjectARB(0);
}
//----------------------------------------------------------------------------------
void CGLShader::Resume()
{
	WISPFUN_DEBUG("c32_f5");
	glUseProgramObjectARB(m_Shader);
}
//----------------------------------------------------------------------------------
//-----------------------------------CDeathShader-----------------------------------
//----------------------------------------------------------------------------------
CDeathShader::CDeathShader()
: CGLShader()
{
	WISPFUN_DEBUG("c33_f1");
}
//----------------------------------------------------------------------------------
bool CDeathShader::Init(const char *vertexShaderData, const char *fragmentShaderData)
{
	if (CGLShader::Init(vertexShaderData, fragmentShaderData))
		m_TexturePointer = glGetUniformLocationARB(m_Shader, "usedTexture");
	else
		LOG("Failed to create DeathShader\n");

	return (m_Shader != 0);
}
//----------------------------------------------------------------------------------
//----------------------------------CColorizerShader--------------------------------
//----------------------------------------------------------------------------------
CColorizerShader::CColorizerShader()
: CGLShader()
{
	WISPFUN_DEBUG("c34_f1");
}
//----------------------------------------------------------------------------------
bool CColorizerShader::Init(const char *vertexShaderData, const char *fragmentShaderData)
{
	if (CGLShader::Init(vertexShaderData, fragmentShaderData))
	{
		m_TexturePointer = glGetUniformLocationARB(m_Shader, "usedTexture");
		m_ColorTablePointer = glGetUniformLocationARB(m_Shader, "colors");
		m_DrawModePointer = glGetUniformLocationARB(m_Shader, "drawMode");
	}
	else
		LOG("Failed to create ColorizerShader\n");

	return (m_Shader != 0);
}
//----------------------------------------------------------------------------------
bool CColorizerShader::Use()
{
	WISPFUN_DEBUG("c34_f2");
	bool result = CGLShader::Use();

	if (result)
	{
		ShaderColorTable = m_ColorTablePointer;
		g_ShaderDrawMode = m_DrawModePointer;
		glUniform1iARB(g_ShaderDrawMode, SDM_NO_COLOR);
	}

	return result;
}
//----------------------------------------------------------------------------------
<commit_msg>shaders compilation logging and error checking<commit_after>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/***********************************************************************************
**
** GLShader.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "stdafx.h"
//----------------------------------------------------------------------------------
CDeathShader g_DeathShader;
CColorizerShader g_ColorizerShader;
CColorizerShader g_FontColorizerShader;
CColorizerShader g_LightColorizerShader;
//----------------------------------------------------------------------------------
void UnuseShader()
{
	WISPFUN_DEBUG("c_uns_sdr");
	glUseProgramObjectARB(0);
	ShaderColorTable = 0;
	g_ShaderDrawMode = 0;
}
//----------------------------------------------------------------------------------
//-----------------------------------CGLShader--------------------------------------
//----------------------------------------------------------------------------------
CGLShader::CGLShader()
{
	WISPFUN_DEBUG("c32_f1");
}
//----------------------------------------------------------------------------------
bool CGLShader::Init(const char *vertexShaderData, const char *fragmentShaderData)
{
	GLint val = GL_FALSE;

	if (vertexShaderData != NULL && fragmentShaderData != NULL)
	{
		m_Shader = glCreateProgramObjectARB();

		m_VertexShader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
		glShaderSourceARB(m_VertexShader, 1, (const GLcharARB**)&vertexShaderData, NULL);
		glCompileShaderARB(m_VertexShader);

		glGetShaderiv(m_VertexShader, GL_COMPILE_STATUS, &val);
		if (val != GL_TRUE)
		{
			LOG("CGLShader::Init vertex shader compilation error:\n");
			auto error = glGetError();
			if (error != 0)
			{
				auto errorStr = gluErrorString(error);
				LOG("CGLShader::Init vertex shader error Code: %i\n", error);
				LOG("CGLShader::Init vertex shader error string: %s\n", errorStr);
			}
			return false;
		}
		LOG("vertex shader compiled successfully\n");

		glAttachObjectARB(m_Shader, m_VertexShader);

		m_FragmentShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
		glShaderSourceARB(m_FragmentShader, 1, (const GLcharARB**)&fragmentShaderData, NULL);
		glCompileShaderARB(m_FragmentShader);

		glGetShaderiv(m_FragmentShader, GL_COMPILE_STATUS, &val);
		if (val != GL_TRUE)
		{
			LOG("CGLShader::Init fragment shader compilation error:\n");
			auto error = glGetError();
			if (error != 0)
			{
				auto errorStr = gluErrorString(error);
				LOG("CGLShader::Init fragment shader error Code: %i\n", error);
				LOG("CGLShader::Init fragment shader error string: %s\n", errorStr);
			}
			return false;
		}
		LOG("fragment shader compiled successfully\n");

		glAttachObjectARB(m_Shader, m_FragmentShader);

		glLinkProgramARB(m_Shader);
		glValidateProgramARB(m_Shader);
	}
	else
		return false;

	glGetShaderiv(m_Shader, GL_COMPILE_STATUS, &val);
	if (val != GL_TRUE)
	{
		LOG("CGLShader::Init shader program compilation error:\n");
		auto error = glGetError();
		if (error != 0)
		{
			auto errorStr = gluErrorString(error);
			LOG("CGLShader::Init shader program error Code: %i\n", error);
			LOG("CGLShader::Init shader program error string: %s\n", errorStr);
		}
		return false;
	}
	LOG("shader program compiled successfully\n");

	return val == GL_TRUE;
}
//----------------------------------------------------------------------------------
CGLShader::~CGLShader()
{
	WISPFUN_DEBUG("c32_f2");
	if (m_Shader != 0)
	{
		glDeleteObjectARB(m_Shader);
		m_Shader = 0;
	}

	if (m_VertexShader != 0)
	{
		glDeleteObjectARB(m_VertexShader);
		m_VertexShader = 0;
	}

	if (m_FragmentShader != 0)
	{
		glDeleteObjectARB(m_FragmentShader);
		m_FragmentShader = 0;
	}

	m_TexturePointer = 0;
}
//----------------------------------------------------------------------------------
bool CGLShader::Use()
{
	WISPFUN_DEBUG("c32_f3");
	UnuseShader();

	bool result = false;

	if (m_Shader != 0)
	{
		glUseProgram(m_Shader);
		result = true;
	}

	return result;
}
//----------------------------------------------------------------------------------
void CGLShader::Pause()
{
	WISPFUN_DEBUG("c32_f4");
	glUseProgramObjectARB(0);
}
//----------------------------------------------------------------------------------
void CGLShader::Resume()
{
	WISPFUN_DEBUG("c32_f5");
	glUseProgramObjectARB(m_Shader);
}
//----------------------------------------------------------------------------------
//-----------------------------------CDeathShader-----------------------------------
//----------------------------------------------------------------------------------
CDeathShader::CDeathShader()
: CGLShader()
{
	WISPFUN_DEBUG("c33_f1");
}
//----------------------------------------------------------------------------------
bool CDeathShader::Init(const char *vertexShaderData, const char *fragmentShaderData)
{
	if (CGLShader::Init(vertexShaderData, fragmentShaderData))
		m_TexturePointer = glGetUniformLocationARB(m_Shader, "usedTexture");
	else
		LOG("Failed to create DeathShader\n");

	return (m_Shader != 0);
}
//----------------------------------------------------------------------------------
//----------------------------------CColorizerShader--------------------------------
//----------------------------------------------------------------------------------
CColorizerShader::CColorizerShader()
: CGLShader()
{
	WISPFUN_DEBUG("c34_f1");
}
//----------------------------------------------------------------------------------
bool CColorizerShader::Init(const char *vertexShaderData, const char *fragmentShaderData)
{
	if (CGLShader::Init(vertexShaderData, fragmentShaderData))
	{
		m_TexturePointer = glGetUniformLocationARB(m_Shader, "usedTexture");
		m_ColorTablePointer = glGetUniformLocationARB(m_Shader, "colors");
		m_DrawModePointer = glGetUniformLocationARB(m_Shader, "drawMode");
	}
	else
		LOG("Failed to create ColorizerShader\n");

	return (m_Shader != 0);
}
//----------------------------------------------------------------------------------
bool CColorizerShader::Use()
{
	WISPFUN_DEBUG("c34_f2");
	bool result = CGLShader::Use();

	if (result)
	{
		ShaderColorTable = m_ColorTablePointer;
		g_ShaderDrawMode = m_DrawModePointer;
		glUniform1iARB(g_ShaderDrawMode, SDM_NO_COLOR);
	}

	return result;
}
//----------------------------------------------------------------------------------
<|endoftext|>


<commit_before>#define LOOKUP_COLOR_COUNT 360

#include "thememanager.hpp"

#include <QColor>

#include <cmath>

namespace chatterino {
namespace singletons {

namespace detail {

double getMultiplierByTheme(const QString &themeName)
{
    if (themeName == "Light") {
        return 0.8;
    } else if (themeName == "White") {
        return 1.0;
    } else if (themeName == "Black") {
        return -1.0;
    } else if (themeName == "Dark") {
        return -0.8;
    }

    return -0.8;
}

}  // namespace detail

ThemeManager &ThemeManager::getInstance()
{
    static ThemeManager instance;
    return instance;
}

ThemeManager::ThemeManager()
    : themeName("/appearance/theme/name", "Dark")
    , themeHue("/appearance/theme/hue", 0.0)
{
    this->update();

    this->themeName.connectSimple([this](auto) { this->update(); });
    this->themeHue.connectSimple([this](auto) { this->update(); });
}

void ThemeManager::update()
{
    this->actuallyUpdate(this->themeHue, detail::getMultiplierByTheme(this->themeName.getValue()));
}

// hue: theme color (0 - 1)
// multiplier: 1 = white, 0.8 = light, -0.8 dark, -1 black
void ThemeManager::actuallyUpdate(double hue, double multiplier)
{
    isLight = multiplier > 0;
    bool lightWin = isLight;

    QColor none(0, 0, 0, 0);
    QColor themeColor = QColor::fromHslF(hue, 0.43, 0.5);
    QColor themeColorNoSat = QColor::fromHslF(hue, 0, 0.5);

    qreal sat = 0;
    //    0.05;

    auto getColor = [multiplier](double h, double s, double l, double a = 1.0) {
        return QColor::fromHslF(h, s, ((l - 0.5) * multiplier) + 0.5, a);
    };

    /// WINDOW
    {
        QColor bg = this->window.background = lightWin ? "#fff" : "#444";
        QColor fg = this->window.text = lightWin ? "#000" : "#eee";
        this->window.borderFocused = lightWin ? "#ccc" : themeColor;
        this->window.borderUnfocused = lightWin ? "#ccc" : themeColorNoSat;

        // Ubuntu style
        // TODO: add setting for this
        //        TabText = QColor(210, 210, 210);
        //        TabBackground = QColor(61, 60, 56);
        //        TabHoverText = QColor(210, 210, 210);
        //        TabHoverBackground = QColor(73, 72, 68);

        // message (referenced later)
        this->messages.textColors.caret =  //
            this->messages.textColors.regular = isLight ? "#000" : "#fff";

        /// TABS
        // text, {regular, hover, unfocused}

        if (lightWin) {
            this->tabs.regular = {fg, {bg, "#ccc", bg}};
            this->tabs.newMessage = {fg, {bg, "#ccc", bg}};
            this->tabs.highlighted = {fg, {bg, "#ccc", bg}};
            this->tabs.selected = {"#fff", {"#333", "#333", "#666"}};
        } else {
            this->tabs.regular = {fg, {bg, "#555", bg}};
            this->tabs.newMessage = {fg, {bg, "#555", bg}};
            this->tabs.highlighted = {fg, {bg, "#555", bg}};
            //            this->tabs.selected = {"#000", {themeColor, themeColor, themeColorNoSat}};
            this->tabs.selected = {"#000", {"#999", "#999", "#888"}};
        }
    }

    // Split
    bool flat = isLight;

    this->splits.messageSeperator = isLight ? QColor(127, 127, 127) : QColor(80, 80, 80);
    this->splits.background = getColor(0, sat, 1);
    this->splits.dropPreview = getColor(hue, 0.5, 0.5, 0.6);
    // this->splits.border
    // this->splits.borderFocused

    this->splits.header.background = getColor(0, sat, flat ? 1 : 0.9);
    this->splits.header.border = getColor(0, sat, flat ? 1 : 0.85);
    this->splits.header.text = this->messages.textColors.regular;

    this->splits.input.background = getColor(0, sat, flat ? 0.95 : 0.95);
    this->splits.input.border = getColor(0, sat, flat ? 1 : 1);
    this->splits.input.text = this->messages.textColors.regular;
    this->splits.input.styleSheet =
        "background:" + this->splits.input.background.name() + ";" +
        "border:" + this->tabs.selected.backgrounds.regular.color().name() + ";" +
        "color:" + this->messages.textColors.regular.name() + ";" +
        "selection-background-color:" + this->tabs.selected.backgrounds.regular.color().name();

    // Message
    this->messages.textColors.link = isLight ? QColor(66, 134, 244) : QColor(66, 134, 244);
    this->messages.textColors.system = QColor(140, 127, 127);

    this->messages.backgrounds.regular = splits.background;
    this->messages.backgrounds.highlighted =
        blendColors(themeColor, this->messages.backgrounds.regular, 0.8);
    // this->messages.backgrounds.resub
    // this->messages.backgrounds.whisper
    this->messages.disabled = getColor(0, sat, 1, 0.6);
    // this->messages.seperator =
    // this->messages.seperatorInner =

    // Scrollbar
    this->scrollbars.background = getColor(0, sat, 0.94);
    this->scrollbars.thumb = getColor(0, sat, 0.80);
    this->scrollbars.thumbSelected = getColor(0, sat, 0.7);

    // tooltip
    this->tooltip.background = QColor(0, 0, 0);
    this->tooltip.text = QColor(255, 255, 255);

    // Selection
    this->messages.selection = isLightTheme() ? QColor(0, 0, 0, 64) : QColor(255, 255, 255, 64);

    this->updated.invoke();
}

QColor ThemeManager::blendColors(const QColor &color1, const QColor &color2, qreal ratio)
{
    int r = color1.red() * (1 - ratio) + color2.red() * ratio;
    int g = color1.green() * (1 - ratio) + color2.green() * ratio;
    int b = color1.blue() * (1 - ratio) + color2.blue() * ratio;

    return QColor(r, g, b, 255);
}

void ThemeManager::normalizeColor(QColor &color)
{
    if (this->isLight) {
        if (color.lightnessF() > 0.5f) {
            color.setHslF(color.hueF(), color.saturationF(), 0.5f);
        }

        if (color.lightnessF() > 0.4f && color.hueF() > 0.1 && color.hueF() < 0.33333) {
            color.setHslF(
                color.hueF(), color.saturationF(),
                color.lightnessF() - sin((color.hueF() - 0.1) / (0.3333 - 0.1) * 3.14159) *
                                         color.saturationF() * 0.2);
        }
    } else {
        if (color.lightnessF() < 0.5f) {
            color.setHslF(color.hueF(), color.saturationF(), 0.5f);
        }

        if (color.lightnessF() < 0.6f && color.hueF() > 0.54444 && color.hueF() < 0.83333) {
            color.setHslF(
                color.hueF(), color.saturationF(),
                color.lightnessF() + sin((color.hueF() - 0.54444) / (0.8333 - 0.54444) * 3.14159) *
                                         color.saturationF() * 0.4);
        }
    }
}

}  // namespace singletons
}  // namespace chatterino
<commit_msg>fixed gcc compile bug<commit_after>#define LOOKUP_COLOR_COUNT 360

#include "thememanager.hpp"

#include <QColor>

#include <cmath>

namespace chatterino {
namespace singletons {

namespace detail {

double getMultiplierByTheme(const QString &themeName)
{
    if (themeName == "Light") {
        return 0.8;
    } else if (themeName == "White") {
        return 1.0;
    } else if (themeName == "Black") {
        return -1.0;
    } else if (themeName == "Dark") {
        return -0.8;
    }

    return -0.8;
}

}  // namespace detail

ThemeManager &ThemeManager::getInstance()
{
    static ThemeManager instance;
    return instance;
}

ThemeManager::ThemeManager()
    : themeName("/appearance/theme/name", "Dark")
    , themeHue("/appearance/theme/hue", 0.0)
{
    this->update();

    this->themeName.connectSimple([this](auto) { this->update(); });
    this->themeHue.connectSimple([this](auto) { this->update(); });
}

void ThemeManager::update()
{
    this->actuallyUpdate(this->themeHue, detail::getMultiplierByTheme(this->themeName.getValue()));
}

// hue: theme color (0 - 1)
// multiplier: 1 = white, 0.8 = light, -0.8 dark, -1 black
void ThemeManager::actuallyUpdate(double hue, double multiplier)
{
    isLight = multiplier > 0;
    bool lightWin = isLight;

    QColor none(0, 0, 0, 0);
    QColor themeColor = QColor::fromHslF(hue, 0.43, 0.5);
    QColor themeColorNoSat = QColor::fromHslF(hue, 0, 0.5);

    qreal sat = 0;
    //    0.05;

    auto getColor = [multiplier](double h, double s, double l, double a = 1.0) {
        return QColor::fromHslF(h, s, ((l - 0.5) * multiplier) + 0.5, a);
    };

    /// WINDOW
    {
        QColor bg = this->window.background = lightWin ? "#fff" : "#444";
        QColor fg = this->window.text = lightWin ? "#000" : "#eee";
        this->window.borderFocused = lightWin ? "#ccc" : themeColor;
        this->window.borderUnfocused = lightWin ? "#ccc" : themeColorNoSat;

        // Ubuntu style
        // TODO: add setting for this
        //        TabText = QColor(210, 210, 210);
        //        TabBackground = QColor(61, 60, 56);
        //        TabHoverText = QColor(210, 210, 210);
        //        TabHoverBackground = QColor(73, 72, 68);

        // message (referenced later)
        this->messages.textColors.caret =  //
            this->messages.textColors.regular = isLight ? "#000" : "#fff";

        /// TABS
        // text, {regular, hover, unfocused}

        if (lightWin) {
            this->tabs.regular = {fg, {bg, QColor("#ccc"), bg}};
            this->tabs.newMessage = {fg, {bg, QColor("#ccc"), bg}};
            this->tabs.highlighted = {fg, {bg, QColor("#ccc"), bg}};
            this->tabs.selected = {QColor("#fff"), {QColor("#333"), QColor("#333"), QColor("#666")}};
        } else {
            this->tabs.regular = {fg, {bg, QColor("#555"), bg}};
            this->tabs.newMessage = {fg, {bg, QColor("#555"), bg}};
            this->tabs.highlighted = {fg, {bg, QColor("#555"), bg}};
            //            this->tabs.selected = {"#000", {themeColor, themeColor, themeColorNoSat}};
            this->tabs.selected = {QColor("#000"), {QColor("#999"), QColor("#999"), QColor("#888")}};
        }
    }

    // Split
    bool flat = isLight;

    this->splits.messageSeperator = isLight ? QColor(127, 127, 127) : QColor(80, 80, 80);
    this->splits.background = getColor(0, sat, 1);
    this->splits.dropPreview = getColor(hue, 0.5, 0.5, 0.6);
    // this->splits.border
    // this->splits.borderFocused

    this->splits.header.background = getColor(0, sat, flat ? 1 : 0.9);
    this->splits.header.border = getColor(0, sat, flat ? 1 : 0.85);
    this->splits.header.text = this->messages.textColors.regular;

    this->splits.input.background = getColor(0, sat, flat ? 0.95 : 0.95);
    this->splits.input.border = getColor(0, sat, flat ? 1 : 1);
    this->splits.input.text = this->messages.textColors.regular;
    this->splits.input.styleSheet =
        "background:" + this->splits.input.background.name() + ";" +
        "border:" + this->tabs.selected.backgrounds.regular.color().name() + ";" +
        "color:" + this->messages.textColors.regular.name() + ";" +
        "selection-background-color:" + this->tabs.selected.backgrounds.regular.color().name();

    // Message
    this->messages.textColors.link = isLight ? QColor(66, 134, 244) : QColor(66, 134, 244);
    this->messages.textColors.system = QColor(140, 127, 127);

    this->messages.backgrounds.regular = splits.background;
    this->messages.backgrounds.highlighted =
        blendColors(themeColor, this->messages.backgrounds.regular, 0.8);
    // this->messages.backgrounds.resub
    // this->messages.backgrounds.whisper
    this->messages.disabled = getColor(0, sat, 1, 0.6);
    // this->messages.seperator =
    // this->messages.seperatorInner =

    // Scrollbar
    this->scrollbars.background = getColor(0, sat, 0.94);
    this->scrollbars.thumb = getColor(0, sat, 0.80);
    this->scrollbars.thumbSelected = getColor(0, sat, 0.7);

    // tooltip
    this->tooltip.background = QColor(0, 0, 0);
    this->tooltip.text = QColor(255, 255, 255);

    // Selection
    this->messages.selection = isLightTheme() ? QColor(0, 0, 0, 64) : QColor(255, 255, 255, 64);

    this->updated.invoke();
}

QColor ThemeManager::blendColors(const QColor &color1, const QColor &color2, qreal ratio)
{
    int r = color1.red() * (1 - ratio) + color2.red() * ratio;
    int g = color1.green() * (1 - ratio) + color2.green() * ratio;
    int b = color1.blue() * (1 - ratio) + color2.blue() * ratio;

    return QColor(r, g, b, 255);
}

void ThemeManager::normalizeColor(QColor &color)
{
    if (this->isLight) {
        if (color.lightnessF() > 0.5f) {
            color.setHslF(color.hueF(), color.saturationF(), 0.5f);
        }

        if (color.lightnessF() > 0.4f && color.hueF() > 0.1 && color.hueF() < 0.33333) {
            color.setHslF(
                color.hueF(), color.saturationF(),
                color.lightnessF() - sin((color.hueF() - 0.1) / (0.3333 - 0.1) * 3.14159) *
                                         color.saturationF() * 0.2);
        }
    } else {
        if (color.lightnessF() < 0.5f) {
            color.setHslF(color.hueF(), color.saturationF(), 0.5f);
        }

        if (color.lightnessF() < 0.6f && color.hueF() > 0.54444 && color.hueF() < 0.83333) {
            color.setHslF(
                color.hueF(), color.saturationF(),
                color.lightnessF() + sin((color.hueF() - 0.54444) / (0.8333 - 0.54444) * 3.14159) *
                                         color.saturationF() * 0.4);
        }
    }
}

}  // namespace singletons
}  // namespace chatterino
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//_________________________________________________________________________
//*--
//*-- Yves Schutz (SUBATECH)
// Reconstruction class. Redesigned from the old AliReconstructionner class and
// derived from STEER/AliReconstructor.
//
// --- ROOT system ---

// --- Standard library ---

// --- AliRoot header files ---
#include "AliESD.h"
#include "AliPHOSReconstructor.h"
#include "AliPHOSClusterizerv1.h"
#include "AliPHOSTrackSegmentMakerv1.h"
#include "AliPHOSPIDv1.h"
#include "AliPHOSGetter.h"
#include "AliPHOSTracker.h"
#include "AliRawReaderFile.h"

ClassImp(AliPHOSReconstructor)

Bool_t AliPHOSReconstructor::fgDebug = kFALSE ;

//____________________________________________________________________________
  AliPHOSReconstructor::AliPHOSReconstructor()
{
  // ctor

}

//____________________________________________________________________________
  AliPHOSReconstructor::~AliPHOSReconstructor()
{
  // dtor

}

//____________________________________________________________________________
void AliPHOSReconstructor::Reconstruct(AliRunLoader* runLoader) const
{
  // method called by AliReconstruction;
  // Only the clusterization is performed,; the rest of the reconstruction is done in FillESD because the track
  // segment maker needs access to the AliESD object to retrieve the tracks reconstructed by
  // the global tracking.

  TString headerFile(runLoader->GetFileName()) ;
  TString branchName(runLoader->GetEventFolder()->GetName()) ;

  AliPHOSClusterizerv1 clu(headerFile, branchName);
  clu.SetEventRange(0, -1) ; // do all the events
  if ( Debug() )
    clu.ExecuteTask("deb all") ;
  else
    clu.ExecuteTask("") ;

}

//____________________________________________________________________________
void AliPHOSReconstructor::Reconstruct(AliRunLoader* runLoader, AliRawReader* rawreader) const
{
  // method called by AliReconstruction;
  // Only the clusterization is performed,; the rest of the reconstruction is done in FillESD because the track
  // segment maker needs access to the AliESD object to retrieve the tracks reconstructed by
  // the global tracking.
  // Here we reconstruct from Raw Data

  rawreader->Reset() ;
  TString headerFile(runLoader->GetFileName()) ;
  TString branchName(runLoader->GetEventFolder()->GetName()) ;

  AliPHOSClusterizerv1 clu(headerFile, branchName);
  clu.SetEventRange(0, -1) ; // do all the events
  if ( Debug() )
    clu.ExecuteTask("deb all") ;
  else
    clu.ExecuteTask("") ;

}

//____________________________________________________________________________
void AliPHOSReconstructor::FillESD(AliRunLoader* runLoader, AliESD* esd) const
{
  // This function creates AliESDtracks from AliPHOSRecParticles
  //         and
  // writes them to the ESD

  Int_t eventNumber = runLoader->GetEventNumber() ;

  AliPHOSGetter::Instance()->Event(eventNumber, "P") ;
  TClonesArray *recParticles = AliPHOSGetter::Instance()->RecParticles();
  Int_t nOfRecParticles = recParticles->GetEntries();
  esd->SetNumberOfPHOSParticles(nOfRecParticles) ;
  esd->SetFirstPHOSParticle(esd->GetNumberOfTracks()) ;

  for (Int_t recpart = 0 ; recpart < nOfRecParticles ; recpart++) {
    AliPHOSRecParticle * rp = dynamic_cast<AliPHOSRecParticle*>(recParticles->At(recpart));
    if (Debug())
      rp->Print();
    AliESDtrack * et = new AliESDtrack() ;
    // fills the ESDtrack
    Double_t xyz[3];
    for (Int_t ixyz=0; ixyz<3; ixyz++)
      xyz[ixyz] = rp->GetPos()[ixyz];
    et->SetPHOSposition(xyz) ;
    et->SetPHOSsignal  (rp->Energy()) ;
    et->SetPHOSpid     (rp->GetPID()) ;
    et->SetLabel       (rp->GetPrimaryIndex());
    // add the track to the esd object
    esd->AddTrack(et);
    delete et;
  }
}

AliTracker* AliPHOSReconstructor::CreateTracker(AliRunLoader* runLoader) const
{
// creates the PHOS tracker
  if (!runLoader) return NULL;
  return new AliPHOSTracker(runLoader);
}

<commit_msg>Reading raw data<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//_________________________________________________________________________
//*--
//*-- Yves Schutz (SUBATECH)
// Reconstruction class. Redesigned from the old AliReconstructionner class and
// derived from STEER/AliReconstructor.
//
// --- ROOT system ---

// --- Standard library ---

// --- AliRoot header files ---
#include "AliESD.h"
#include "AliPHOSReconstructor.h"
#include "AliPHOSClusterizerv1.h"
#include "AliPHOSTrackSegmentMakerv1.h"
#include "AliPHOSPIDv1.h"
#include "AliPHOSGetter.h"
#include "AliPHOSTracker.h"
#include "AliRawReader.h"

ClassImp(AliPHOSReconstructor)

Bool_t AliPHOSReconstructor::fgDebug = kFALSE ;

//____________________________________________________________________________
  AliPHOSReconstructor::AliPHOSReconstructor()
{
  // ctor

}

//____________________________________________________________________________
  AliPHOSReconstructor::~AliPHOSReconstructor()
{
  // dtor

}

//____________________________________________________________________________
void AliPHOSReconstructor::Reconstruct(AliRunLoader* runLoader) const
{
  // method called by AliReconstruction;
  // Only the clusterization is performed,; the rest of the reconstruction is done in FillESD because the track
  // segment maker needs access to the AliESD object to retrieve the tracks reconstructed by
  // the global tracking.

  TString headerFile(runLoader->GetFileName()) ;
  TString branchName(runLoader->GetEventFolder()->GetName()) ;

  AliPHOSClusterizerv1 clu(headerFile, branchName);
  clu.SetEventRange(0, -1) ; // do all the events
  if ( Debug() )
    clu.ExecuteTask("deb all") ;
  else
    clu.ExecuteTask("") ;

}

//____________________________________________________________________________
void AliPHOSReconstructor::Reconstruct(AliRunLoader* runLoader, AliRawReader* rawreader) const
{
  // method called by AliReconstruction;
  // Only the clusterization is performed,; the rest of the reconstruction is done in FillESD because the track
  // segment maker needs access to the AliESD object to retrieve the tracks reconstructed by
  // the global tracking.
  // Here we reconstruct from Raw Data

  rawreader->Reset() ;
  TString headerFile(runLoader->GetFileName()) ;
  TString branchName(runLoader->GetEventFolder()->GetName()) ;

  AliPHOSClusterizerv1 clu(headerFile, branchName);
  clu.SetEventRange(0, 0) ; // reconstruct one events
  clu.SetRawReader(rawreader);
  if ( Debug() )
    clu.ExecuteTask("deb all") ;
  else
    clu.ExecuteTask("") ;

}

//____________________________________________________________________________
void AliPHOSReconstructor::FillESD(AliRunLoader* runLoader, AliESD* esd) const
{
  // This function creates AliESDtracks from AliPHOSRecParticles
  //         and
  // writes them to the ESD

  Int_t eventNumber = runLoader->GetEventNumber() ;

  AliPHOSGetter::Instance()->Event(eventNumber, "P") ;
  TClonesArray *recParticles = AliPHOSGetter::Instance()->RecParticles();
  Int_t nOfRecParticles = recParticles->GetEntries();
  esd->SetNumberOfPHOSParticles(nOfRecParticles) ;
  esd->SetFirstPHOSParticle(esd->GetNumberOfTracks()) ;

  for (Int_t recpart = 0 ; recpart < nOfRecParticles ; recpart++) {
    AliPHOSRecParticle * rp = dynamic_cast<AliPHOSRecParticle*>(recParticles->At(recpart));
    if (Debug())
      rp->Print();
    AliESDtrack * et = new AliESDtrack() ;
    // fills the ESDtrack
    Double_t xyz[3];
    for (Int_t ixyz=0; ixyz<3; ixyz++)
      xyz[ixyz] = rp->GetPos()[ixyz];
    et->SetPHOSposition(xyz) ;
    et->SetPHOSsignal  (rp->Energy()) ;
    et->SetPHOSpid     (rp->GetPID()) ;
    et->SetLabel       (rp->GetPrimaryIndex());
    // add the track to the esd object
    esd->AddTrack(et);
    delete et;
  }
}

AliTracker* AliPHOSReconstructor::CreateTracker(AliRunLoader* runLoader) const
{
// creates the PHOS tracker
  if (!runLoader) return NULL;
  return new AliPHOSTracker(runLoader);
}

<|endoftext|>


<commit_before>/*
* Copyright 2010 MQWeb - Franky Braem
*
* Licensed under the EUPL, Version 1.1 or – as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/
#include "MQ/MQSubsystem.h"
#include "MQ/Web/Application.h"
#include "MQ/Web/RequestHandlerFactory.h"

#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPServerParams.h"

#include "Poco/Logger.h"
#include "Poco/File.h"

#include <iostream>

using namespace Poco::Net;
using namespace Poco::Util;

MQWebApplication::MQWebApplication(): _helpRequested(false)
{
	addSubsystem(new MQ::MQSubsystem());
}

MQWebApplication::~MQWebApplication()
{
}

void MQWebApplication::initialize(Application& self)
{
	try
	{
		loadConfiguration(); // load default configuration files, if present
	}
	catch(Poco::FileException& fe)
	{
		std::cout << "Caught a file exception when loading configuration file: " << fe.message() << std::endl;
	}

	try
	{
		ServerApplication::initialize(self);
	}
	catch(Poco::NotFoundException& nfe)
	{
		// We can get here when some log configuration is not available
		std::cout << "Please check your logger configuration because we got a NotFoundException for " << nfe.message() << std::endl;
	}
}

void MQWebApplication::uninitialize()
{
	Poco::Logger::get("mq.web").information("MQWeb process stopped!");

	ServerApplication::uninitialize();
}

void MQWebApplication::defineOptions(Poco::Util::OptionSet& options)
{
	ServerApplication::defineOptions(options);

	options.addOption(
	Option("help", "h", "display help information on command line arguments")
		.required(false)
		.repeatable(false));

	options.addOption(
	Option("qmgr", "m", "connect only to this queuemanager")
		.required(false)
		.repeatable(false)
		.binding("mq.web.qmgr")
		.argument("name"));

	options.addOption(
	Option("port", "p", "Port for HTTP listener")
		.required(false)
		.repeatable(false)
		.binding("mq.web.port")
		.argument("port"));
}

void MQWebApplication::handleOption(const std::string& name, const std::string& value)
{
	ServerApplication::handleOption(name, value);

	if (name == "help")
	{
		_helpRequested = true;
	}
}

void MQWebApplication::displayHelp()
{
	HelpFormatter helpFormatter(options());
	helpFormatter.setCommand(commandName());
	helpFormatter.setUsage("OPTIONS");
	helpFormatter.setHeader("A web server for managing Websphere MQ.");
	helpFormatter.format(std::cout);
}

int MQWebApplication::main(const std::vector<std::string>& args)
{
	if (_helpRequested)
	{
		displayHelp();
		return Application::EXIT_OK;
	}

	Poco::Logger& logger = Poco::Logger::get("mq.web");

	MQ::MQSubsystem& mqSystem = getSubsystem<MQ::MQSubsystem>();

	try
	{
		mqSystem.load();
	}
	catch(Poco::LibraryLoadException& lle)
	{
		Poco::Logger::get("mq").fatal(lle.message());
		return Application::EXIT_SOFTWARE;
	}

	_cache.setLogger(logger);

	// Check the template path configuration (mq.web.templates)
	Poco::Path templatePath;
	std::string templatesValue;
	try
	{
		templatesValue = config().getString("mq.web.templates");
		templatesValue = config().expand(templatesValue);
		templatePath.assign(templatesValue);
		templatePath.makeDirectory();
	}
	catch(Poco::NotFoundException&)
	{
		templatePath.assign(config().getString("application.dir"));
		templatePath.pushDirectory("templates");
		poco_warning_f1(logger, "No mq.web.templates found in the configuration file. Trying to use %s", templatePath.toString());
	}
	catch(Poco::PathSyntaxException&)
	{
		poco_fatal_f1(logger, "Invalid path specified for mq.web.templates: %s", templatesValue);
		return Application::EXIT_CONFIG;
	}

	Poco::File file(templatePath);
	if ( !file.exists() )
	{
		poco_fatal_f1(logger, "Template path %s doesn't exist! Check the configuration file.", templatePath.toString());
		return Application::EXIT_CONFIG;
	}

	_cache.addPath(templatePath);

	// Check the static path configuration (mq.web.static)
	Poco::Path staticPath;
	std::string staticValue;
	try
	{
		staticValue = config().getString("mq.web.static");
		staticValue = config().expand(staticValue);
		staticPath.assign(staticValue);
		staticPath.makeDirectory();
	}
	catch(Poco::NotFoundException&)
	{
		staticPath.assign(config().getString("application.dir"));
		staticPath.pushDirectory("static");
		config().setString("mq.web.static", staticPath.toString());
		poco_warning_f1(logger, "No mq.web.static found in the configuration file. Trying to use %s", staticPath.toString());
	}
	catch(Poco::PathSyntaxException&)
	{
		poco_fatal_f1(logger, "Invalid path specified for mq.web.static: %s", staticValue);
		return Application::EXIT_CONFIG;
	}

	file = Poco::File(staticPath);
	if ( !file.exists() )
	{
		poco_fatal_f1(logger, "Path for static files %s doesn't exist! Check the configuration file.", staticPath.toString());
		return Application::EXIT_CONFIG;
	}

	unsigned short port = (unsigned short) config().getInt("mq.web.port", 8081);

	// set-up a server socket
	ServerSocket svs(port);
	// set-up a HTTPServer instance
	HTTPServer srv(new MQ::Web::RequestHandlerFactory, svs, new HTTPServerParams);
	// start the HTTPServer
	srv.start();

	poco_information_f1(logger, "MQWeb started and listening on port %hu", port);

	// wait for CTRL-C or kill
	waitForTerminationRequest();
	// Stop the HTTPServer
	srv.stop();

	return Application::EXIT_OK;
}

POCO_SERVER_MAIN(MQWebApplication)
<commit_msg>Don't fail anymore when there is no mq.web.templates / mq.web.static configuration<commit_after>/*
* Copyright 2010 MQWeb - Franky Braem
*
* Licensed under the EUPL, Version 1.1 or – as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/
#include "MQ/MQSubsystem.h"
#include "MQ/Web/Application.h"
#include "MQ/Web/RequestHandlerFactory.h"

#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPServerParams.h"

#include "Poco/Logger.h"
#include "Poco/File.h"

#include <iostream>

using namespace Poco::Net;
using namespace Poco::Util;

MQWebApplication::MQWebApplication(): _helpRequested(false)
{
	addSubsystem(new MQ::MQSubsystem());
}

MQWebApplication::~MQWebApplication()
{
}

void MQWebApplication::initialize(Application& self)
{
	try
	{
		loadConfiguration(); // load default configuration files, if present
	}
	catch(Poco::FileException& fe)
	{
		std::cout << "Caught a file exception when loading configuration file: " << fe.message() << std::endl;
	}

	try
	{
		ServerApplication::initialize(self);
	}
	catch(Poco::NotFoundException& nfe)
	{
		// We can get here when some log configuration is not available
		std::cout << "Please check your logger configuration because we got a NotFoundException for " << nfe.message() << std::endl;
	}
}

void MQWebApplication::uninitialize()
{
	Poco::Logger::get("mq.web").information("MQWeb process stopped!");

	ServerApplication::uninitialize();
}

void MQWebApplication::defineOptions(Poco::Util::OptionSet& options)
{
	ServerApplication::defineOptions(options);

	options.addOption(
	Option("help", "h", "display help information on command line arguments")
		.required(false)
		.repeatable(false));

	options.addOption(
	Option("qmgr", "m", "connect only to this queuemanager")
		.required(false)
		.repeatable(false)
		.binding("mq.web.qmgr")
		.argument("name"));

	options.addOption(
	Option("port", "p", "Port for HTTP listener")
		.required(false)
		.repeatable(false)
		.binding("mq.web.port")
		.argument("port"));
}

void MQWebApplication::handleOption(const std::string& name, const std::string& value)
{
	ServerApplication::handleOption(name, value);

	if (name == "help")
	{
		_helpRequested = true;
	}
}

void MQWebApplication::displayHelp()
{
	HelpFormatter helpFormatter(options());
	helpFormatter.setCommand(commandName());
	helpFormatter.setUsage("OPTIONS");
	helpFormatter.setHeader("A web server for managing Websphere MQ.");
	helpFormatter.format(std::cout);
}

int MQWebApplication::main(const std::vector<std::string>& args)
{
	if (_helpRequested)
	{
		displayHelp();
		return Application::EXIT_OK;
	}

	Poco::Logger& logger = Poco::Logger::get("mq.web");

	MQ::MQSubsystem& mqSystem = getSubsystem<MQ::MQSubsystem>();

	try
	{
		mqSystem.load();
	}
	catch(Poco::LibraryLoadException& lle)
	{
		Poco::Logger::get("mq").fatal(lle.message());
		return Application::EXIT_SOFTWARE;
	}

	_cache.setLogger(logger);

	if ( config().has("mq.web.templates") )
	{
		Poco::Path templatePath;
		std::string templatesValue;
		try
		{
			templatesValue = config().getString("mq.web.templates");
			templatesValue = config().expand(templatesValue);
			templatePath.assign(templatesValue);
			templatePath.makeDirectory();
		}
		catch(Poco::PathSyntaxException&)
		{
			poco_fatal_f1(logger, "Invalid path specified for mq.web.templates: %s", templatesValue);
			return Application::EXIT_CONFIG;
		}

		Poco::File file(templatePath);
		if ( !file.exists() )
		{
			poco_fatal_f1(logger, "Template path %s doesn't exist! Check the configuration file.", templatePath.toString());
			return Application::EXIT_CONFIG;
		}

		_cache.addPath(templatePath);
	}

	// Check the static path configuration (mq.web.static)
	if ( config().has("mq.web.static") )
	{
		Poco::Path staticPath;
		std::string staticValue;
		try
		{
			staticValue = config().getString("mq.web.static");
			staticValue = config().expand(staticValue);
			staticPath.assign(staticValue);
			staticPath.makeDirectory();
		}
		catch(Poco::PathSyntaxException&)
		{
			poco_fatal_f1(logger, "Invalid path specified for mq.web.static: %s", staticValue);
			return Application::EXIT_CONFIG;
		}

		Poco::File file = Poco::File(staticPath);
		if ( !file.exists() )
		{
			poco_fatal_f1(logger, "Path for static files %s doesn't exist! Check the configuration file.", staticPath.toString());
			return Application::EXIT_CONFIG;
		}
	}

	unsigned short port = (unsigned short) config().getInt("mq.web.port", 8081);

	// set-up a server socket
	ServerSocket svs(port);
	// set-up a HTTPServer instance
	HTTPServer srv(new MQ::Web::RequestHandlerFactory, svs, new HTTPServerParams);
	// start the HTTPServer
	srv.start();

	poco_information_f1(logger, "MQWeb started and listening on port %hu", port);

	// wait for CTRL-C or kill
	waitForTerminationRequest();
	// Stop the HTTPServer
	srv.stop();

	return Application::EXIT_OK;
}

POCO_SERVER_MAIN(MQWebApplication)
<|endoftext|>


<commit_before>/*
* Copyright 2017 - KBC Group NV - Franky Braem - The MIT license
* 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 "MQ/Web/QueueRemove.h"
#include "MQ/MQException.h"

namespace MQ {
namespace Web {

QueueRemove::QueueRemove(CommandServer& commandServer, Poco::JSON::Object::Ptr input)
: PCFCommand(commandServer, MQCMD_DELETE_Q, "Queue", input)
{
	// Required Parameters
	addParameter<std::string>(MQCA_Q_NAME, "QName");

	// Optional Parameters
	addParameterNumFromString(MQIACF_REMOVE_AUTHREC, "Authrec");
	addParameter<std::string>(MQCACF_COMMAND_SCOPE, "CommandScope");
	addParameter<MQLONG>(MQIA_PAGESET_ID, "PageSetId");
	addParameterNumFromString(MQIACF_PURGE, "Purge");
	addParameterNumFromString(MQIA_QSG_DISP, "QSGDisposition");
	addParameterNumFromString(MQIA_Q_TYPE, "QType");
}

QueueRemove::~QueueRemove()
{
}

Poco::JSON::Array::Ptr QueueRemove::execute()
{
	PCFCommand::execute();

	for(PCF::Vector::const_iterator it = begin(); it != end(); it++)
	{
		if ( (*it)->isExtendedResponse() ) // Skip extended response
			continue;

		if ( (*it)->getReasonCode() != MQRC_NONE )
		{
			throw MQException("PCF", getCommandString((*it)->getCommand()), (*it)->getCompletionCode(), (*it)->getReasonCode());
		}
	}
	return new Poco::JSON::Array();
}

}} //  Namespace MQ::Web
<commit_msg>Authrec and Purge doesn't have values in the dictionary<commit_after>/*
* Copyright 2017 - KBC Group NV - Franky Braem - The MIT license
* 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 "MQ/Web/QueueRemove.h"
#include "MQ/MQException.h"

namespace MQ {
namespace Web {

QueueRemove::QueueRemove(CommandServer& commandServer, Poco::JSON::Object::Ptr input)
: PCFCommand(commandServer, MQCMD_DELETE_Q, "Queue", input)
{
	// Required Parameters
	addParameter<std::string>(MQCA_Q_NAME, "QName");

	// Optional Parameters
	std::string authrec = input->optValue<std::string>("Authrec", "No");
	if ( Poco::icompare(authrec, "Yes") == 0 )
	{
		pcf()->addParameter(MQIACF_REMOVE_AUTHREC, MQRAR_YES);
	}
	addParameter<std::string>(MQCACF_COMMAND_SCOPE, "CommandScope");

	std::string purge = input->optValue<std::string>("Purge", "No");
	if ( Poco::icompare(authrec, "Yes") == 0 )
	{
		pcf()->addParameter(MQIACF_PURGE, MQPO_YES);
	}

	addParameterNumFromString(MQIA_QSG_DISP, "QSGDisposition");
	addParameterNumFromString(MQIA_Q_TYPE, "QType");
}

QueueRemove::~QueueRemove()
{
}

Poco::JSON::Array::Ptr QueueRemove::execute()
{
	PCFCommand::execute();

	for(PCF::Vector::const_iterator it = begin(); it != end(); it++)
	{
		if ( (*it)->isExtendedResponse() ) // Skip extended response
			continue;

		if ( (*it)->getReasonCode() != MQRC_NONE )
		{
			throw MQException("PCF", getCommandString((*it)->getCommand()), (*it)->getCompletionCode(), (*it)->getReasonCode());
		}
	}
	return new Poco::JSON::Array();
}

}} //  Namespace MQ::Web
<|endoftext|>


<commit_before>// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************

#include "stdafx.h"
#include "WinRTMidi.h"
#include "WindowsVersionHelper.h"
#include <iostream>
#include <string>
#include <conio.h>

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

using namespace std;
using namespace WinRT;

CRITICAL_SECTION gCriticalSection;

// WinRTMidi DLL function pointers
WinRTWatcherPortCountFunc   gWatcherPortCountFunc = nullptr;
WinRTWatcherPortNameFunc    gWatcherPortNameFunc = nullptr;
WinRTWatcherPortTypeFunc    gWatcherPortTypeFunc = nullptr;
WinRTMidiInitializeFunc     gMidiInitFunc = nullptr;
WinRTMidiFreeFunc           gMidiFreeFunc = nullptr;
WinRTMidiGetPortWatcherFunc gMidiGetPortWatcher = nullptr;
WinRTMidiInPortOpenFunc     gMidiInPortOpenFunc = nullptr;
WinRTMidiInPortFreeFunc     gMidiInPortFreeFunc = nullptr;
WinRTMidiOutPortOpenFunc    gMidiOutPortOpenFunc = nullptr;
WinRTMidiOutPortFreeFunc    gMidiOutPortFreeFunc = nullptr;
WinRTMidiOutPortSendFunc    gMidiOutPortSendFunc = nullptr;

// Midi Out port
WinRTMidiOutPortPtr gMidiOutPort = nullptr;

void printPortNames(const WinRTMidiPortWatcherPtr watcher)
{
    if (watcher == nullptr)
    {
        return;
    }

    WinRTMidiPortType type = gWatcherPortTypeFunc(watcher);
    if (type == In)
    {
        cout << "MIDI In Ports" << endl;
    }
    else
    {
        cout << "MIDI Out Ports" << endl;
    }

    int nPorts = gWatcherPortCountFunc(watcher);
    for (int i = 0; i < nPorts; i++)
    {
        const char* name = gWatcherPortNameFunc(watcher, i);
        cout << i << ": " << gWatcherPortNameFunc(watcher, i) << endl;
    }

    cout << endl;
}

void midiPortChangedCallback(const WinRTMidiPortWatcherPtr portWatcher, WinRTMidiPortUpdateType update)
{
    EnterCriticalSection(&gCriticalSection);
    string portName = gWatcherPortTypeFunc(portWatcher) == In ? "In" : "Out";

    switch (update)
    {
    case PortAdded:
        cout << "***MIDI " << portName << " port added***" << endl;
        break;

    case PortRemoved:
        cout << "***MIDI " << portName << " port removed***" << endl;
        break;

    case EnumerationComplete:
        cout << "***MIDI " << portName << " port enumeration complete***" << endl;
        break;
    }

    printPortNames(portWatcher);
    LeaveCriticalSection(&gCriticalSection);
}

void midiInCallback(const WinRTMidiInPortPtr port, double timeStamp, const unsigned char* message, unsigned int nBytes)
{
    if (gMidiOutPort != nullptr)
    {
        gMidiOutPortSendFunc(gMidiOutPort, message, nBytes);
    }

    EnterCriticalSection(&gCriticalSection);
    for (unsigned int i = 0; i < nBytes; i++)
    {
        cout << "Byte " << i << " = " << (int)message[i] << ", ";
    }

    if (nBytes > 0)
    {
        cout << "timestamp = " << timeStamp << endl;
    }
    LeaveCriticalSection(&gCriticalSection);
}

int main()
{
    HINSTANCE dllHandle = NULL;
    WinRTMidiPtr midiPtr = nullptr;
    WinRTMidiInPortPtr midiInPort = nullptr;

    //Load the WinRTMidi dll

    //Load the WinRTMidi dll
    if (windows10orGreaterWithManifest())
    {
        dllHandle = LoadLibrary(L"WinRTMidi.dll");
    }

    if (NULL == dllHandle)
    {
        cout << "Unable to load WinRTMidi.dll" << endl;
        goto cleanup;
    }

    InitializeCriticalSection(&gCriticalSection);

    // GetWinRTMidi DLL function pointers. Error checking needs to be added!
    //Get pointer to the WinRTMidiInitializeFunc function using GetProcAddress:
    gMidiInitFunc = reinterpret_cast<WinRTMidiInitializeFunc>(::GetProcAddress(dllHandle, "winrt_initialize_midi"));

    //Get pointer to the WinRTMidiFreeFunc function using GetProcAddress:
    gMidiFreeFunc = reinterpret_cast<WinRTMidiFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi"));

    //Get pointer to the WinRTMidiGetPortWatcherFunc function using GetProcAddress:
    gMidiGetPortWatcher = reinterpret_cast<WinRTMidiGetPortWatcherFunc>(::GetProcAddress(dllHandle, "winrt_get_portwatcher"));

    //Get pointer to the WinRTMidiInPortOpenFunc function using GetProcAddress:
    gMidiInPortOpenFunc = reinterpret_cast<WinRTMidiInPortOpenFunc>(::GetProcAddress(dllHandle, "winrt_open_midi_in_port"));

    //Get pointer to the WinRTMidiInPortFreeFunc function using GetProcAddress:
    gMidiInPortFreeFunc = reinterpret_cast<WinRTMidiInPortFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi_in_port"));

    //Get pointer to the WinRTMidiOutPortOpenFunc function using GetProcAddress:
    gMidiOutPortOpenFunc = reinterpret_cast<WinRTMidiOutPortOpenFunc>(::GetProcAddress(dllHandle, "winrt_open_midi_out_port"));

    //Get pointer to the WinRTMidiOutPortFreeFunc function using GetProcAddress:
    gMidiOutPortFreeFunc = reinterpret_cast<WinRTMidiOutPortFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi_out_port"));

    //Get pointer to the WinRTMidiOutPortSendFunc function using GetProcAddress:
    gMidiOutPortSendFunc = reinterpret_cast<WinRTMidiOutPortSendFunc>(::GetProcAddress(dllHandle, "winrt_midi_out_port_send"));

    //Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
    gWatcherPortCountFunc = reinterpret_cast<WinRTWatcherPortCountFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_count"));

    //Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
    gWatcherPortNameFunc = reinterpret_cast<WinRTWatcherPortNameFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_name"));

    //Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
    gWatcherPortTypeFunc = reinterpret_cast<WinRTWatcherPortTypeFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_type"));

    // initialize Midi interface
    WinRTMidiErrorType result = gMidiInitFunc(midiPortChangedCallback, &midiPtr);
    if(result != WINRT_NO_ERROR)
    {
        cout << "Unable to initialize WinRTMidi" << endl;
        goto cleanup;
    }

    // open midi in port 0
    result = gMidiInPortOpenFunc(midiPtr, 0, midiInCallback, &midiInPort);
    if (result != WINRT_NO_ERROR)
    {
        cout << "Unable to create Midi In port" << endl;
        goto cleanup;
    }

    // open midi out port 0
    result = gMidiOutPortOpenFunc(midiPtr, 0, &gMidiOutPort);
    if (result != WINRT_NO_ERROR)
    {
        cout << "Unable to create Midi Out port" << endl;
        goto cleanup;
    }

    // example on how get midi port info
    const WinRTMidiPortWatcherPtr watcher = gMidiGetPortWatcher(midiPtr, In);
    if (watcher != nullptr)
    {
        unsigned int numPorts = gWatcherPortCountFunc(watcher);
        if (numPorts > 0)
        {
            const char* name = gWatcherPortNameFunc(watcher, 0);
        }
    }

cleanup:

    // process midi until user presses key on keyboard
    cout << "Press any key to exit..." << endl;
    char c = _getch();

    // clean up midi objects
    // okay to call with nullptrs
    if(gMidiOutPortFreeFunc)
    {
        gMidiOutPortFreeFunc(gMidiOutPort);
    }

    if(gMidiInPortFreeFunc)
    {
        gMidiInPortFreeFunc(midiInPort);
    }

    if(gMidiFreeFunc)
    {
        gMidiFreeFunc(midiPtr);
    }

    //Free the library:
    if (dllHandle)
    {
        FreeLibrary(dllHandle);
    }

    DeleteCriticalSection(&gCriticalSection);

    return 0;
}<commit_msg>code formatting<commit_after>// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************

#include "stdafx.h"
#include "WinRTMidi.h"
#include "WindowsVersionHelper.h"
#include <iostream>
#include <string>
#include <conio.h>

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

using namespace std;
using namespace WinRT;

CRITICAL_SECTION gCriticalSection;

// WinRTMidi DLL function pointers
WinRTWatcherPortCountFunc   gWatcherPortCountFunc = nullptr;
WinRTWatcherPortNameFunc    gWatcherPortNameFunc = nullptr;
WinRTWatcherPortTypeFunc    gWatcherPortTypeFunc = nullptr;
WinRTMidiInitializeFunc     gMidiInitFunc = nullptr;
WinRTMidiFreeFunc           gMidiFreeFunc = nullptr;
WinRTMidiGetPortWatcherFunc gMidiGetPortWatcher = nullptr;
WinRTMidiInPortOpenFunc     gMidiInPortOpenFunc = nullptr;
WinRTMidiInPortFreeFunc     gMidiInPortFreeFunc = nullptr;
WinRTMidiOutPortOpenFunc    gMidiOutPortOpenFunc = nullptr;
WinRTMidiOutPortFreeFunc    gMidiOutPortFreeFunc = nullptr;
WinRTMidiOutPortSendFunc    gMidiOutPortSendFunc = nullptr;

// Midi Out port
WinRTMidiOutPortPtr gMidiOutPort = nullptr;

void printPortNames(const WinRTMidiPortWatcherPtr watcher)
{
    if(watcher == nullptr)
    {
        return;
    }

    WinRTMidiPortType type = gWatcherPortTypeFunc(watcher);
    if(type == In)
    {
        cout << "MIDI In Ports" << endl;
    }
    else
    {
        cout << "MIDI Out Ports" << endl;
    }

    int nPorts = gWatcherPortCountFunc(watcher);
    for (int i = 0; i < nPorts; i++)
    {
        const char* name = gWatcherPortNameFunc(watcher, i);
        cout << i << ": " << gWatcherPortNameFunc(watcher, i) << endl;
    }

    cout << endl;
}

void midiPortChangedCallback(const WinRTMidiPortWatcherPtr portWatcher, WinRTMidiPortUpdateType update)
{
    EnterCriticalSection(&gCriticalSection);
    string portName = gWatcherPortTypeFunc(portWatcher) == In ? "In" : "Out";

    switch (update)
    {
    case PortAdded:
        cout << "***MIDI " << portName << " port added***" << endl;
        break;

    case PortRemoved:
        cout << "***MIDI " << portName << " port removed***" << endl;
        break;

    case EnumerationComplete:
        cout << "***MIDI " << portName << " port enumeration complete***" << endl;
        break;
    }

    printPortNames(portWatcher);
    LeaveCriticalSection(&gCriticalSection);
}

void midiInCallback(const WinRTMidiInPortPtr port, double timeStamp, const unsigned char* message, unsigned int nBytes)
{
    if(gMidiOutPort != nullptr)
    {
        gMidiOutPortSendFunc(gMidiOutPort, message, nBytes);
    }

    EnterCriticalSection(&gCriticalSection);
    for (unsigned int i = 0; i < nBytes; i++)
    {
        cout << "Byte " << i << " = " << (int)message[i] << ", ";
    }

    if(nBytes > 0)
    {
        cout << "timestamp = " << timeStamp << endl;
    }
    LeaveCriticalSection(&gCriticalSection);
}

int main()
{
    HINSTANCE dllHandle = NULL;
    WinRTMidiPtr midiPtr = nullptr;
    WinRTMidiInPortPtr midiInPort = nullptr;

    //Load the WinRTMidi dll

    //Load the WinRTMidi dll
    if(windows10orGreaterWithManifest())
    {
        dllHandle = LoadLibrary(L"WinRTMidi.dll");
    }

    if(NULL == dllHandle)
    {
        cout << "Unable to load WinRTMidi.dll" << endl;
        goto cleanup;
    }

    InitializeCriticalSection(&gCriticalSection);

    // GetWinRTMidi DLL function pointers. Error checking needs to be added!
    //Get pointer to the WinRTMidiInitializeFunc function using GetProcAddress:
    gMidiInitFunc = reinterpret_cast<WinRTMidiInitializeFunc>(::GetProcAddress(dllHandle, "winrt_initialize_midi"));

    //Get pointer to the WinRTMidiFreeFunc function using GetProcAddress:
    gMidiFreeFunc = reinterpret_cast<WinRTMidiFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi"));

    //Get pointer to the WinRTMidiGetPortWatcherFunc function using GetProcAddress:
    gMidiGetPortWatcher = reinterpret_cast<WinRTMidiGetPortWatcherFunc>(::GetProcAddress(dllHandle, "winrt_get_portwatcher"));

    //Get pointer to the WinRTMidiInPortOpenFunc function using GetProcAddress:
    gMidiInPortOpenFunc = reinterpret_cast<WinRTMidiInPortOpenFunc>(::GetProcAddress(dllHandle, "winrt_open_midi_in_port"));

    //Get pointer to the WinRTMidiInPortFreeFunc function using GetProcAddress:
    gMidiInPortFreeFunc = reinterpret_cast<WinRTMidiInPortFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi_in_port"));

    //Get pointer to the WinRTMidiOutPortOpenFunc function using GetProcAddress:
    gMidiOutPortOpenFunc = reinterpret_cast<WinRTMidiOutPortOpenFunc>(::GetProcAddress(dllHandle, "winrt_open_midi_out_port"));

    //Get pointer to the WinRTMidiOutPortFreeFunc function using GetProcAddress:
    gMidiOutPortFreeFunc = reinterpret_cast<WinRTMidiOutPortFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi_out_port"));

    //Get pointer to the WinRTMidiOutPortSendFunc function using GetProcAddress:
    gMidiOutPortSendFunc = reinterpret_cast<WinRTMidiOutPortSendFunc>(::GetProcAddress(dllHandle, "winrt_midi_out_port_send"));

    //Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
    gWatcherPortCountFunc = reinterpret_cast<WinRTWatcherPortCountFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_count"));

    //Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
    gWatcherPortNameFunc = reinterpret_cast<WinRTWatcherPortNameFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_name"));

    //Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
    gWatcherPortTypeFunc = reinterpret_cast<WinRTWatcherPortTypeFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_type"));

    // initialize Midi interface
    WinRTMidiErrorType result = gMidiInitFunc(midiPortChangedCallback, &midiPtr);
    if(result != WINRT_NO_ERROR)
    {
        cout << "Unable to initialize WinRTMidi" << endl;
        goto cleanup;
    }

    // open midi in port 0
    result = gMidiInPortOpenFunc(midiPtr, 0, midiInCallback, &midiInPort);
    if(result != WINRT_NO_ERROR)
    {
        cout << "Unable to create Midi In port" << endl;
        goto cleanup;
    }

    // open midi out port 0
    result = gMidiOutPortOpenFunc(midiPtr, 0, &gMidiOutPort);
    if(result != WINRT_NO_ERROR)
    {
        cout << "Unable to create Midi Out port" << endl;
        goto cleanup;
    }

    // example on how get midi port info
    const WinRTMidiPortWatcherPtr watcher = gMidiGetPortWatcher(midiPtr, In);
    if(watcher != nullptr)
    {
        unsigned int numPorts = gWatcherPortCountFunc(watcher);
        if(numPorts > 0)
        {
            const char* name = gWatcherPortNameFunc(watcher, 0);
        }
    }

cleanup:

    // process midi until user presses key on keyboard
    cout << "Press any key to exit..." << endl;
    char c = _getch();

    // clean up midi objects
    // okay to call with nullptrs
    if(gMidiOutPortFreeFunc)
    {
        gMidiOutPortFreeFunc(gMidiOutPort);
    }

    if(gMidiInPortFreeFunc)
    {
        gMidiInPortFreeFunc(midiInPort);
    }

    if(gMidiFreeFunc)
    {
        gMidiFreeFunc(midiPtr);
    }

    //Free the library:
    if(dllHandle)
    {
        FreeLibrary(dllHandle);
    }

    DeleteCriticalSection(&gCriticalSection);

    return 0;
}<|endoftext|>