<commit_before>/*
 *  vaapiencoder_base.cpp - basic va encoder for video
 *
 *  Copyright (C) 2013-2014 Intel Corporation
 *    Author: Wind Yuan <feng.yuan@intel.com>
 *    Author: Xu Guangxin <guangxin.xu@intel.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *
 *  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., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301 USA
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "vaapiencoder_base.h"
#include <assert.h>
#include <stdint.h>
#include "common/common_def.h"
#include "common/utils.h"
#include "scopedlogger.h"
#include "vaapicodedbuffer.h"
#include "vaapi/vaapidisplay.h"
#include "vaapi/vaapicontext.h"
#include "vaapi/vaapiutils.h"

const uint32_t MaxOutputBuffer=5;
namespace YamiMediaCodec{
VaapiEncoderBase::VaapiEncoderBase():
    m_entrypoint(VAEntrypointEncSlice),
    m_maxOutputBuffer(MaxOutputBuffer),
    m_maxCodedbufSize(0)
{
    FUNC_ENTER();
    m_externalDisplay.handle = 0,
    m_externalDisplay.type = NATIVE_DISPLAY_AUTO,

    m_videoParamCommon.size = sizeof(m_videoParamCommon);
    m_videoParamCommon.rawFormat = RAW_FORMAT_NV12;
    m_videoParamCommon.frameRate.frameRateNum = 30;
    m_videoParamCommon.frameRate.frameRateDenom = 1;
    m_videoParamCommon.intraPeriod = 15;
    m_videoParamCommon.rcMode = RATE_CONTROL_CQP;
    m_videoParamCommon.rcParams.initQP = 26;
    m_videoParamCommon.rcParams.minQP = 1;
    m_videoParamCommon.rcParams.targetPercentage= 70;
    m_videoParamCommon.rcParams.windowSize = 500;
    m_videoParamCommon.rcParams.disableBitsStuffing = 1;
    m_videoParamCommon.cyclicFrameInterval = 30;
    m_videoParamCommon.refreshType = VIDEO_ENC_NONIR;
    m_videoParamCommon.airParams.airAuto = 1;

    updateMaxOutputBufferCount();
}

VaapiEncoderBase::~VaapiEncoderBase()
{
    cleanupVA();
    INFO("~VaapiEncoderBase");
}

void VaapiEncoderBase::setNativeDisplay(NativeDisplay * nativeDisplay)
{
    if (!nativeDisplay || nativeDisplay->type == NATIVE_DISPLAY_AUTO)
        return;

    m_externalDisplay = *nativeDisplay;
}

Encode_Status VaapiEncoderBase::start(void)
{
    FUNC_ENTER();
    if (!initVA())
        return ENCODE_FAIL;

    return ENCODE_SUCCESS;
}

void VaapiEncoderBase::flush(void)
{
    AutoLock l(m_lock);
    m_output.clear();
}

Encode_Status VaapiEncoderBase::stop(void)
{
    FUNC_ENTER();
    cleanupVA();
    return ENCODE_SUCCESS;
}

bool VaapiEncoderBase::isBusy()
{
    AutoLock l(m_lock);
    return m_output.size() >= m_maxOutputBuffer;
}

Encode_Status VaapiEncoderBase::encode(VideoEncRawBuffer *inBuffer)
{
    FUNC_ENTER();

    if (!inBuffer || !inBuffer->data && !inBuffer->size) {
        // XXX handle EOS when there is B frames
        inBuffer->bufAvailable = true;
        return ENCODE_SUCCESS;
    }
    VideoFrameRawData frame;
    if (!fillFrameRawData(&frame, inBuffer->fourcc, width(), height(), inBuffer->data))
        return ENCODE_INVALID_PARAMS;
    inBuffer->bufAvailable = true;
    if (inBuffer->forceKeyFrame)
        frame.flags |= VIDEO_FRAME_FLAGS_KEY;
    frame.timeStamp = inBuffer->timeStamp;
    return encode(&frame);
}

Encode_Status VaapiEncoderBase::encode(VideoFrameRawData* frame)
{
    if (!frame || !frame->width || !frame->height || !frame->fourcc)
        return ENCODE_INVALID_PARAMS;

    FUNC_ENTER();
    Encode_Status ret;

    if (isBusy())
        return ENCODE_IS_BUSY;
    SurfacePtr surface = createSurface(frame);
    if (!surface)
        return ENCODE_NO_MEMORY;
    return doEncode(surface, frame->timeStamp, frame->flags & VIDEO_FRAME_FLAGS_KEY);
}

Encode_Status VaapiEncoderBase::getParameters(VideoParamConfigType type, Yami_PTR videoEncParams)
{
    FUNC_ENTER();
    Encode_Status ret = ENCODE_INVALID_PARAMS;
    if (!videoEncParams)
        return ret;

    DEBUG("type = 0x%08x", type);
    switch (type) {
    case VideoParamsTypeCommon: {
        VideoParamsCommon* common = (VideoParamsCommon*)videoEncParams;
        if (common->size == sizeof(VideoParamsCommon)) {
            PARAMETER_ASSIGN(*common, m_videoParamCommon);
            ret = ENCODE_SUCCESS;
        }
        break;
    }
    default:
        ret = ENCODE_SUCCESS;
        break;
    }
    return ret;
}

Encode_Status VaapiEncoderBase::setParameters(VideoParamConfigType type, Yami_PTR videoEncParams)
{
    FUNC_ENTER();
    Encode_Status ret = ENCODE_SUCCESS;
    if (!videoEncParams)
        return ret;

    DEBUG("type = 0x%08x", type);
    switch (type) {
    case VideoParamsTypeCommon: {
        VideoParamsCommon* common = (VideoParamsCommon*)videoEncParams;
        if (common->size == sizeof(VideoParamsCommon)) {
            PARAMETER_ASSIGN(m_videoParamCommon, *common);
            //dirty work around, force rcmod before we support more
            m_videoParamCommon.rcMode = RATE_CONTROL_CQP;
            //end
        } else
            ret = ENCODE_INVALID_PARAMS;
        m_maxCodedbufSize = 0; // resolution may change, recalculate max codec buffer size when it is requested
        break;
    }
    case VideoConfigTypeFrameRate: {
        VideoConfigFrameRate* frameRateConfig = (VideoConfigFrameRate*)videoEncParams;
        if (frameRateConfig->size == sizeof(VideoConfigFrameRate)) {
            m_videoParamCommon.frameRate = frameRateConfig->frameRate;
        } else
            ret = ENCODE_INVALID_PARAMS;
        }
        break;
    case VideoConfigTypeBitRate: {
        VideoConfigBitRate* rcParamsConfig = (VideoConfigBitRate*)videoEncParams;
        if (rcParamsConfig->size == sizeof(VideoConfigFrameRate)) {
            m_videoParamCommon.rcParams = rcParamsConfig->rcParams;
        } else
            ret = ENCODE_INVALID_PARAMS;
        }
        break;
    default:
        ret = ENCODE_INVALID_PARAMS;
        break;
    }
    INFO("bitrate: %d", bitRate());
    return ret;
}

Encode_Status VaapiEncoderBase::setConfig(VideoParamConfigType type, Yami_PTR videoEncConfig)
{
    FUNC_ENTER();
    DEBUG("type = %d", type);
    return ENCODE_SUCCESS;
}

Encode_Status VaapiEncoderBase::getConfig(VideoParamConfigType type, Yami_PTR videoEncConfig)
{
    FUNC_ENTER();
    return ENCODE_SUCCESS;
}

Encode_Status VaapiEncoderBase::getMaxOutSize(uint32_t *maxSize)
{
    FUNC_ENTER();
    *maxSize = 0;
    return ENCODE_SUCCESS;
}

SurfacePtr VaapiEncoderBase::createSurface(uint32_t fourcc)
{
    VASurfaceAttrib attrib;
    VaapiChromaType chroma;

    attrib.flags = VA_SURFACE_ATTRIB_SETTABLE;
    attrib.type = VASurfaceAttribPixelFormat;
    attrib.value.type = VAGenericValueTypeInteger;
    attrib.value.value.i = fourcc;

    switch(fourcc) {
    case VA_FOURCC_NV12:
    case VA_FOURCC_I420:
        chroma = VAAPI_CHROMA_TYPE_YUV420;
    break;
    case VA_FOURCC_YUY2:
        chroma = VAAPI_CHROMA_TYPE_YUV422;
    break;
    default:
        ASSERT(0);
        break;
    }
    return VaapiSurface::create(m_display, chroma,
                                m_videoParamCommon.resolution.width, m_videoParamCommon.resolution.height, &attrib, 1);

}

SurfacePtr VaapiEncoderBase::createSurface(VideoFrameRawData* frame)
{
    SurfacePtr surface = createSurface(frame->fourcc);
    SurfacePtr nil;
    if (!surface)
        return nil;

    ImagePtr image = VaapiImage::derive(surface);
    if (!image) {
        ERROR("VaapiImage::derive() failed");
        return nil;
    }
    ImageRawPtr raw = image->map();
    if (!raw) {
        ERROR("image->map() failed");
        return nil;
    }

    uint8_t* src = reinterpret_cast<uint8_t*>(frame->handle);
    if (!raw->copyFrom(src, frame->offset, frame->pitch)) {
        ERROR("copyfrom in buffer failed");
        return nil;
    }
    return surface;
}

void VaapiEncoderBase::fill(VAEncMiscParameterHRD* hrd) const
{
    hrd->buffer_size = m_videoParamCommon.rcParams.bitRate * m_videoParamCommon.rcParams.windowSize/1000;
    hrd->initial_buffer_fullness = hrd->buffer_size/2;
    DEBUG("bitRate: %d, hrd->buffer_size: %d, hrd->initial_buffer_fullness: %d",
        m_videoParamCommon.rcParams.bitRate, hrd->buffer_size,hrd->initial_buffer_fullness);
}

void VaapiEncoderBase::fill(VAEncMiscParameterRateControl* rateControl) const
{
    rateControl->bits_per_second = m_videoParamCommon.rcParams.bitRate;
    rateControl->initial_qp =  m_videoParamCommon.rcParams.initQP;
    rateControl->min_qp =  m_videoParamCommon.rcParams.minQP;
    /*FIXME: where to find max_qp */
    rateControl->window_size = m_videoParamCommon.rcParams.windowSize;
    rateControl->target_percentage = m_videoParamCommon.rcParams.targetPercentage;
    rateControl->rc_flags.bits.disable_frame_skip = m_videoParamCommon.rcParams.disableFrameSkip;
    rateControl->rc_flags.bits.disable_bit_stuffing = m_videoParamCommon.rcParams.disableBitsStuffing;
}

/* Generates additional control parameters */
bool VaapiEncoderBase::ensureMiscParams (VaapiEncPicture* picture)
{
    VAEncMiscParameterHRD* hrd;
    if (!picture->newMisc(VAEncMiscParameterTypeHRD, hrd))
        return false;
    fill(hrd);
    VideoRateControl mode = rateControlMode();
    if (mode == RATE_CONTROL_CBR ||
            mode == RATE_CONTROL_VBR) {
        VAEncMiscParameterRateControl* rateControl;
        if (!picture->newMisc(VAEncMiscParameterTypeRateControl, rateControl))
            return false;
        fill(rateControl);
    }
    return true;
}

struct ProfileMapItem {
    VaapiProfile vaapiProfile;
    VAProfile    vaProfile;
};

const ProfileMapItem g_profileMap[] =
{
    {VAAPI_PROFILE_H264_BASELINE,  VAProfileH264Baseline},
    {VAAPI_PROFILE_H264_CONSTRAINED_BASELINE,VAProfileH264ConstrainedBaseline},
    {VAAPI_PROFILE_H264_MAIN, VAProfileH264Main},
    {VAAPI_PROFILE_H264_HIGH,VAProfileH264High},
    {VAAPI_PROFILE_JPEG_BASELINE,VAProfileJPEGBaseline},
};

VaapiProfile VaapiEncoderBase::profile() const
{
    for (int i = 0; i < N_ELEMENTS(g_profileMap); i++) {
        if (m_videoParamCommon.profile == g_profileMap[i].vaProfile)
            return g_profileMap[i].vaapiProfile;
    }
    return VAAPI_PROFILE_UNKNOWN;
}

void VaapiEncoderBase::cleanupVA()
{
    m_context.reset();
    m_display.reset();
}

bool VaapiEncoderBase::initVA()
{
    VAConfigAttrib attrib, *pAttrib = NULL;
    int32_t attribCount = 0;
    FUNC_ENTER();

    m_display = VaapiDisplay::create(m_externalDisplay);
    if (!m_display) {
        ERROR("failed to create display");
        return false;
    }

    if (RATE_CONTROL_NONE != m_videoParamCommon.rcMode) {
        attrib.type = VAConfigAttribRateControl;
        attrib.value = m_videoParamCommon.rcMode;
        pAttrib = &attrib;
        attribCount = 1;
    }
    ConfigPtr config = VaapiConfig::create(m_display, m_videoParamCommon.profile, m_entrypoint, pAttrib, attribCount);
    if (!config) {
        ERROR("failed to create config");
        return false;
    }

    m_context = VaapiContext::create(config,
                             m_videoParamCommon.resolution.width,
                             m_videoParamCommon.resolution.height,
                             VA_PROGRESSIVE, 0, 0);
    if (!m_context) {
        ERROR("failed to create context");
        return false;
    }
    return true;
}

Encode_Status VaapiEncoderBase::getOutput(VideoEncOutputBuffer * outBuffer, bool withWait)
{
    bool isEmpty;
    FUNC_ENTER();
    if (!outBuffer)
        return ENCODE_INVALID_PARAMS;

    {
        AutoLock l(m_lock);
        isEmpty = m_output.empty();
        INFO("output queue size: %ld\n", m_output.size());
    }

    if (isEmpty) {
        if (outBuffer->format == OUTPUT_CODEC_DATA)
           return getCodecConfig(outBuffer);
        return ENCODE_BUFFER_NO_MORE;
    }

    PicturePtr& picture = m_output.front();
    picture->sync();
    Encode_Status ret = picture->getOutput(outBuffer);
    if (ret != ENCODE_SUCCESS)
        return ret;
    if (outBuffer->format != OUTPUT_CODEC_DATA) {
        AutoLock l(m_lock);
        m_output.pop_front();
    }
    return ENCODE_SUCCESS;
}

Encode_Status VaapiEncoderBase::getCodecConfig(VideoEncOutputBuffer * outBuffer)
{
    ASSERT(outBuffer && (outBuffer->format == OUTPUT_CODEC_DATA));
    outBuffer->dataSize  = 0;
    return ENCODE_SUCCESS;
}

}
<commit_msg>fix a typo in VaapiEncoderBase::setParameters<commit_after>/*
 *  vaapiencoder_base.cpp - basic va encoder for video
 *
 *  Copyright (C) 2013-2014 Intel Corporation
 *    Author: Wind Yuan <feng.yuan@intel.com>
 *    Author: Xu Guangxin <guangxin.xu@intel.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *
 *  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., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301 USA
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "vaapiencoder_base.h"
#include <assert.h>
#include <stdint.h>
#include "common/common_def.h"
#include "common/utils.h"
#include "scopedlogger.h"
#include "vaapicodedbuffer.h"
#include "vaapi/vaapidisplay.h"
#include "vaapi/vaapicontext.h"
#include "vaapi/vaapiutils.h"

const uint32_t MaxOutputBuffer=5;
namespace YamiMediaCodec{
VaapiEncoderBase::VaapiEncoderBase():
    m_entrypoint(VAEntrypointEncSlice),
    m_maxOutputBuffer(MaxOutputBuffer),
    m_maxCodedbufSize(0)
{
    FUNC_ENTER();
    m_externalDisplay.handle = 0,
    m_externalDisplay.type = NATIVE_DISPLAY_AUTO,

    m_videoParamCommon.size = sizeof(m_videoParamCommon);
    m_videoParamCommon.rawFormat = RAW_FORMAT_NV12;
    m_videoParamCommon.frameRate.frameRateNum = 30;
    m_videoParamCommon.frameRate.frameRateDenom = 1;
    m_videoParamCommon.intraPeriod = 15;
    m_videoParamCommon.rcMode = RATE_CONTROL_CQP;
    m_videoParamCommon.rcParams.initQP = 26;
    m_videoParamCommon.rcParams.minQP = 1;
    m_videoParamCommon.rcParams.targetPercentage= 70;
    m_videoParamCommon.rcParams.windowSize = 500;
    m_videoParamCommon.rcParams.disableBitsStuffing = 1;
    m_videoParamCommon.cyclicFrameInterval = 30;
    m_videoParamCommon.refreshType = VIDEO_ENC_NONIR;
    m_videoParamCommon.airParams.airAuto = 1;

    updateMaxOutputBufferCount();
}

VaapiEncoderBase::~VaapiEncoderBase()
{
    cleanupVA();
    INFO("~VaapiEncoderBase");
}

void VaapiEncoderBase::setNativeDisplay(NativeDisplay * nativeDisplay)
{
    if (!nativeDisplay || nativeDisplay->type == NATIVE_DISPLAY_AUTO)
        return;

    m_externalDisplay = *nativeDisplay;
}

Encode_Status VaapiEncoderBase::start(void)
{
    FUNC_ENTER();
    if (!initVA())
        return ENCODE_FAIL;

    return ENCODE_SUCCESS;
}

void VaapiEncoderBase::flush(void)
{
    AutoLock l(m_lock);
    m_output.clear();
}

Encode_Status VaapiEncoderBase::stop(void)
{
    FUNC_ENTER();
    cleanupVA();
    return ENCODE_SUCCESS;
}

bool VaapiEncoderBase::isBusy()
{
    AutoLock l(m_lock);
    return m_output.size() >= m_maxOutputBuffer;
}

Encode_Status VaapiEncoderBase::encode(VideoEncRawBuffer *inBuffer)
{
    FUNC_ENTER();

    if (!inBuffer || !inBuffer->data && !inBuffer->size) {
        // XXX handle EOS when there is B frames
        inBuffer->bufAvailable = true;
        return ENCODE_SUCCESS;
    }
    VideoFrameRawData frame;
    if (!fillFrameRawData(&frame, inBuffer->fourcc, width(), height(), inBuffer->data))
        return ENCODE_INVALID_PARAMS;
    inBuffer->bufAvailable = true;
    if (inBuffer->forceKeyFrame)
        frame.flags |= VIDEO_FRAME_FLAGS_KEY;
    frame.timeStamp = inBuffer->timeStamp;
    return encode(&frame);
}

Encode_Status VaapiEncoderBase::encode(VideoFrameRawData* frame)
{
    if (!frame || !frame->width || !frame->height || !frame->fourcc)
        return ENCODE_INVALID_PARAMS;

    FUNC_ENTER();
    Encode_Status ret;

    if (isBusy())
        return ENCODE_IS_BUSY;
    SurfacePtr surface = createSurface(frame);
    if (!surface)
        return ENCODE_NO_MEMORY;
    return doEncode(surface, frame->timeStamp, frame->flags & VIDEO_FRAME_FLAGS_KEY);
}

Encode_Status VaapiEncoderBase::getParameters(VideoParamConfigType type, Yami_PTR videoEncParams)
{
    FUNC_ENTER();
    Encode_Status ret = ENCODE_INVALID_PARAMS;
    if (!videoEncParams)
        return ret;

    DEBUG("type = 0x%08x", type);
    switch (type) {
    case VideoParamsTypeCommon: {
        VideoParamsCommon* common = (VideoParamsCommon*)videoEncParams;
        if (common->size == sizeof(VideoParamsCommon)) {
            PARAMETER_ASSIGN(*common, m_videoParamCommon);
            ret = ENCODE_SUCCESS;
        }
        break;
    }
    default:
        ret = ENCODE_SUCCESS;
        break;
    }
    return ret;
}

Encode_Status VaapiEncoderBase::setParameters(VideoParamConfigType type, Yami_PTR videoEncParams)
{
    FUNC_ENTER();
    Encode_Status ret = ENCODE_SUCCESS;
    if (!videoEncParams)
        return ret;

    DEBUG("type = 0x%08x", type);
    switch (type) {
    case VideoParamsTypeCommon: {
        VideoParamsCommon* common = (VideoParamsCommon*)videoEncParams;
        if (common->size == sizeof(VideoParamsCommon)) {
            PARAMETER_ASSIGN(m_videoParamCommon, *common);
            //dirty work around, force rcmod before we support more
            m_videoParamCommon.rcMode = RATE_CONTROL_CQP;
            //end
        } else
            ret = ENCODE_INVALID_PARAMS;
        m_maxCodedbufSize = 0; // resolution may change, recalculate max codec buffer size when it is requested
        break;
    }
    case VideoConfigTypeFrameRate: {
        VideoConfigFrameRate* frameRateConfig = (VideoConfigFrameRate*)videoEncParams;
        if (frameRateConfig->size == sizeof(VideoConfigFrameRate)) {
            m_videoParamCommon.frameRate = frameRateConfig->frameRate;
        } else
            ret = ENCODE_INVALID_PARAMS;
        }
        break;
    case VideoConfigTypeBitRate: {
        VideoConfigBitRate* rcParamsConfig = (VideoConfigBitRate*)videoEncParams;
        if (rcParamsConfig->size == sizeof(VideoConfigBitRate)) {
            m_videoParamCommon.rcParams = rcParamsConfig->rcParams;
        } else
            ret = ENCODE_INVALID_PARAMS;
        }
        break;
    default:
        ret = ENCODE_INVALID_PARAMS;
        break;
    }
    INFO("bitrate: %d", bitRate());
    return ret;
}

Encode_Status VaapiEncoderBase::setConfig(VideoParamConfigType type, Yami_PTR videoEncConfig)
{
    FUNC_ENTER();
    DEBUG("type = %d", type);
    return ENCODE_SUCCESS;
}

Encode_Status VaapiEncoderBase::getConfig(VideoParamConfigType type, Yami_PTR videoEncConfig)
{
    FUNC_ENTER();
    return ENCODE_SUCCESS;
}

Encode_Status VaapiEncoderBase::getMaxOutSize(uint32_t *maxSize)
{
    FUNC_ENTER();
    *maxSize = 0;
    return ENCODE_SUCCESS;
}

SurfacePtr VaapiEncoderBase::createSurface(uint32_t fourcc)
{
    VASurfaceAttrib attrib;
    VaapiChromaType chroma;

    attrib.flags = VA_SURFACE_ATTRIB_SETTABLE;
    attrib.type = VASurfaceAttribPixelFormat;
    attrib.value.type = VAGenericValueTypeInteger;
    attrib.value.value.i = fourcc;

    switch(fourcc) {
    case VA_FOURCC_NV12:
    case VA_FOURCC_I420:
        chroma = VAAPI_CHROMA_TYPE_YUV420;
    break;
    case VA_FOURCC_YUY2:
        chroma = VAAPI_CHROMA_TYPE_YUV422;
    break;
    default:
        ASSERT(0);
        break;
    }
    return VaapiSurface::create(m_display, chroma,
                                m_videoParamCommon.resolution.width, m_videoParamCommon.resolution.height, &attrib, 1);

}

SurfacePtr VaapiEncoderBase::createSurface(VideoFrameRawData* frame)
{
    SurfacePtr surface = createSurface(frame->fourcc);
    SurfacePtr nil;
    if (!surface)
        return nil;

    ImagePtr image = VaapiImage::derive(surface);
    if (!image) {
        ERROR("VaapiImage::derive() failed");
        return nil;
    }
    ImageRawPtr raw = image->map();
    if (!raw) {
        ERROR("image->map() failed");
        return nil;
    }

    uint8_t* src = reinterpret_cast<uint8_t*>(frame->handle);
    if (!raw->copyFrom(src, frame->offset, frame->pitch)) {
        ERROR("copyfrom in buffer failed");
        return nil;
    }
    return surface;
}

void VaapiEncoderBase::fill(VAEncMiscParameterHRD* hrd) const
{
    hrd->buffer_size = m_videoParamCommon.rcParams.bitRate * m_videoParamCommon.rcParams.windowSize/1000;
    hrd->initial_buffer_fullness = hrd->buffer_size/2;
    DEBUG("bitRate: %d, hrd->buffer_size: %d, hrd->initial_buffer_fullness: %d",
        m_videoParamCommon.rcParams.bitRate, hrd->buffer_size,hrd->initial_buffer_fullness);
}

void VaapiEncoderBase::fill(VAEncMiscParameterRateControl* rateControl) const
{
    rateControl->bits_per_second = m_videoParamCommon.rcParams.bitRate;
    rateControl->initial_qp =  m_videoParamCommon.rcParams.initQP;
    rateControl->min_qp =  m_videoParamCommon.rcParams.minQP;
    /*FIXME: where to find max_qp */
    rateControl->window_size = m_videoParamCommon.rcParams.windowSize;
    rateControl->target_percentage = m_videoParamCommon.rcParams.targetPercentage;
    rateControl->rc_flags.bits.disable_frame_skip = m_videoParamCommon.rcParams.disableFrameSkip;
    rateControl->rc_flags.bits.disable_bit_stuffing = m_videoParamCommon.rcParams.disableBitsStuffing;
}

/* Generates additional control parameters */
bool VaapiEncoderBase::ensureMiscParams (VaapiEncPicture* picture)
{
    VAEncMiscParameterHRD* hrd;
    if (!picture->newMisc(VAEncMiscParameterTypeHRD, hrd))
        return false;
    fill(hrd);
    VideoRateControl mode = rateControlMode();
    if (mode == RATE_CONTROL_CBR ||
            mode == RATE_CONTROL_VBR) {
        VAEncMiscParameterRateControl* rateControl;
        if (!picture->newMisc(VAEncMiscParameterTypeRateControl, rateControl))
            return false;
        fill(rateControl);
    }
    return true;
}

struct ProfileMapItem {
    VaapiProfile vaapiProfile;
    VAProfile    vaProfile;
};

const ProfileMapItem g_profileMap[] =
{
    {VAAPI_PROFILE_H264_BASELINE,  VAProfileH264Baseline},
    {VAAPI_PROFILE_H264_CONSTRAINED_BASELINE,VAProfileH264ConstrainedBaseline},
    {VAAPI_PROFILE_H264_MAIN, VAProfileH264Main},
    {VAAPI_PROFILE_H264_HIGH,VAProfileH264High},
    {VAAPI_PROFILE_JPEG_BASELINE,VAProfileJPEGBaseline},
};

VaapiProfile VaapiEncoderBase::profile() const
{
    for (int i = 0; i < N_ELEMENTS(g_profileMap); i++) {
        if (m_videoParamCommon.profile == g_profileMap[i].vaProfile)
            return g_profileMap[i].vaapiProfile;
    }
    return VAAPI_PROFILE_UNKNOWN;
}

void VaapiEncoderBase::cleanupVA()
{
    m_context.reset();
    m_display.reset();
}

bool VaapiEncoderBase::initVA()
{
    VAConfigAttrib attrib, *pAttrib = NULL;
    int32_t attribCount = 0;
    FUNC_ENTER();

    m_display = VaapiDisplay::create(m_externalDisplay);
    if (!m_display) {
        ERROR("failed to create display");
        return false;
    }

    if (RATE_CONTROL_NONE != m_videoParamCommon.rcMode) {
        attrib.type = VAConfigAttribRateControl;
        attrib.value = m_videoParamCommon.rcMode;
        pAttrib = &attrib;
        attribCount = 1;
    }
    ConfigPtr config = VaapiConfig::create(m_display, m_videoParamCommon.profile, m_entrypoint, pAttrib, attribCount);
    if (!config) {
        ERROR("failed to create config");
        return false;
    }

    m_context = VaapiContext::create(config,
                             m_videoParamCommon.resolution.width,
                             m_videoParamCommon.resolution.height,
                             VA_PROGRESSIVE, 0, 0);
    if (!m_context) {
        ERROR("failed to create context");
        return false;
    }
    return true;
}

Encode_Status VaapiEncoderBase::getOutput(VideoEncOutputBuffer * outBuffer, bool withWait)
{
    bool isEmpty;
    FUNC_ENTER();
    if (!outBuffer)
        return ENCODE_INVALID_PARAMS;

    {
        AutoLock l(m_lock);
        isEmpty = m_output.empty();
        INFO("output queue size: %ld\n", m_output.size());
    }

    if (isEmpty) {
        if (outBuffer->format == OUTPUT_CODEC_DATA)
           return getCodecConfig(outBuffer);
        return ENCODE_BUFFER_NO_MORE;
    }

    PicturePtr& picture = m_output.front();
    picture->sync();
    Encode_Status ret = picture->getOutput(outBuffer);
    if (ret != ENCODE_SUCCESS)
        return ret;
    if (outBuffer->format != OUTPUT_CODEC_DATA) {
        AutoLock l(m_lock);
        m_output.pop_front();
    }
    return ENCODE_SUCCESS;
}

Encode_Status VaapiEncoderBase::getCodecConfig(VideoEncOutputBuffer * outBuffer)
{
    ASSERT(outBuffer && (outBuffer->format == OUTPUT_CODEC_DATA));
    outBuffer->dataSize  = 0;
    return ENCODE_SUCCESS;
}

}
<|endoftext|>


<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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 <stdarg.h>
#include "Assert.h"
#include "LuaEnvironment.h"
#include "StringUtils.h"
#include "LuaStack.h"
#include "Device.h"
#include "LuaResource.h"

namespace crown
{

//-----------------------------------------------------------------------------
CE_EXPORT int luaopen_libcrown(lua_State* /*L*/)
{
	LuaEnvironment* env = device()->lua_environment();

	load_int_setting(*env);
	load_float_setting(*env);
	load_string_setting(*env);

	load_vec2(*env);
	load_vec3(*env);
	load_mat4(*env);
	load_quat(*env);
	load_math(*env);

	load_mouse(*env);
	load_keyboard(*env);
	load_accelerometer(*env);

	load_device(*env);

	load_window(*env);

	return 1;
}

//-----------------------------------------------------------------------------
LuaEnvironment::LuaEnvironment() :
	m_state(luaL_newstate()),
	m_is_used(false)
{
	// Open Lua default libraries
	string::strncpy(m_error_buffer, "", 1024);
	string::strncpy(m_tmp_buffer, "", 1024);
}

//-----------------------------------------------------------------------------
void LuaEnvironment::init()
{
	// Open default libraries
	luaL_openlibs(m_state);
	// Open Crown library
	lua_cpcall(m_state, luaopen_libcrown, NULL);

	// load_buffer(class_system, string::strlen(class_system));
	// execute(0, 0);
	// load_buffer(commands_list, string::strlen(commands_list));
	// execute(0, 0);
	// load_buffer(get_cmd_by_name, string::strlen(get_cmd_by_name));
	// execute(0, 0);
	// load_buffer(tmp_print_table, string::strlen(tmp_print_table));
	// execute(0, 0);
	// load_buffer(count_all, string::strlen(count_all));
	// execute(0, 0);

	m_is_used = true;
}

//-----------------------------------------------------------------------------
void LuaEnvironment::shutdown()
{
	lua_close(m_state);

	m_is_used = false;
}

//-----------------------------------------------------------------------------
const char* LuaEnvironment::error()
{
	string::strncpy(m_tmp_buffer, m_error_buffer, 1024);
	string::strncpy(m_error_buffer, "", 1024);

	return m_tmp_buffer;
}

//-----------------------------------------------------------------------------
void LuaEnvironment::load(const LuaResource* lr)
{
	CE_ASSERT_NOT_NULL(lr);

	if (luaL_loadbuffer(m_state, (const char*) lr->code(), lr->size(), "") != 0)
	{
		lua_error();
	}

	if (lua_pcall(m_state, 0, 0, 0) != 0)
	{
		lua_error();
	}
}

//-----------------------------------------------------------------------------
void LuaEnvironment::call_global(const char* func, uint8_t argc, ...)
{
	CE_ASSERT_NOT_NULL(func);

	LuaStack stack(m_state);

	va_list vl;
	va_start(vl, argc);

	lua_getglobal(m_state, func);

	for (uint8_t i = 0; i < argc; i++)
	{
		const int type = va_arg(vl, int);
		switch (type)
		{
			case ARGUMENT_FLOAT:
			{
				stack.push_float(va_arg(vl, double));
				break;
			}
			default:
			{
				CE_ASSERT(false, "Oops, lua argument unknown");
				break;
			}
		}
	}

	va_end(vl);

	if (lua_pcall(m_state, argc, 0, 0) != 0)
	{
		lua_error();
	}
}

//-----------------------------------------------------------------------------
void LuaEnvironment::lua_error()
{
	string::strncpy(m_error_buffer, "", 1024);
	string::strncpy(m_error_buffer, lua_tostring(m_state, -1), 1024);
}

//-----------------------------------------------------------------------------
void LuaEnvironment::load_module_function(const char* module, const char* name, const lua_CFunction func)
{
	luaL_Reg entry[2];

	entry[0].name = name;
	entry[0].func = func;
	entry[1].name = NULL;
	entry[1].func = NULL;

	luaL_register(m_state, module, entry);
}

//-----------------------------------------------------------
void LuaEnvironment::load_module_enum(const char* /*module*/, const char* name, uint32_t value)
{
	lua_pushinteger(m_state, value);
	lua_setfield(m_state, -2, name);
}

const char* LuaEnvironment::class_system =  "function class(klass, super) "
    										"	if not klass then "
        									"		klass = {} "
                							"		local meta = {} "
        									"		meta.__call = function(self, ...) "
            								"			local object = {} "
            								"			setmetatable(object, klass) "
            								"			if object.init then object:init(...) end "
            								"			return object "
       										"		end "
        									"		setmetatable(klass, meta) "
    										"	end "
    										"	if super then "
        									"		for k,v in pairs(super) do "
            								"			klass[k] = v "
        									"		end "
    										"	end "
    										"	klass.__index = klass "
    										"	return klass "
											"end";

const char* LuaEnvironment::commands_list = "function get_all_commands() "
											"	local cmds = {}; "
											"	for class_name,class in pairs(_G) do "
											"		if type(class) == 'table' then "
			 								"			for func_name,func in pairs(class) do "
			 								"				if type(func) == 'function' then "
											"					cmds[#cmds+1] = class_name .. '.' .. func_name "
											"				end "
											"			end "
											"		end "
											"	end "
											"	return cmds "
											"end";

const char* LuaEnvironment::get_cmd_by_name = 	"function get_command_by_name(text) "
												"	local cmds = get_all_commands() "
												"	local results = {} "
												"	local index = 0 "
												"	for i,cmd in pairs(cmds) do "
												"		if string.find(cmd, text) then "
												"			results[index] = cmds[i] "
												"			index = index + 1 "
												"		end "
												"	end "
												"	return results "
												"end";

const char* LuaEnvironment::tmp_print_table =	"function print_table(table) "
												"	for k,v in pairs(table) do "
												"		print(v) "
												"	end "
												"end";

const char* LuaEnvironment::count_all = 	"function count_all(f) "
											"	local seen = {} "
											"	local count_table "
											"	count_table = function(t) "
											"		if seen[t] then return end "
											"		f(t) "
											"		seen[t] = true "
											"		for k,v in pairs(t) do "
											"			if type(v) == 'table' then "
											"				count_table(v) "
											"			elseif type(v) == 'userdata' then "
											"				f(v) "
											"			end "
											"		end "
											"	end "
											"	count_table(_G) "
											"end";

} // namespace crown<commit_msg>Add custom require() function to LuaEnvironment<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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 <stdarg.h>
#include "Assert.h"
#include "LuaEnvironment.h"
#include "StringUtils.h"
#include "LuaStack.h"
#include "Device.h"
#include "LuaResource.h"
#include "ResourceManager.h"

namespace crown
{

//-----------------------------------------------------------------------------
CE_EXPORT int luaopen_libcrown(lua_State* /*L*/)
{
	LuaEnvironment* env = device()->lua_environment();

	load_int_setting(*env);
	load_float_setting(*env);
	load_string_setting(*env);

	load_vec2(*env);
	load_vec3(*env);
	load_mat4(*env);
	load_quat(*env);
	load_math(*env);

	load_mouse(*env);
	load_keyboard(*env);
	load_accelerometer(*env);

	load_device(*env);

	load_window(*env);

	return 1;
}

//-----------------------------------------------------------------------------
static int crown_lua_require(lua_State* L)
{
	LuaStack stack(L);

	const char* filename = stack.get_string(1);

	const ResourceId lua_res = device()->resource_manager()->load("lua", filename);
	device()->resource_manager()->flush();

	const LuaResource* lr = (LuaResource*) device()->resource_manager()->data(lua_res);
	luaL_loadbuffer(L, (const char*) lr->code(), lr->size(), "");

	device()->resource_manager()->unload(lua_res);

	return 1;
}

//-----------------------------------------------------------------------------
LuaEnvironment::LuaEnvironment() :
	m_state(luaL_newstate()),
	m_is_used(false)
{
	// Open Lua default libraries
	string::strncpy(m_error_buffer, "", 1024);
	string::strncpy(m_tmp_buffer, "", 1024);
}

//-----------------------------------------------------------------------------
void LuaEnvironment::init()
{
	// Open default libraries
	luaL_openlibs(m_state);
	// Open Crown library
	lua_cpcall(m_state, luaopen_libcrown, NULL);

	// Register custom loader
	lua_getfield(m_state, LUA_GLOBALSINDEX, "package");
	lua_getfield(m_state, -1, "loaders");
	lua_remove(m_state, -2);

	int num_loaders = 0;
	lua_pushnil(m_state);
	while (lua_next(m_state, -2) != 0)
	{
		lua_pop(m_state, 1);
		num_loaders++;
	}

	lua_pushinteger(m_state, num_loaders + 1);
	lua_pushcfunction(m_state, crown_lua_require);
	lua_rawset(m_state, -3);

	lua_pop(m_state, 1);

	// load_buffer(class_system, string::strlen(class_system));
	// execute(0, 0);
	// load_buffer(commands_list, string::strlen(commands_list));
	// execute(0, 0);
	// load_buffer(get_cmd_by_name, string::strlen(get_cmd_by_name));
	// execute(0, 0);
	// load_buffer(tmp_print_table, string::strlen(tmp_print_table));
	// execute(0, 0);
	// load_buffer(count_all, string::strlen(count_all));
	// execute(0, 0);

	m_is_used = true;
}

//-----------------------------------------------------------------------------
void LuaEnvironment::shutdown()
{
	lua_close(m_state);

	m_is_used = false;
}

//-----------------------------------------------------------------------------
const char* LuaEnvironment::error()
{
	string::strncpy(m_tmp_buffer, m_error_buffer, 1024);
	string::strncpy(m_error_buffer, "", 1024);

	return m_tmp_buffer;
}

//-----------------------------------------------------------------------------
void LuaEnvironment::load(const LuaResource* lr)
{
	CE_ASSERT_NOT_NULL(lr);

	if (luaL_loadbuffer(m_state, (const char*) lr->code(), lr->size(), "") != 0)
	{
		lua_error();
	}

	if (lua_pcall(m_state, 0, 0, 0) != 0)
	{
		lua_error();
	}
}

//-----------------------------------------------------------------------------
void LuaEnvironment::call_global(const char* func, uint8_t argc, ...)
{
	CE_ASSERT_NOT_NULL(func);

	LuaStack stack(m_state);

	va_list vl;
	va_start(vl, argc);

	lua_getglobal(m_state, func);

	for (uint8_t i = 0; i < argc; i++)
	{
		const int type = va_arg(vl, int);
		switch (type)
		{
			case ARGUMENT_FLOAT:
			{
				stack.push_float(va_arg(vl, double));
				break;
			}
			default:
			{
				CE_ASSERT(false, "Oops, lua argument unknown");
				break;
			}
		}
	}

	va_end(vl);

	if (lua_pcall(m_state, argc, 0, 0) != 0)
	{
		lua_error();
	}
}

//-----------------------------------------------------------------------------
void LuaEnvironment::lua_error()
{
	string::strncpy(m_error_buffer, "", 1024);
	string::strncpy(m_error_buffer, lua_tostring(m_state, -1), 1024);
}

//-----------------------------------------------------------------------------
void LuaEnvironment::load_module_function(const char* module, const char* name, const lua_CFunction func)
{
	luaL_Reg entry[2];

	entry[0].name = name;
	entry[0].func = func;
	entry[1].name = NULL;
	entry[1].func = NULL;

	luaL_register(m_state, module, entry);
}

//-----------------------------------------------------------
void LuaEnvironment::load_module_enum(const char* /*module*/, const char* name, uint32_t value)
{
	lua_pushinteger(m_state, value);
	lua_setfield(m_state, -2, name);
}

const char* LuaEnvironment::class_system =  "function class(klass, super) "
    										"	if not klass then "
        									"		klass = {} "
                							"		local meta = {} "
        									"		meta.__call = function(self, ...) "
            								"			local object = {} "
            								"			setmetatable(object, klass) "
            								"			if object.init then object:init(...) end "
            								"			return object "
       										"		end "
        									"		setmetatable(klass, meta) "
    										"	end "
    										"	if super then "
        									"		for k,v in pairs(super) do "
            								"			klass[k] = v "
        									"		end "
    										"	end "
    										"	klass.__index = klass "
    										"	return klass "
											"end";

const char* LuaEnvironment::commands_list = "function get_all_commands() "
											"	local cmds = {}; "
											"	for class_name,class in pairs(_G) do "
											"		if type(class) == 'table' then "
			 								"			for func_name,func in pairs(class) do "
			 								"				if type(func) == 'function' then "
											"					cmds[#cmds+1] = class_name .. '.' .. func_name "
											"				end "
											"			end "
											"		end "
											"	end "
											"	return cmds "
											"end";

const char* LuaEnvironment::get_cmd_by_name = 	"function get_command_by_name(text) "
												"	local cmds = get_all_commands() "
												"	local results = {} "
												"	local index = 0 "
												"	for i,cmd in pairs(cmds) do "
												"		if string.find(cmd, text) then "
												"			results[index] = cmds[i] "
												"			index = index + 1 "
												"		end "
												"	end "
												"	return results "
												"end";

const char* LuaEnvironment::tmp_print_table =	"function print_table(table) "
												"	for k,v in pairs(table) do "
												"		print(v) "
												"	end "
												"end";

const char* LuaEnvironment::count_all = 	"function count_all(f) "
											"	local seen = {} "
											"	local count_table "
											"	count_table = function(t) "
											"		if seen[t] then return end "
											"		f(t) "
											"		seen[t] = true "
											"		for k,v in pairs(t) do "
											"			if type(v) == 'table' then "
											"				count_table(v) "
											"			elseif type(v) == 'userdata' then "
											"				f(v) "
											"			end "
											"		end "
											"	end "
											"	count_table(_G) "
											"end";

} // namespace crown<|endoftext|>


<commit_before>// Copyright (c) Microsoft. All rights reserved.

//
// GpioTestTool
//
//   Utility to manipulate GPIO pins from the command line.
//   Demonstrates how to use the GPIO WinRT APIs from standard
//   C++ with WRL.
//

#include <windows.h>
#include <strsafe.h>
#include <wrl.h>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <cwctype>

#include <windows.foundation.h>
#include <windows.devices.gpio.h>

using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Devices::Gpio;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

class wexception
{
public:
    explicit wexception (const std::wstring& Msg) : msg(Msg) { }

    wexception (const wchar_t* Msg, ...) {
        HRESULT hr;
        WCHAR buf[512];

        va_list argList;
        va_start(argList, Msg);
        hr = StringCchVPrintfW(
                buf,
                ARRAYSIZE(buf),
                Msg,
                argList);
        va_end(argList);

        this->msg = SUCCEEDED(hr) ? buf : Msg;
    }

    virtual ~wexception () { /*empty*/ }

    virtual const wchar_t *wwhat () const
    {
        return this->msg.c_str();
    }

private:
    std::wstring msg;
};

ComPtr<IGpioController> MakeDefaultController ()
{
    ComPtr<IGpioController> controller;

    // get the activation factory
    ComPtr<IGpioControllerStatics> controllerStatics;
    HRESULT hr = GetActivationFactory(
        HStringReference(RuntimeClass_Windows_Devices_Gpio_GpioController).Get(),
        &controllerStatics);
    if (FAILED(hr)) {
        throw wexception(
            L"Failed to get activation factory for %s. Please ensure the type "
            L"is present on the system. (hr = 0x%x)",
            RuntimeClass_Windows_Devices_Gpio_GpioController,
            hr);
    }

    hr = controllerStatics->GetDefault(controller.GetAddressOf());
    if (FAILED(hr)) {
        throw wexception(
            L"Failed to get instance of default GPIO controller. (hr = 0x%x)",
            hr);
    }

    if (!controller) {
        throw wexception(L"GPIO is not available on this system");
    }

    return controller;
}

ComPtr<IGpioPin> MakePin (int PinNumber)
{
    auto controller = MakeDefaultController();

    ComPtr<IGpioPin> pin;
    HRESULT hr = controller->OpenPin(PinNumber, pin.GetAddressOf());
    if (FAILED(hr)) {
        throw wexception(L"Failed to open pin. (hr = 0x%x)", hr);
    }

    return pin;
}

void ListPins ()
{
    auto controller = MakeDefaultController();

    INT32 pinCount;
    HRESULT hr = controller->get_PinCount(&pinCount);
    if (FAILED(hr)) {
        throw wexception(L"Failed to get pin count. (hr = 0x%x)", hr);
    }

    wprintf(L"The default GPIO controller has %d pins:\n", pinCount);
    for (INT32 pinNumber = 0; pinNumber < pinCount; ++pinNumber) {
        ComPtr<IGpioPin> pin;
        hr = controller->OpenPin(pinNumber, pin.GetAddressOf());
        switch (hr) {
        case S_OK:
            wprintf(L"  Pin %d is available\n", pinNumber);
            break;
        case __HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION):
            wprintf(L"  Pin %d is currently in use\n", pinNumber);
            break;
        case __HRESULT_FROM_WIN32(ERROR_NOT_FOUND):
            // pin is not available to applications; don't print anything
            break;
        default:
            wprintf(
                L" Pin %d: unexpected error occurred attempting to open. (hr = 0x%x)\n",
                pinNumber,
                hr);
        }
    }
}

GpioPinValue operator! (GpioPinValue Value)
{
    return (Value == GpioPinValue_Low) ? GpioPinValue_High : GpioPinValue_Low;
}

std::wistream& operator>> (std::wistream& is, GpioPinValue& value)
{
    int raw;
    is >> raw;
    if (is.fail()) {
        return is;
    }
    switch (raw) {
    case GpioPinValue_Low:
    case GpioPinValue_High:
        value = GpioPinValue(raw);
        break;
    default:
        is.clear(is.failbit);
    }
    return is;
}

PCWSTR StringFromGpioPinValue (GpioPinValue value)
{
    switch (value) {
    case GpioPinValue_Low: return L"Low";
    case GpioPinValue_High: return L"High";
    default: return L"[invalid GpioPinValue]";
    }
}

std::wistream& operator>> (std::wistream& is, GpioPinDriveMode& value)
{
    is.clear();
    std::wstring driveMode;
    is >> driveMode;
    if (!_wcsicmp(driveMode.c_str(), L"input")) {
        value = GpioPinDriveMode_Input;
    } else if (!_wcsicmp(driveMode.c_str(), L"output")) {
        value = GpioPinDriveMode_Output;
    } else if (!_wcsicmp(driveMode.c_str(), L"inputPullUp")) {
        value = GpioPinDriveMode_InputPullUp;
    } else if (!_wcsicmp(driveMode.c_str(), L"inputPullDown")) {
        value = GpioPinDriveMode_InputPullDown;
    } else {
        is.clear(is.failbit);
    }
    return is;
}

PCWSTR StringFromGpioPinDriveMode (GpioPinDriveMode value)
{
    switch (value) {
    case GpioPinDriveMode_Input: return L"input";
    case GpioPinDriveMode_Output: return L"output";
    case GpioPinDriveMode_InputPullUp: return L"inputPullUp";
    case GpioPinDriveMode_InputPullDown: return L"inputPullDown";
    default: return L"[invalid GpioPinDriveMode]";
    }
}

PCWSTR StringFromGpioSharingMode (GpioSharingMode value)
{
    switch (value) {
    case GpioSharingMode_Exclusive: return L"Exclusive";
    case GpioSharingMode_SharedReadOnly: return L"SharedReadOnly";
    default: return L"[invalid GpioSharingMode]";
    }
}

PCWSTR Help =
    L"Commands:\n"
    L" > write 0|1                        Write pin low (0) or high (1)\n"
    L" > high                             Alias for 'write 1'\n"
    L" > low                              Alias for 'write 0'\n"
    L" > toggle                           Toggle the pin from its current state\n"
    L" > read                             Read pin\n"
    L" > setdrivemode drive_mode          Set the pins's drive mode\n"
    L"     where drive_mode = input|output|\n"
    L"                        inputPullUp|inputPullDown\n"
    L" > info                             Dump information about the pin\n"
    L" > help                             Display this help message\n"
    L" > quit                             Quit\n";

void ShowPrompt (_In_ IGpioPin* pin)
{
    GpioPinValue outputLatch = GpioPinValue_High;
    while (std::wcin) {
        wprintf(L"> ");

        std::wstring line;
        if (!std::getline(std::wcin, line)) {
            return;
        }
        std::wistringstream linestream(line);

        std::wstring command;
        linestream >> command;
        if ((command == L"q") || (command == L"quit")) {
            return;
        } else if ((command == L"h") || (command == L"help")) {
            wprintf(L"%s\n", Help);
        } else if ((command == L"w") || (command == L"write")) {
            GpioPinValue value;
            linestream >> value;
            if (linestream.fail()) {
                wprintf(L"Syntax error: expecting 0 or 1\nUsage: write 0|1\n");
                continue;
            }

            HRESULT hr = pin->Write(value);
            if (FAILED(hr)) {
                wprintf(L"Failed to write pin. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if (command == L"high") {
            HRESULT hr = pin->Write(GpioPinValue_High);
            if (FAILED(hr)) {
                wprintf(L"Failed to write pin. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if (command == L"low") {
            HRESULT hr = pin->Write(GpioPinValue_Low);
            if (FAILED(hr)) {
                wprintf(L"Failed to write pin. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if ((command == L"t") || (command == L"toggle")) {
            outputLatch = !outputLatch;
            HRESULT hr = pin->Write(outputLatch);
            if (FAILED(hr)) {
                wprintf(L"Failed to write pin. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if ((command == L"r") || (command == L"read")) {
            GpioPinValue value;
            HRESULT hr = pin->Read(&value);
            if (FAILED(hr)) {
                wprintf(L"Failed to read pin. (hr = 0x%x)\n", hr);
                continue;
            }
            wprintf(L"%s\n", StringFromGpioPinValue(value));
        } else if (command == L"setdrivemode") {
            GpioPinDriveMode driveMode;
            linestream >> driveMode;
            if (!linestream) {
                wprintf(L"Syntax error: expecting valid drive mode. Type 'help' for usage.\n");
                continue;
            }

            HRESULT hr = pin->SetDriveMode(driveMode);
            if (FAILED(hr)) {
                wprintf(L"Failed to set drive mode. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if ((command == L"i") || (command == L"info")) {
            int pinNumber;
            pin->get_PinNumber(&pinNumber);
            GpioSharingMode sharingMode;
            pin->get_SharingMode(&sharingMode);
            TimeSpan debounceTimeout;
            pin->get_DebounceTimeout(&debounceTimeout);
            GpioPinDriveMode driveMode;
            pin->GetDriveMode(&driveMode);
            GpioPinValue value;
            pin->Read(&value);

            wprintf(
                L"        Pin Number: %d\n"
                L"      Sharing Mode: %s\n"
                L"  Debounce Timeout: %d ms\n"
                L"        Drive Mode: %s\n"
                L"             Value: %s\n",
                pinNumber,
                StringFromGpioSharingMode(sharingMode),
                int(debounceTimeout.Duration / 10000LL),
                StringFromGpioPinDriveMode(driveMode),
                StringFromGpioPinValue(value));
        } else if (command.empty()) {
            // ignore
        } else {
            wprintf(
                L"Unrecognized command: %s. Type 'help' for command usage.\n",
                command.c_str());
        }
    }
}

PCWSTR Usage =
L"GpioTestTool: Command line GPIO testing utility\n"
L"Usage: %s [-list] PinNumber\n"
L"\n"
L"  -list         List the available pins on the default GPIO controller.\n"
L"  PinNumber     The pin number with which you wish to interact. This\n"
L"                parameter is required.\n"
L"\n"
L"Example:\n"
L"  %s -list\n"
L"  %s 47\n";

void PrintUsage (PCWSTR name)
{
    wprintf(Usage, name, name, name);
}

int __cdecl wmain (_In_ int argc, _In_reads_(argc) wchar_t *argv[])
{
    enum MainReturnValue { Success, Failure };

    if (argc < 2) {
        fwprintf(
            stderr,
            L"Missing required command line parameter PinNumber\n\n");
        PrintUsage(argv[0]);
        return Success;
    }

    PCWSTR arg = argv[1];
    if (!_wcsicmp(arg, L"-h") || !_wcsicmp(arg, L"/h") ||
        !_wcsicmp(arg, L"-?") || !_wcsicmp(arg, L"/?")) {

        PrintUsage(argv[0]);
        return Success;
    }

    RoInitializeWrapper roInit(RO_INIT_MULTITHREADED);
    try {
        if (!_wcsicmp(arg, L"-list") || !_wcsicmp(arg, L"/list")) {
            ListPins();
            return Success;
        } else {
            std::wistringstream is(arg);
            INT32 pinNumber;
            is >> pinNumber;
            if (!is) {
                fwprintf(
                    stderr,
                    L"Expecting integer: %s\nType %s /? for usage.\n",
                    arg,
                    argv[0]);
                return Failure;
            }

            auto pin = MakePin(pinNumber);
            wprintf(L"Type 'help' for a list of commands\n");
            ShowPrompt(pin.Get());
            return Success;
        }
    } catch (const wexception& ex) {
        fwprintf(stderr, L"Error: %s\n", ex.wwhat());
        return Failure;
    }
}
<commit_msg>Added interrupt listener command to GpioTestTool.<commit_after>// Copyright (c) Microsoft. All rights reserved.

//
// GpioTestTool
//
//   Utility to manipulate GPIO pins from the command line.
//   Demonstrates how to use the GPIO WinRT APIs from standard
//   C++ with WRL.
//

#include <windows.h>
#include <strsafe.h>
#include <wrl.h>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <cwctype>

#include <windows.foundation.h>
#include <windows.devices.gpio.h>

using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Devices::Gpio;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

typedef ITypedEventHandler<GpioPin *, GpioPinValueChangedEventArgs *>
    IGpioPinValueChangedHandler;

class wexception
{
public:
    explicit wexception (const std::wstring& Msg) : msg(Msg) { }

    wexception (const wchar_t* Msg, ...) {
        HRESULT hr;
        WCHAR buf[512];

        va_list argList;
        va_start(argList, Msg);
        hr = StringCchVPrintfW(
                buf,
                ARRAYSIZE(buf),
                Msg,
                argList);
        va_end(argList);

        this->msg = SUCCEEDED(hr) ? buf : Msg;
    }

    virtual ~wexception () { /*empty*/ }

    virtual const wchar_t *wwhat () const
    {
        return this->msg.c_str();
    }

private:
    std::wstring msg;
};

ComPtr<IGpioController> MakeDefaultController ()
{
    ComPtr<IGpioController> controller;

    // get the activation factory
    ComPtr<IGpioControllerStatics> controllerStatics;
    HRESULT hr = GetActivationFactory(
        HStringReference(RuntimeClass_Windows_Devices_Gpio_GpioController).Get(),
        &controllerStatics);
    if (FAILED(hr)) {
        throw wexception(
            L"Failed to get activation factory for %s. Please ensure the type "
            L"is present on the system. (hr = 0x%x)",
            RuntimeClass_Windows_Devices_Gpio_GpioController,
            hr);
    }

    hr = controllerStatics->GetDefault(controller.GetAddressOf());
    if (FAILED(hr)) {
        throw wexception(
            L"Failed to get instance of default GPIO controller. (hr = 0x%x)",
            hr);
    }

    if (!controller) {
        throw wexception(L"GPIO is not available on this system");
    }

    return controller;
}

ComPtr<IGpioPin> MakePin (int PinNumber)
{
    auto controller = MakeDefaultController();

    ComPtr<IGpioPin> pin;
    HRESULT hr = controller->OpenPin(PinNumber, pin.GetAddressOf());
    if (FAILED(hr)) {
        throw wexception(L"Failed to open pin. (hr = 0x%x)", hr);
    }

    return pin;
}

void ListPins ()
{
    auto controller = MakeDefaultController();

    INT32 pinCount;
    HRESULT hr = controller->get_PinCount(&pinCount);
    if (FAILED(hr)) {
        throw wexception(L"Failed to get pin count. (hr = 0x%x)", hr);
    }

    wprintf(L"The default GPIO controller has %d pins:\n", pinCount);
    for (INT32 pinNumber = 0; pinNumber < pinCount; ++pinNumber) {
        ComPtr<IGpioPin> pin;
        hr = controller->OpenPin(pinNumber, pin.GetAddressOf());
        switch (hr) {
        case S_OK:
            wprintf(L"  Pin %d is available\n", pinNumber);
            break;
        case __HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION):
            wprintf(L"  Pin %d is currently in use\n", pinNumber);
            break;
        case __HRESULT_FROM_WIN32(ERROR_NOT_FOUND):
            // pin is not available to applications; don't print anything
            break;
        default:
            wprintf(
                L" Pin %d: unexpected error occurred attempting to open. (hr = 0x%x)\n",
                pinNumber,
                hr);
        }
    }
}

GpioPinValue operator! (GpioPinValue Value)
{
    return (Value == GpioPinValue_Low) ? GpioPinValue_High : GpioPinValue_Low;
}

std::wistream& operator>> (std::wistream& is, GpioPinValue& value)
{
    int raw;
    is >> raw;
    if (is.fail()) {
        return is;
    }
    switch (raw) {
    case GpioPinValue_Low:
    case GpioPinValue_High:
        value = GpioPinValue(raw);
        break;
    default:
        is.clear(is.failbit);
    }
    return is;
}

PCWSTR StringFromGpioPinValue (GpioPinValue value)
{
    switch (value) {
    case GpioPinValue_Low: return L"Low";
    case GpioPinValue_High: return L"High";
    default: return L"[invalid GpioPinValue]";
    }
}

std::wistream& operator>> (std::wistream& is, GpioPinDriveMode& value)
{
    is.clear();
    std::wstring driveMode;
    is >> driveMode;
    if (!_wcsicmp(driveMode.c_str(), L"input")) {
        value = GpioPinDriveMode_Input;
    } else if (!_wcsicmp(driveMode.c_str(), L"output")) {
        value = GpioPinDriveMode_Output;
    } else if (!_wcsicmp(driveMode.c_str(), L"inputPullUp")) {
        value = GpioPinDriveMode_InputPullUp;
    } else if (!_wcsicmp(driveMode.c_str(), L"inputPullDown")) {
        value = GpioPinDriveMode_InputPullDown;
    } else {
        is.clear(is.failbit);
    }
    return is;
}

PCWSTR StringFromGpioPinDriveMode (GpioPinDriveMode value)
{
    switch (value) {
    case GpioPinDriveMode_Input: return L"input";
    case GpioPinDriveMode_Output: return L"output";
    case GpioPinDriveMode_InputPullUp: return L"inputPullUp";
    case GpioPinDriveMode_InputPullDown: return L"inputPullDown";
    default: return L"[invalid GpioPinDriveMode]";
    }
}

PCWSTR StringFromGpioSharingMode (GpioSharingMode value)
{
    switch (value) {
    case GpioSharingMode_Exclusive: return L"Exclusive";
    case GpioSharingMode_SharedReadOnly: return L"SharedReadOnly";
    default: return L"[invalid GpioSharingMode]";
    }
}

PCWSTR StringFromGpioPinEdge (GpioPinEdge value)
{
    switch (value) {
    case GpioPinEdge_FallingEdge: return L"Falling";
    case GpioPinEdge_RisingEdge: return L"Rising";
    default: return L"[Invalid GpioPinEdge value]";
    }
}

PCWSTR Help =
    L"Commands:\n"
    L" > write 0|1                        Write pin low (0) or high (1)\n"
    L" > high                             Alias for 'write 1'\n"
    L" > low                              Alias for 'write 0'\n"
    L" > toggle                           Toggle the pin from its current state\n"
    L" > read                             Read pin\n"
    L" > setdrivemode drive_mode          Set the pins's drive mode\n"
    L"     where drive_mode = input|output|\n"
    L"                        inputPullUp|inputPullDown\n"
    L" > interrupt on|off                 Register or unregister for pin value\n"
    L"                                    change events.\n"
    L" > info                             Dump information about the pin\n"
    L" > help                             Display this help message\n"
    L" > quit                             Quit\n";

void ShowPrompt (_In_ IGpioPin* pin)
{
    auto listener = Callback<IGpioPinValueChangedHandler>([] (
        _In_ IGpioPin* /*Pin*/,
        _In_ IGpioPinValueChangedEventArgs* Args
        ) -> HRESULT
    {
        GpioPinEdge edge;
        Args->get_Edge(&edge);
        wprintf(L"%s edge occurred.\n", StringFromGpioPinEdge(edge));
        return S_OK;
    });

    auto token = EventRegistrationToken();
    bool listenerRegistered = false;

    GpioPinValue outputLatch = GpioPinValue_High;
    while (std::wcin) {
        wprintf(L"> ");

        std::wstring line;
        if (!std::getline(std::wcin, line)) {
            return;
        }
        std::wistringstream linestream(line);

        std::wstring command;
        linestream >> command;
        if ((command == L"q") || (command == L"quit")) {
            return;
        } else if ((command == L"h") || (command == L"help")) {
            wprintf(L"%s\n", Help);
        } else if ((command == L"w") || (command == L"write")) {
            GpioPinValue value;
            linestream >> value;
            if (linestream.fail()) {
                wprintf(L"Syntax error: expecting 0 or 1\nUsage: write 0|1\n");
                continue;
            }

            HRESULT hr = pin->Write(value);
            if (FAILED(hr)) {
                wprintf(L"Failed to write pin. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if (command == L"high") {
            HRESULT hr = pin->Write(GpioPinValue_High);
            if (FAILED(hr)) {
                wprintf(L"Failed to write pin. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if (command == L"low") {
            HRESULT hr = pin->Write(GpioPinValue_Low);
            if (FAILED(hr)) {
                wprintf(L"Failed to write pin. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if ((command == L"t") || (command == L"toggle")) {
            outputLatch = !outputLatch;
            HRESULT hr = pin->Write(outputLatch);
            if (FAILED(hr)) {
                wprintf(L"Failed to write pin. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if ((command == L"r") || (command == L"read")) {
            GpioPinValue value;
            HRESULT hr = pin->Read(&value);
            if (FAILED(hr)) {
                wprintf(L"Failed to read pin. (hr = 0x%x)\n", hr);
                continue;
            }
            wprintf(L"%s\n", StringFromGpioPinValue(value));
        } else if (command == L"setdrivemode") {
            GpioPinDriveMode driveMode;
            linestream >> driveMode;
            if (!linestream) {
                wprintf(L"Syntax error: expecting valid drive mode. Type 'help' for usage.\n");
                continue;
            }

            HRESULT hr = pin->SetDriveMode(driveMode);
            if (FAILED(hr)) {
                wprintf(L"Failed to set drive mode. (hr = 0x%x)\n", hr);
                continue;
            }
        } else if ((command == L"int") || (command == L"interrupt")) {
            std::wstring onOrOff;
            linestream >> onOrOff;
            if (onOrOff == L"on") {
                if (listenerRegistered) {
                    wprintf(L"Interrupt listener already registered.\n");
                    continue;
                }

                HRESULT hr = pin->add_ValueChanged(listener.Get(), &token);
                if (FAILED(hr)) {
                    wprintf(
                        L"Failed to add event listener to ValueChanged event. (hr = 0x%x)\n",
                        hr);
                    continue;
                }
                listenerRegistered = true;
            } else if (onOrOff == L"off") {
                if (!listenerRegistered) {
                    wprintf(L"No interrupt listener is currently registered.\n");
                    continue;
                }

                HRESULT hr = pin->remove_ValueChanged(token);
                if (FAILED(hr)) {
                    wprintf(
                        L"Failed to remove ValueChanged event. (hr = 0x%x)\n",
                        hr);
                    continue;
                }
                listenerRegistered = false;
            } else {
                wprintf(
                    L"Expecting 'on' or 'off': %s. Type 'help' for usage.\n",
                    onOrOff.c_str());
            }
        } else if ((command == L"i") || (command == L"info")) {
            int pinNumber;
            pin->get_PinNumber(&pinNumber);
            GpioSharingMode sharingMode;
            pin->get_SharingMode(&sharingMode);
            TimeSpan debounceTimeout;
            pin->get_DebounceTimeout(&debounceTimeout);
            GpioPinDriveMode driveMode;
            pin->GetDriveMode(&driveMode);
            GpioPinValue value;
            pin->Read(&value);

            wprintf(
                L"        Pin Number: %d\n"
                L"      Sharing Mode: %s\n"
                L"  Debounce Timeout: %d ms\n"
                L"        Drive Mode: %s\n"
                L"             Value: %s\n",
                pinNumber,
                StringFromGpioSharingMode(sharingMode),
                int(debounceTimeout.Duration / 10000LL),
                StringFromGpioPinDriveMode(driveMode),
                StringFromGpioPinValue(value));
        } else if (command.empty()) {
            // ignore
        } else {
            wprintf(
                L"Unrecognized command: %s. Type 'help' for command usage.\n",
                command.c_str());
        }
    }
}

PCWSTR Usage =
L"GpioTestTool: Command line GPIO testing utility\n"
L"Usage: %s [-list] PinNumber\n"
L"\n"
L"  -list         List the available pins on the default GPIO controller.\n"
L"  PinNumber     The pin number with which you wish to interact. This\n"
L"                parameter is required.\n"
L"\n"
L"Example:\n"
L"  %s -list\n"
L"  %s 47\n";

void PrintUsage (PCWSTR name)
{
    wprintf(Usage, name, name, name);
}

int __cdecl wmain (_In_ int argc, _In_reads_(argc) wchar_t *argv[])
{
    enum MainReturnValue { Success, Failure };

    if (argc < 2) {
        fwprintf(
            stderr,
            L"Missing required command line parameter PinNumber\n\n");
        PrintUsage(argv[0]);
        return Success;
    }

    PCWSTR arg = argv[1];
    if (!_wcsicmp(arg, L"-h") || !_wcsicmp(arg, L"/h") ||
        !_wcsicmp(arg, L"-?") || !_wcsicmp(arg, L"/?")) {

        PrintUsage(argv[0]);
        return Success;
    }

    RoInitializeWrapper roInit(RO_INIT_MULTITHREADED);
    try {
        if (!_wcsicmp(arg, L"-list") || !_wcsicmp(arg, L"/list")) {
            ListPins();
            return Success;
        } else {
            std::wistringstream is(arg);
            INT32 pinNumber;
            is >> pinNumber;
            if (!is) {
                fwprintf(
                    stderr,
                    L"Expecting integer: %s\nType %s /? for usage.\n",
                    arg,
                    argv[0]);
                return Failure;
            }

            auto pin = MakePin(pinNumber);
            wprintf(L"Type 'help' for a list of commands\n");
            ShowPrompt(pin.Get());
            return Success;
        }
    } catch (const wexception& ex) {
        fwprintf(stderr, L"Error: %s\n", ex.wwhat());
        return Failure;
    }
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      managedframe.cpp
// Purpose:   Implementation of wxExManagedFrame class.
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <list>
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/richtooltip.h>
#include <wx/wxcrt.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/defs.h>
#include <wx/extension/ex.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>

#if wxUSE_GUI

// Support class.
// Offers a text ctrl related to a ex object.
class wxExExTextCtrl: public wxTextCtrl
{
public:
  /// Constructor. Creates empty control.
  wxExExTextCtrl(
    wxWindow* parent,
    wxExManagedFrame* frame,
    wxStaticText* prefix,
    wxWindowID id = wxID_ANY,
    const wxPoint& pos = wxDefaultPosition,
    const wxSize& size = wxDefaultSize);

  /// Returns ex component.
  wxExEx* GetEx() {return m_ex;};

  /// Sets ex component.
  void SetEx(wxExEx* ex);
protected:
  void OnCommand(wxCommandEvent& event);
  void OnEnter(wxCommandEvent& event);
  void OnFocus(wxFocusEvent& event);
  void OnKey(wxKeyEvent& event);
private:
  wxExManagedFrame* m_Frame;
  wxExEx* m_ex;
  wxStaticText* m_Prefix;
  bool m_UserInput;

  std::list < wxString > m_Commands;
  std::list < wxString >::const_iterator m_CommandsIterator;

  std::list < wxString > m_Finds;
  std::list < wxString >::const_iterator m_FindsIterator;

  DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
  EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
  EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
  EVT_UPDATE_UI_RANGE(
    ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()

wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
  wxWindowID id,
  const wxString& title,
  long style)
  : wxExFrame(parent, id, title, style)

{
  m_Manager.SetManagedWindow(this);

  m_ToolBar = new wxExToolBar(this);
  m_ToolBar->AddControls();

  AddToolBarPane(m_ToolBar, "TOOLBAR", _("Toolbar"));
  AddToolBarPane(new wxExFindToolBar(this), "FINDBAR", _("Findbar"));
  AddToolBarPane(CreateExPanel(), "VIBAR");

  m_Manager.Update();
}

wxExManagedFrame::~wxExManagedFrame()
{
  m_Manager.UnInit();
}

bool wxExManagedFrame::AddToolBarPane(
  wxWindow* window,
  const wxString& name,
  const wxString& caption)
{
  wxAuiPaneInfo pane;

  pane
    .LeftDockable(false)
    .RightDockable(false)
    .Name(name);

  // If the toolbar has a caption, it is at the top,
  // otherwise fixed at the bottom and initially hidden.
  if (!caption.empty())
  {
    pane
      .Top()
      .ToolbarPane()
      .Caption(caption);
  }
  else
  {
    pane
      .Bottom()
      .CloseButton(false)
      .Hide()
      .DockFixed(true)
      .Movable(false)
      .Row(10)
      .CaptionVisible(false);
  }

  return m_Manager.AddPane(window, pane);
}

bool wxExManagedFrame::AllowClose(wxWindowID id, wxWindow* page)
{
  // The page will be closed, so do not update find focus now.
  SetFindFocus(NULL);
  return true;
}

wxPanel* wxExManagedFrame::CreateExPanel()
{
  // A ex panel starts with small static text for : or /, then
  // comes the ex ctrl for getting user input.
  wxPanel* panel = new wxPanel(this);
  m_exTextPrefix = new wxStaticText(panel, wxID_ANY, wxEmptyString);
  m_exTextCtrl = new wxExExTextCtrl(panel, this, m_exTextPrefix, wxID_ANY);

  wxFlexGridSizer* sizer = new wxFlexGridSizer(2);
  sizer->AddGrowableCol(1);
  sizer->Add(m_exTextPrefix, wxSizerFlags().Expand());
  sizer->Add(m_exTextCtrl, wxSizerFlags().Expand());

  panel->SetSizerAndFit(sizer);

  return panel;
}

void wxExManagedFrame::GetExCommand(wxExEx* ex, const wxString& command)
{
  m_exTextPrefix->SetLabel(command);
  m_exTextCtrl->SetEx(ex);

  m_Manager.GetPane("VIBAR").Show();
  m_Manager.Update();
}

void wxExManagedFrame::HideExBar(bool set_focus)
{
  if (m_Manager.GetPane("VIBAR").IsShown())
  {
    m_Manager.GetPane("VIBAR").Hide();
    m_Manager.Update();

    if (set_focus && m_exTextCtrl != NULL && m_exTextCtrl->GetEx() != NULL)
    {
      m_exTextCtrl->GetEx()->GetSTC()->SetFocus();
    }
  }
}

void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
    case wxID_PREFERENCES:
      wxExSTC::ConfigDialog(this,
        _("Editor Options"),
        wxExSTC::STC_CONFIG_MODELESS |
        wxExSTC::STC_CONFIG_SIMPLE |
        wxExSTC::STC_CONFIG_WITH_APPLY,
        event.GetId());
    break;

    case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
    case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
    case ID_VIEW_FINDBAR:
      event.Check(m_Manager.GetPane("FINDBAR").IsShown());
    break;

    case ID_VIEW_TOOLBAR:
      event.Check(m_Manager.GetPane("TOOLBAR").IsShown());
    break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnNotebook(wxWindowID id, wxWindow* page)
{
  SetFindFocus(page);
}

void wxExManagedFrame::ShowExMessage(const wxString& text)
{
  HideExBar();

  if (GetStatusBar() != NULL && GetStatusBar()->IsShown())
  {
    GetStatusBar()->SetStatusText(text);
  }
  else
  {
    wxRichToolTip tt("vi", text);
    tt.ShowFor(m_exTextCtrl);
  }
}

void wxExManagedFrame::SyncCloseAll(wxWindowID id)
{
  SetFindFocus(NULL);
}

void wxExManagedFrame::TogglePane(const wxString& pane)
{
  wxAuiPaneInfo& info = m_Manager.GetPane(pane);

  wxASSERT(info.IsOk());

  info.IsShown() ? info.Hide(): info.Show();

  m_Manager.Update();
}

// Implementation of support class.

BEGIN_EVENT_TABLE(wxExExTextCtrl, wxTextCtrl)
  EVT_CHAR(wxExExTextCtrl::OnKey)
  EVT_SET_FOCUS(wxExExTextCtrl::OnFocus)
  EVT_TEXT(wxID_ANY, wxExExTextCtrl::OnCommand)
  EVT_TEXT_ENTER(wxID_ANY, wxExExTextCtrl::OnEnter)
END_EVENT_TABLE()

wxExExTextCtrl::wxExExTextCtrl(
  wxWindow* parent,
  wxExManagedFrame* frame,
  wxStaticText* prefix,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size)
  : wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER)
  , m_Frame(frame)
  , m_ex(NULL)
  , m_UserInput(false)
  , m_Prefix(prefix)
{
  m_CommandsIterator = m_Commands.begin();
  m_FindsIterator = m_Finds.begin();
}

void wxExExTextCtrl::OnCommand(wxCommandEvent& event)
{
  event.Skip();

  if (m_UserInput && m_ex != NULL && m_Prefix->GetLabel() != ":")
  {
    m_ex->GetSTC()->PositionRestore();
    m_ex->GetSTC()->FindNext(
      GetValue(),
      wxSTC_FIND_REGEXP | wxFR_MATCHCASE,
      m_Prefix->GetLabel() == "/");
  }
}

void wxExExTextCtrl::OnEnter(wxCommandEvent& event)
{
  if (GetValue().empty())
  {
    m_Frame->HideExBar();
    return;
  }

  if (m_Prefix->GetLabel() == ":")
  {
    m_Commands.remove(GetValue());
    m_Commands.push_front(GetValue());
    m_CommandsIterator = m_Commands.begin();

    if (m_ex != NULL)
    {
      if (m_ex->Command(m_Prefix->GetLabel() + GetValue()))
      {
        m_Frame->HideExBar();
        wxConfigBase::Get()->Write("excommand", GetValue());
      }
    }
  }
  else
  {
    m_Finds.remove(GetValue());
    m_Finds.push_front(GetValue());
    m_FindsIterator = m_Finds.begin();

    if (m_UserInput)
    {
      wxExFindReplaceData::Get()->SetFindString(GetValue());

      if (m_ex != NULL)
      {
        m_ex->MacroRecord(m_Prefix->GetLabel() + GetValue());
      }
    }
    else if (m_ex != NULL)
    {
      m_ex->Command(m_Prefix->GetLabel() + GetValue());
    }

    m_Frame->HideExBar();
  }
}

void wxExExTextCtrl::OnFocus(wxFocusEvent& event)
{
  event.Skip();

  if (m_ex != NULL)
  {
    m_ex->GetSTC()->PositionSave();
  }
}

void wxExExTextCtrl::OnKey(wxKeyEvent& event)
{
  const int key = event.GetKeyCode();

  switch (key)
  {
  case WXK_UP:
  case WXK_DOWN:
    if (m_Prefix->GetLabel() == ":")
    {
      wxExSetTextCtrlValue(this, key, m_Commands, m_CommandsIterator);
    }
    else
    {
      wxExSetTextCtrlValue(this, key, m_Finds, m_FindsIterator);
    }
    break;

  case WXK_ESCAPE:
    if (m_ex != NULL)
    {
      m_ex->GetSTC()->PositionRestore();
    }

    m_Frame->HideExBar();

    m_UserInput = false;
  break;

  default:
    if (key != WXK_RETURN)
    {
      m_UserInput = true;
    }

    event.Skip();
  }
}

void wxExExTextCtrl::SetEx(wxExEx* ex)
{
  m_UserInput = false;
  m_ex = ex;

  if (m_Prefix->GetLabel() != ":")
  {
    if (!m_ex->GetSTC()->GetSelectedText().empty())
    {
      SetValue(m_ex->GetSTC()->GetSelectedText());
      wxExFindReplaceData::Get()->SetFindString(GetValue());
    }
    else
    {
      SetValue(wxExFindReplaceData::Get()->GetFindString());
    }
  }
  else
  {
    SetValue(wxConfigBase::Get()->Read("excommand", wxEmptyString));
  }

  Show();
  SelectAll();
  SetFocus();
}
#endif // wxUSE_GUI
<commit_msg>use wxLogMessage instead of rich tool tip<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      managedframe.cpp
// Purpose:   Implementation of wxExManagedFrame class.
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <list>
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/wxcrt.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/defs.h>
#include <wx/extension/ex.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>

#if wxUSE_GUI

// Support class.
// Offers a text ctrl related to a ex object.
class wxExExTextCtrl: public wxTextCtrl
{
public:
  /// Constructor. Creates empty control.
  wxExExTextCtrl(
    wxWindow* parent,
    wxExManagedFrame* frame,
    wxStaticText* prefix,
    wxWindowID id = wxID_ANY,
    const wxPoint& pos = wxDefaultPosition,
    const wxSize& size = wxDefaultSize);

  /// Returns ex component.
  wxExEx* GetEx() {return m_ex;};

  /// Sets ex component.
  void SetEx(wxExEx* ex);
protected:
  void OnCommand(wxCommandEvent& event);
  void OnEnter(wxCommandEvent& event);
  void OnFocus(wxFocusEvent& event);
  void OnKey(wxKeyEvent& event);
private:
  wxExManagedFrame* m_Frame;
  wxExEx* m_ex;
  wxStaticText* m_Prefix;
  bool m_UserInput;

  std::list < wxString > m_Commands;
  std::list < wxString >::const_iterator m_CommandsIterator;

  std::list < wxString > m_Finds;
  std::list < wxString >::const_iterator m_FindsIterator;

  DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
  EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
  EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
  EVT_UPDATE_UI_RANGE(
    ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()

wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
  wxWindowID id,
  const wxString& title,
  long style)
  : wxExFrame(parent, id, title, style)

{
  m_Manager.SetManagedWindow(this);

  m_ToolBar = new wxExToolBar(this);
  m_ToolBar->AddControls();

  AddToolBarPane(m_ToolBar, "TOOLBAR", _("Toolbar"));
  AddToolBarPane(new wxExFindToolBar(this), "FINDBAR", _("Findbar"));
  AddToolBarPane(CreateExPanel(), "VIBAR");

  m_Manager.Update();
}

wxExManagedFrame::~wxExManagedFrame()
{
  m_Manager.UnInit();
}

bool wxExManagedFrame::AddToolBarPane(
  wxWindow* window,
  const wxString& name,
  const wxString& caption)
{
  wxAuiPaneInfo pane;

  pane
    .LeftDockable(false)
    .RightDockable(false)
    .Name(name);

  // If the toolbar has a caption, it is at the top,
  // otherwise fixed at the bottom and initially hidden.
  if (!caption.empty())
  {
    pane
      .Top()
      .ToolbarPane()
      .Caption(caption);
  }
  else
  {
    pane
      .Bottom()
      .CloseButton(false)
      .Hide()
      .DockFixed(true)
      .Movable(false)
      .Row(10)
      .CaptionVisible(false);
  }

  return m_Manager.AddPane(window, pane);
}

bool wxExManagedFrame::AllowClose(wxWindowID id, wxWindow* page)
{
  // The page will be closed, so do not update find focus now.
  SetFindFocus(NULL);
  return true;
}

wxPanel* wxExManagedFrame::CreateExPanel()
{
  // A ex panel starts with small static text for : or /, then
  // comes the ex ctrl for getting user input.
  wxPanel* panel = new wxPanel(this);
  m_exTextPrefix = new wxStaticText(panel, wxID_ANY, wxEmptyString);
  m_exTextCtrl = new wxExExTextCtrl(panel, this, m_exTextPrefix, wxID_ANY);

  wxFlexGridSizer* sizer = new wxFlexGridSizer(2);
  sizer->AddGrowableCol(1);
  sizer->Add(m_exTextPrefix, wxSizerFlags().Expand());
  sizer->Add(m_exTextCtrl, wxSizerFlags().Expand());

  panel->SetSizerAndFit(sizer);

  return panel;
}

void wxExManagedFrame::GetExCommand(wxExEx* ex, const wxString& command)
{
  m_exTextPrefix->SetLabel(command);
  m_exTextCtrl->SetEx(ex);

  m_Manager.GetPane("VIBAR").Show();
  m_Manager.Update();
}

void wxExManagedFrame::HideExBar(bool set_focus)
{
  if (m_Manager.GetPane("VIBAR").IsShown())
  {
    m_Manager.GetPane("VIBAR").Hide();
    m_Manager.Update();

    if (set_focus && m_exTextCtrl != NULL && m_exTextCtrl->GetEx() != NULL)
    {
      m_exTextCtrl->GetEx()->GetSTC()->SetFocus();
    }
  }
}

void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
    case wxID_PREFERENCES:
      wxExSTC::ConfigDialog(this,
        _("Editor Options"),
        wxExSTC::STC_CONFIG_MODELESS |
        wxExSTC::STC_CONFIG_SIMPLE |
        wxExSTC::STC_CONFIG_WITH_APPLY,
        event.GetId());
    break;

    case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
    case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
    case ID_VIEW_FINDBAR:
      event.Check(m_Manager.GetPane("FINDBAR").IsShown());
    break;

    case ID_VIEW_TOOLBAR:
      event.Check(m_Manager.GetPane("TOOLBAR").IsShown());
    break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnNotebook(wxWindowID id, wxWindow* page)
{
  SetFindFocus(page);
}

void wxExManagedFrame::ShowExMessage(const wxString& text)
{
  HideExBar();

  if (GetStatusBar() != NULL && GetStatusBar()->IsShown())
  {
    GetStatusBar()->SetStatusText(text);
  }
  else
  {
    wxLogMessage(text);
  }
}

void wxExManagedFrame::SyncCloseAll(wxWindowID id)
{
  SetFindFocus(NULL);
}

void wxExManagedFrame::TogglePane(const wxString& pane)
{
  wxAuiPaneInfo& info = m_Manager.GetPane(pane);

  wxASSERT(info.IsOk());

  info.IsShown() ? info.Hide(): info.Show();

  m_Manager.Update();
}

// Implementation of support class.

BEGIN_EVENT_TABLE(wxExExTextCtrl, wxTextCtrl)
  EVT_CHAR(wxExExTextCtrl::OnKey)
  EVT_SET_FOCUS(wxExExTextCtrl::OnFocus)
  EVT_TEXT(wxID_ANY, wxExExTextCtrl::OnCommand)
  EVT_TEXT_ENTER(wxID_ANY, wxExExTextCtrl::OnEnter)
END_EVENT_TABLE()

wxExExTextCtrl::wxExExTextCtrl(
  wxWindow* parent,
  wxExManagedFrame* frame,
  wxStaticText* prefix,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size)
  : wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER)
  , m_Frame(frame)
  , m_ex(NULL)
  , m_UserInput(false)
  , m_Prefix(prefix)
{
  m_CommandsIterator = m_Commands.begin();
  m_FindsIterator = m_Finds.begin();
}

void wxExExTextCtrl::OnCommand(wxCommandEvent& event)
{
  event.Skip();

  if (m_UserInput && m_ex != NULL && m_Prefix->GetLabel() != ":")
  {
    m_ex->GetSTC()->PositionRestore();
    m_ex->GetSTC()->FindNext(
      GetValue(),
      wxSTC_FIND_REGEXP | wxFR_MATCHCASE,
      m_Prefix->GetLabel() == "/");
  }
}

void wxExExTextCtrl::OnEnter(wxCommandEvent& event)
{
  if (GetValue().empty())
  {
    m_Frame->HideExBar();
    return;
  }

  if (m_Prefix->GetLabel() == ":")
  {
    m_Commands.remove(GetValue());
    m_Commands.push_front(GetValue());
    m_CommandsIterator = m_Commands.begin();

    if (m_ex != NULL)
    {
      if (m_ex->Command(m_Prefix->GetLabel() + GetValue()))
      {
        m_Frame->HideExBar();
        wxConfigBase::Get()->Write("excommand", GetValue());
      }
    }
  }
  else
  {
    m_Finds.remove(GetValue());
    m_Finds.push_front(GetValue());
    m_FindsIterator = m_Finds.begin();

    if (m_UserInput)
    {
      wxExFindReplaceData::Get()->SetFindString(GetValue());

      if (m_ex != NULL)
      {
        m_ex->MacroRecord(m_Prefix->GetLabel() + GetValue());
      }
    }
    else if (m_ex != NULL)
    {
      m_ex->Command(m_Prefix->GetLabel() + GetValue());
    }

    m_Frame->HideExBar();
  }
}

void wxExExTextCtrl::OnFocus(wxFocusEvent& event)
{
  event.Skip();

  if (m_ex != NULL)
  {
    m_ex->GetSTC()->PositionSave();
  }
}

void wxExExTextCtrl::OnKey(wxKeyEvent& event)
{
  const int key = event.GetKeyCode();

  switch (key)
  {
  case WXK_UP:
  case WXK_DOWN:
    if (m_Prefix->GetLabel() == ":")
    {
      wxExSetTextCtrlValue(this, key, m_Commands, m_CommandsIterator);
    }
    else
    {
      wxExSetTextCtrlValue(this, key, m_Finds, m_FindsIterator);
    }
    break;

  case WXK_ESCAPE:
    if (m_ex != NULL)
    {
      m_ex->GetSTC()->PositionRestore();
    }

    m_Frame->HideExBar();

    m_UserInput = false;
  break;

  default:
    if (key != WXK_RETURN)
    {
      m_UserInput = true;
    }

    event.Skip();
  }
}

void wxExExTextCtrl::SetEx(wxExEx* ex)
{
  m_UserInput = false;
  m_ex = ex;

  if (m_Prefix->GetLabel() != ":")
  {
    if (!m_ex->GetSTC()->GetSelectedText().empty())
    {
      SetValue(m_ex->GetSTC()->GetSelectedText());
      wxExFindReplaceData::Get()->SetFindString(GetValue());
    }
    else
    {
      SetValue(wxExFindReplaceData::Get()->GetFindString());
    }
  }
  else
  {
    SetValue(wxConfigBase::Get()->Read("excommand", wxEmptyString));
  }

  Show();
  SelectAll();
  SetFocus();
}
#endif // wxUSE_GUI
<|endoftext|>


<commit_before>/*

DAcase2.c

This program connects to the DAQ data source passed as argument
and populates local "./result.txt" file with the ids of events received
during the run.

The program exits when being asked to shut down (daqDA_checkshutdown)
or End of Run event.

Messages on stdout are exported to DAQ log system.

contact: alice-datesupport@cern.ch

*/

#include "event.h"
#include "monitor.h"
extern "C" {
#include "daqDA.h"
}

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

#include <TSystem.h>

#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliPHOSDA1.h"
#include "AliPHOSRawDecoderv1.h"
#include "AliCaloAltroMapping.h"

/* Main routine
      Arguments:
      1- monitoring data source
*/
int main(int argc, char **argv) {

  int status;

  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  /* open result file */
  FILE *fp=NULL;
  fp=fopen("./result.txt","a");
  if (fp==NULL) {
    printf("Failed to open file\n");
    return -1;
  }

  /* Open mapping files */
  AliAltroMapping *mapping[4];
  TString path = gSystem->Getenv("ALICE_ROOT");
  path += "/PHOS/mapping/RCU";
  TString path2;
  for(Int_t i = 0; i < 4; i++) {
    path2 = path;
    path2 += i;
    path2 += ".data";
    mapping[i] = new AliCaloAltroMapping(path2.Data());
  }

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
    printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* log start of process */
  printf("DA example case2 monitoring program started\n");

  /* init some counters */
  int nevents_physics=0;
  int nevents_total=0;

  AliRawReader *rawReader = NULL;

  AliPHOSDA1 da1(2); // DA1 (Calibration DA) for module2

  Float_t e[64][56][2];
  Float_t t[64][56][2];

  Int_t gain = -1;
  Int_t X = -1;
  Int_t Z = -1;

  /* main loop (infinite) */
  for(;;) {
    struct eventHeaderStruct *event;
    eventTypeType eventT;

    /* check shutdown condition */
    if (daqDA_checkShutdown()) {break;}

    /* get next event (blocking call until timeout) */
    status=monitorGetEventDynamic((void **)&event);
    if (status==MON_ERR_EOF) {
      printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
    }

    if (status!=0) {
      printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
    }

    /* retry if got no event */
    if (event==NULL) {
      continue;
    }

    /* use event - here, just write event id to result file */
    eventT=event->eventType;

    if (eventT==PHYSICS_EVENT) {
      fprintf(fp,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n",
	  (unsigned long)event->eventRunNb,
        (unsigned long)event->eventSize,
        EVENT_ID_GET_BUNCH_CROSSING(event->eventId),
        EVENT_ID_GET_ORBIT(event->eventId),
        EVENT_ID_GET_PERIOD(event->eventId)
      );

      for(Int_t iX=0; iX<64; iX++) {
	for(Int_t iZ=0; iZ<56; iZ++) {
	  for(Int_t iGain=0; iGain<2; iGain++) {
	    e[iX][iZ][iGain] = 0.;
	    t[iX][iZ][iGain] = 0.;
	  }
	}
      }

      rawReader = new AliRawReaderDate((void*)event);
      AliPHOSRawDecoderv1 dc(rawReader,mapping);
      dc.SubtractPedestals(kTRUE);

      while(dc.NextDigit()) {

	X = dc.GetRow() - 1;
	Z = dc.GetColumn() - 1;

	if(dc.IsLowGain()) gain = 0;
	else
	  gain = 1;

	e[X][Z][gain] = dc.GetEnergy();
	t[X][Z][gain] = dc.GetTime();

      }

      da1.FillHistograms(e,t);
      //da1.UpdateHistoFile();

      delete rawReader;
      nevents_physics++;
    }

    nevents_total++;

    /* free resources */
    free(event);

    /* exit when last event received, no need to wait for TERM signal */
    if (eventT==END_OF_RUN) {
      printf("EOR event detected\n");
      break;
    }
  }

  for(Int_t i = 0; i < 4; i++) delete mapping[i];

  /* write report */
  fprintf(fp,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);

  /* close result file */
  fclose(fp);

  return status;
}
<commit_msg>Old version is deleted<commit_after><|endoftext|>


<commit_before>/// \file PasskeySetup.cpp
//-----------------------------------------------------------------------------

#include "stdafx.h"
#include "PasswordSafe.h"
#include "PasskeySetup.h"
#include "util.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//-----------------------------------------------------------------------------
CPasskeySetup::CPasskeySetup(CWnd* pParent)
   : CDialog(CPasskeySetup::IDD, pParent)
{
   m_passkey = "";
   m_verify = "";
}

void CPasskeySetup::DoDataExchange(CDataExchange* pDX)
{
   CDialog::DoDataExchange(pDX);
   DDX_Text(pDX, IDC_PASSKEY, m_passkey.m_mystring);
   DDX_Text(pDX, IDC_VERIFY, m_verify.m_mystring);
}

BEGIN_MESSAGE_MAP(CPasskeySetup, CDialog)
   ON_BN_CLICKED(ID_HELP, OnHelp)
END_MESSAGE_MAP()

void CPasskeySetup::OnCancel()
{
   app.m_pMainWnd = NULL;
   CDialog::OnCancel();
}

void CPasskeySetup::OnOK()
{
   UpdateData(TRUE);
   if (m_passkey != m_verify)
   {
      AfxMessageBox("The two entries do not match.");
      ((CEdit*)GetDlgItem(IDC_VERIFY))->SetFocus();
      return;
   }

   if (m_passkey == "")
   {
      AfxMessageBox("Please enter a key and verify it.");
      ((CEdit*)GetDlgItem(IDC_PASSKEY))->SetFocus();
      return;
   }
   app.m_pMainWnd = NULL;
   CDialog::OnOK();
}

void CPasskeySetup::OnHelp()
{
   WinHelp(0x20084, HELP_CONTEXT);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<commit_msg>Header fixes, HtmlHelp<commit_after>/// \file PasskeySetup.cpp
//-----------------------------------------------------------------------------

#include "stdafx.h"
#include "PasswordSafe.h"

#include "ThisMfcApp.h"
#include "resource.h"

#include "util.h"

#include "PasskeySetup.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//-----------------------------------------------------------------------------
CPasskeySetup::CPasskeySetup(CWnd* pParent)
   : CDialog(CPasskeySetup::IDD, pParent)
{
   m_passkey = "";
   m_verify = "";
}

void CPasskeySetup::DoDataExchange(CDataExchange* pDX)
{
   CDialog::DoDataExchange(pDX);
   DDX_Text(pDX, IDC_PASSKEY, m_passkey.m_mystring);
   DDX_Text(pDX, IDC_VERIFY, m_verify.m_mystring);
}

BEGIN_MESSAGE_MAP(CPasskeySetup, CDialog)
   ON_BN_CLICKED(ID_HELP, OnHelp)
END_MESSAGE_MAP()

void CPasskeySetup::OnCancel()
{
   app.m_pMainWnd = NULL;
   CDialog::OnCancel();
}

void CPasskeySetup::OnOK()
{
   UpdateData(TRUE);
   if (m_passkey != m_verify)
   {
      AfxMessageBox("The two entries do not match.");
      ((CEdit*)GetDlgItem(IDC_VERIFY))->SetFocus();
      return;
   }

   if (m_passkey == "")
   {
      AfxMessageBox("Please enter a key and verify it.");
      ((CEdit*)GetDlgItem(IDC_PASSKEY))->SetFocus();
      return;
   }
   app.m_pMainWnd = NULL;
   CDialog::OnOK();
}

void CPasskeySetup::OnHelp()
{
   //WinHelp(0x20084, HELP_CONTEXT);
   ::HtmlHelp(NULL,
              "pwsafe.chm::/html/pws_intro.htm",
              HH_DISPLAY_TOPIC, 0);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<|endoftext|>