<commit_before>#include "blackmagicsdk_video_source.h"
#include "deck_link_display_mode_detector.h"
#include <thread>
#include <chrono>

namespace gg
{

VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()
    : IVideoSource()
    , _frame_rate(0.0)
    , _video_buffer(nullptr)
    , _video_buffer_length(0)
    , _cols(0)
    , _rows(0)
    , _buffer_video_frame(VideoFrame(UYVY))
    , _running(false)
{
    // nop
}

VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,
                                                   ColourSpace colour)
    : IVideoSource(colour)
    , _frame_rate(0.0)
    , _video_buffer(nullptr)
    , _video_buffer_length(0)
    , _cols(0)
    , _rows(0)
    , _buffer_video_frame(VideoFrame(colour, false)) // TODO manage data?
    , _deck_link(nullptr)
    , _deck_link_input(nullptr)
    , _running(false)
{
    // Pixel format, i.e. colour space
    BMDPixelFormat pixel_format;
    switch(_colour)
    {
    case UYVY:
        pixel_format = bmdFormat8BitYUV;
        break;
    case BGRA:
        pixel_format = bmdFormat8BitBGRA;
        break;
    case I420:
    default:
        bail("BlackmagicSDK video source supports only UYVY and BGRA colour spaces");
    }

    // Get an iterator through the available DeckLink ports
    IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();
    if (deck_link_iterator == nullptr)
        bail("DeckLink drivers do not appear to be installed");

    HRESULT res;

    // Get the desired DeckLink index (port)
    int idx = deck_link_index;
    while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)
    {
        if (idx == 0)
            break;
        --idx;

        _deck_link->Release();
    }
    if (deck_link_iterator != nullptr)
        deck_link_iterator->Release();
    // No glory: release everything and throw exception
    if (res != S_OK or _deck_link == nullptr)
        bail(
            std::string("Could not get DeckLink device ").append(std::to_string(deck_link_index))
        );

    // Get the input interface of connected DeckLink port
    res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));
    // No glory: release everything and throw exception
    if (res != S_OK)
        bail("Could not get the Blackmagic DeckLink input interface");

    // Set the input format (i.e. display mode)
    BMDDisplayMode display_mode;
    std::string error_msg = "";
    BMDVideoInputFlags video_input_flags = bmdVideoInputFlagDefault
            | bmdVideoInputDualStream3D;
    if (not detect_input_format(pixel_format, video_input_flags, display_mode, _frame_rate, error_msg))
        bail(error_msg);

    // Set this object (IDeckLinkInputCallback instance) as callback
    res = _deck_link_input->SetCallback(this);
    // No glory: release everything and throw exception
    if (res != S_OK)
        bail("Could not set the callback of Blackmagic DeckLink device");

    // Enable video input
    res = _deck_link_input->EnableVideoInput(display_mode,
                                             pixel_format,
                                             video_input_flags);
    // No glory
    if (res != S_OK)
        bail("Could not enable video input of Blackmagic DeckLink device");

    // Start streaming
    _running = true;
    res = _deck_link_input->StartStreams();
    // No glory: release everything and throw exception
    if (res != S_OK)
    {
        _running = false;
        bail("Could not start streaming from the Blackmagic DeckLink device");
    }

    // artificial sleep introduced to allow for starting of streams
    // the value is determined empirically
    std::this_thread::sleep_for(std::chrono::milliseconds(75));
}

VideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()
{
    { // Artificial scope for data lock
        // Make sure streamer thread not trying to access buffer
        std::lock_guard<std::mutex> data_lock_guard(_data_lock);
        _running = false;
    }

    // Stop streaming and disable enabled inputs
    _deck_link_input->SetCallback(nullptr);
    _deck_link_input->StopStreams();
    _deck_link_input->DisableVideoInput();

    // Release DeckLink members
    release_deck_link();
}

bool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)
{
    // Make sure only this thread is accessing the cols and rows members now
    std::lock_guard<std::mutex> data_lock_guard(_data_lock);
    if (_cols <= 0 or _rows <= 0)
        return false;

    width = _cols;
    height = _rows;
    return true;
}

bool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)
{
    if (frame.colour() != _colour)
        return false;

    // Make sure only this thread is accessing the video frame data now
    std::lock_guard<std::mutex> data_lock_guard(_data_lock);

    if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)
    {
        frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);
        return true;
    }
    else
        return false;
}

double VideoSourceBlackmagicSDK::get_frame_rate()
{
    return _frame_rate;
}

void VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)
{
    // issue #147
    throw VideoSourceError("Blackmagic does not support cropping yet");
}

void VideoSourceBlackmagicSDK::get_full_frame()
{
    // nop: set_sub_frame currently not implemented
}

HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)
{
    return E_NOINTERFACE;
}

ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)
{
    __sync_add_and_fetch(&_n_ref, 1);
    return _n_ref;
}

ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)
{
    __sync_sub_and_fetch(&_n_ref, 1);
    return _n_ref;
}

HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(
    BMDVideoInputFormatChangedEvents events,
    IDeckLinkDisplayMode * display_mode,
    BMDDetectedVideoInputFormatFlags format_flags
)
{
    // not supported yet: see issue #149
    return S_OK;
}

HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(
    IDeckLinkVideoInputFrame * video_frame,
    IDeckLinkAudioInputPacket * audio_packet
)
{
    if (not _running)
        // nop if not running!
        return S_OK;

    // Not processing the audio packet, but only the video
    // frame for the time being
    if (video_frame == nullptr)
        // nop if no data
        return S_OK;

    // Nr. of bytes of received data
    size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();

    { // Artificial scope for data lock
        // Make sure only this thread is accessing the buffer now
        std::lock_guard<std::mutex> data_lock_guard(_data_lock);

        // Extend buffer if more memory needed than already allocated
        if (n_bytes > _video_buffer_length)
            _video_buffer = reinterpret_cast<uint8_t *>(
                        realloc(_video_buffer, n_bytes * sizeof(uint8_t))
            );
        if (_video_buffer == nullptr) // something's terribly wrong!
            // nop if something's terribly wrong!
            return S_OK;

        // Get the new data into the buffer
        HRESULT res = video_frame->GetBytes(
            reinterpret_cast<void **>(&_video_buffer)
        );
        // If data could not be read into the buffer, return
        if (FAILED(res))
            return res;
        // Set video frame specs according to new data
        _video_buffer_length = n_bytes;
        _cols = video_frame->GetWidth();
        _rows = video_frame->GetHeight();

        // Propagate new video frame to observers
        _buffer_video_frame.init_from_specs(
            _video_buffer, _video_buffer_length, _cols, _rows
        );
    }

    this->notify(_buffer_video_frame);

    // Everything went fine, return success
    return S_OK;
}

void VideoSourceBlackmagicSDK::release_deck_link() noexcept
{
    if (_deck_link_input != nullptr)
    {
        _deck_link_input->Release();
        _deck_link_input = nullptr;
    }

    if (_deck_link != nullptr)
        _deck_link->Release();
}

bool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,
                                                   BMDVideoInputFlags & video_input_flags,
                                                   BMDDisplayMode & display_mode,
                                                   double & frame_rate,
                                                   std::string & error_msg) noexcept
{
    std::vector<BMDDisplayMode> display_modes =
    {
        bmdModeHD1080p6000, bmdModeHD1080p5994,
        bmdModeHD1080p50,
        bmdModeHD1080p30, bmdModeHD1080p2997,
        bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,
        bmdModeHD1080i6000, bmdModeHD1080i5994,
        bmdModeHD1080i50,
        bmdModeHD720p60, bmdModeHD720p5994,
        bmdModeHD720p50,
        bmdMode4K2160p60, bmdMode4K2160p5994,
        bmdMode4K2160p50,
        bmdMode4K2160p30, bmdMode4K2160p2997,
        bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,
        bmdMode2k25, bmdMode2k24, bmdMode2k2398,
    };

    DeckLinkDisplayModeDetector detector(
                _deck_link_input,
                display_modes, pixel_format, video_input_flags
    );
    BMDDisplayMode display_mode_ = detector.get_display_mode();
    if (display_mode_ != bmdModeUnknown)
    {
        frame_rate = detector.get_frame_rate();
        display_mode = display_mode_;
        video_input_flags = detector.get_video_input_flags();
        return true;
    }
    else
    {
        error_msg = detector.get_error_msg();
        return false;
    }
}

}
<commit_msg>Issue #5: Blackmagic video source falls back to non-stereo in case bmdVideoInputDualStream3D flag leads to error in input format detection<commit_after>#include "blackmagicsdk_video_source.h"
#include "deck_link_display_mode_detector.h"
#include <thread>
#include <chrono>

namespace gg
{

VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()
    : IVideoSource()
    , _frame_rate(0.0)
    , _video_buffer(nullptr)
    , _video_buffer_length(0)
    , _cols(0)
    , _rows(0)
    , _buffer_video_frame(VideoFrame(UYVY))
    , _running(false)
{
    // nop
}

VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,
                                                   ColourSpace colour)
    : IVideoSource(colour)
    , _frame_rate(0.0)
    , _video_buffer(nullptr)
    , _video_buffer_length(0)
    , _cols(0)
    , _rows(0)
    , _buffer_video_frame(VideoFrame(colour, false)) // TODO manage data?
    , _deck_link(nullptr)
    , _deck_link_input(nullptr)
    , _running(false)
{
    // Pixel format, i.e. colour space
    BMDPixelFormat pixel_format;
    switch(_colour)
    {
    case UYVY:
        pixel_format = bmdFormat8BitYUV;
        break;
    case BGRA:
        pixel_format = bmdFormat8BitBGRA;
        break;
    case I420:
    default:
        bail("BlackmagicSDK video source supports only UYVY and BGRA colour spaces");
    }

    // Get an iterator through the available DeckLink ports
    IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();
    if (deck_link_iterator == nullptr)
        bail("DeckLink drivers do not appear to be installed");

    HRESULT res;

    // Get the desired DeckLink index (port)
    int idx = deck_link_index;
    while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)
    {
        if (idx == 0)
            break;
        --idx;

        _deck_link->Release();
    }
    if (deck_link_iterator != nullptr)
        deck_link_iterator->Release();
    // No glory: release everything and throw exception
    if (res != S_OK or _deck_link == nullptr)
        bail(
            std::string("Could not get DeckLink device ").append(std::to_string(deck_link_index))
        );

    // Get the input interface of connected DeckLink port
    res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));
    // No glory: release everything and throw exception
    if (res != S_OK)
        bail("Could not get the Blackmagic DeckLink input interface");

    // Set the input format (i.e. display mode)
    BMDDisplayMode display_mode;
    std::string error_msg = "";
    BMDVideoInputFlags video_input_flags = bmdVideoInputFlagDefault
            | bmdVideoInputDualStream3D;
    if (not detect_input_format(pixel_format, video_input_flags, display_mode, _frame_rate, error_msg))
    {
        video_input_flags ^= bmdVideoInputDualStream3D;
        if (not detect_input_format(pixel_format, video_input_flags, display_mode, _frame_rate, error_msg))
            bail(error_msg);
    }

    // Set this object (IDeckLinkInputCallback instance) as callback
    res = _deck_link_input->SetCallback(this);
    // No glory: release everything and throw exception
    if (res != S_OK)
        bail("Could not set the callback of Blackmagic DeckLink device");

    // Enable video input
    res = _deck_link_input->EnableVideoInput(display_mode,
                                             pixel_format,
                                             video_input_flags);
    // No glory
    if (res != S_OK)
        bail("Could not enable video input of Blackmagic DeckLink device");

    // Start streaming
    _running = true;
    res = _deck_link_input->StartStreams();
    // No glory: release everything and throw exception
    if (res != S_OK)
    {
        _running = false;
        bail("Could not start streaming from the Blackmagic DeckLink device");
    }

    // artificial sleep introduced to allow for starting of streams
    // the value is determined empirically
    std::this_thread::sleep_for(std::chrono::milliseconds(75));
}

VideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()
{
    { // Artificial scope for data lock
        // Make sure streamer thread not trying to access buffer
        std::lock_guard<std::mutex> data_lock_guard(_data_lock);
        _running = false;
    }

    // Stop streaming and disable enabled inputs
    _deck_link_input->SetCallback(nullptr);
    _deck_link_input->StopStreams();
    _deck_link_input->DisableVideoInput();

    // Release DeckLink members
    release_deck_link();
}

bool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)
{
    // Make sure only this thread is accessing the cols and rows members now
    std::lock_guard<std::mutex> data_lock_guard(_data_lock);
    if (_cols <= 0 or _rows <= 0)
        return false;

    width = _cols;
    height = _rows;
    return true;
}

bool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)
{
    if (frame.colour() != _colour)
        return false;

    // Make sure only this thread is accessing the video frame data now
    std::lock_guard<std::mutex> data_lock_guard(_data_lock);

    if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)
    {
        frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);
        return true;
    }
    else
        return false;
}

double VideoSourceBlackmagicSDK::get_frame_rate()
{
    return _frame_rate;
}

void VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)
{
    // issue #147
    throw VideoSourceError("Blackmagic does not support cropping yet");
}

void VideoSourceBlackmagicSDK::get_full_frame()
{
    // nop: set_sub_frame currently not implemented
}

HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)
{
    return E_NOINTERFACE;
}

ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)
{
    __sync_add_and_fetch(&_n_ref, 1);
    return _n_ref;
}

ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)
{
    __sync_sub_and_fetch(&_n_ref, 1);
    return _n_ref;
}

HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(
    BMDVideoInputFormatChangedEvents events,
    IDeckLinkDisplayMode * display_mode,
    BMDDetectedVideoInputFormatFlags format_flags
)
{
    // not supported yet: see issue #149
    return S_OK;
}

HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(
    IDeckLinkVideoInputFrame * video_frame,
    IDeckLinkAudioInputPacket * audio_packet
)
{
    if (not _running)
        // nop if not running!
        return S_OK;

    // Not processing the audio packet, but only the video
    // frame for the time being
    if (video_frame == nullptr)
        // nop if no data
        return S_OK;

    // Nr. of bytes of received data
    size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();

    { // Artificial scope for data lock
        // Make sure only this thread is accessing the buffer now
        std::lock_guard<std::mutex> data_lock_guard(_data_lock);

        // Extend buffer if more memory needed than already allocated
        if (n_bytes > _video_buffer_length)
            _video_buffer = reinterpret_cast<uint8_t *>(
                        realloc(_video_buffer, n_bytes * sizeof(uint8_t))
            );
        if (_video_buffer == nullptr) // something's terribly wrong!
            // nop if something's terribly wrong!
            return S_OK;

        // Get the new data into the buffer
        HRESULT res = video_frame->GetBytes(
            reinterpret_cast<void **>(&_video_buffer)
        );
        // If data could not be read into the buffer, return
        if (FAILED(res))
            return res;
        // Set video frame specs according to new data
        _video_buffer_length = n_bytes;
        _cols = video_frame->GetWidth();
        _rows = video_frame->GetHeight();

        // Propagate new video frame to observers
        _buffer_video_frame.init_from_specs(
            _video_buffer, _video_buffer_length, _cols, _rows
        );
    }

    this->notify(_buffer_video_frame);

    // Everything went fine, return success
    return S_OK;
}

void VideoSourceBlackmagicSDK::release_deck_link() noexcept
{
    if (_deck_link_input != nullptr)
    {
        _deck_link_input->Release();
        _deck_link_input = nullptr;
    }

    if (_deck_link != nullptr)
        _deck_link->Release();
}

bool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,
                                                   BMDVideoInputFlags & video_input_flags,
                                                   BMDDisplayMode & display_mode,
                                                   double & frame_rate,
                                                   std::string & error_msg) noexcept
{
    std::vector<BMDDisplayMode> display_modes =
    {
        bmdModeHD1080p6000, bmdModeHD1080p5994,
        bmdModeHD1080p50,
        bmdModeHD1080p30, bmdModeHD1080p2997,
        bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,
        bmdModeHD1080i6000, bmdModeHD1080i5994,
        bmdModeHD1080i50,
        bmdModeHD720p60, bmdModeHD720p5994,
        bmdModeHD720p50,
        bmdMode4K2160p60, bmdMode4K2160p5994,
        bmdMode4K2160p50,
        bmdMode4K2160p30, bmdMode4K2160p2997,
        bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,
        bmdMode2k25, bmdMode2k24, bmdMode2k2398,
    };

    DeckLinkDisplayModeDetector detector(
                _deck_link_input,
                display_modes, pixel_format, video_input_flags
    );
    BMDDisplayMode display_mode_ = detector.get_display_mode();
    if (display_mode_ != bmdModeUnknown)
    {
        frame_rate = detector.get_frame_rate();
        display_mode = display_mode_;
        video_input_flags = detector.get_video_input_flags();
        return true;
    }
    else
    {
        error_msg = detector.get_error_msg();
        return false;
    }
}

}
<|endoftext|>


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

#include "common/error.h"
#include "common/io.h"

#ifndef SHADERS_DIR
#define SHADERS_DIR "./shaders/"
#endif

const float vertices[] = {
     0.0f,  0.5f,  1.0f, 0.0f, 0.0f, // vertex 1: Red
     0.5f, -0.5f,  0.0f, 1.0f, 0.0f, // vertex 2: Green
    -0.5f, -0.5f,  0.0f, 0.0f, 1.0f  // vertex 3: Blue
};

enum class ShaderType {vertex, fragment};

/**
 * Read |filename| from SHADERS_DIR, compile it as a shader and return its ID.
 */
GLuint compileShader(const std::string& filename, ShaderType type) {
    std::string source = readFile(SHADERS_DIR + filename);
    if (source.length() == 0)
      throw Exception("empty shader file");
    auto gl_type = GL_VERTEX_SHADER;
    if (type != ShaderType::vertex) gl_type = GL_FRAGMENT_SHADER;

    GLuint shader = glCreateShader(gl_type);
    const char* source_c = source.c_str();
    glShaderSource(shader, 1, &source_c, NULL);
    glCompileShader(shader);
    GLint status;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
    if (status != GL_TRUE) {
        std::cerr << "Failed to compile shader:\n";
        std::cerr << source << std::endl;
        std::cerr << "************************************\n";
        char buffer[512];
        glGetShaderInfoLog(shader, 512, NULL, buffer);
        std::cerr << buffer;
        throw Exception();
    }
    printGlErrors();
    return shader;
}

void initGlew() {
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    printGlErrors();
    if(err != GLEW_OK) {
        throw Exception("glewInit failed");
    }
}

/**
 * Return ID of the linked and activated shader.
 */
GLuint initShaders() {
    auto vshader = compileShader("vshader.glsl", ShaderType::vertex);
    auto fshader = compileShader("fshader.glsl", ShaderType::fragment);
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vshader);
    glAttachShader(shaderProgram, fshader);
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);
    printGlErrors();
    return shaderProgram;
}

SDL_GLContext initContext(SDL_Window *window) {
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                        SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GLContext context = SDL_GL_CreateContext(window);
    printGlErrors();
    return context;
}

/**
 * Copy buffers to memory, set shader attributes, bind to VAO.
 * Return bound VAO ID.
 */
GLuint initBuffers(GLuint shaderProgram) {
    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                 GL_STATIC_DRAW);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), 0);

    GLint colorAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colorAttrib);
    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), (void*)(2*sizeof(float)));

    GLint uniColor = glGetUniformLocation(shaderProgram, "triangleColor");
    glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);
    printGlErrors();
    return vao;
}

void paint() {
    glDrawArrays(GL_TRIANGLES, 0, 3);
    printGlErrors();
}

int main(int argc, char *argv[]) {
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("Hello World",
                                           100, 100, 800, 600,
                                           SDL_WINDOW_OPENGL);
    auto context = initContext(window);
    initGlew();
    auto program = initShaders();
    initBuffers(program);

    paint();

    SDL_Event event;
    while (true) {
        if (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) break;
            if (event.type == SDL_KEYDOWN) break;
        }
        SDL_GL_SwapWindow(window);
    }

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
<commit_msg>tutorial: work around known glew bug<commit_after>/* Copyright 2015 Martina Kollarova
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <iostream>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_opengl.h>

#include "common/error.h"
#include "common/io.h"

#ifndef SHADERS_DIR
#define SHADERS_DIR "./shaders/"
#endif

const float vertices[] = {
     0.0f,  0.5f,  1.0f, 0.0f, 0.0f, // vertex 1: Red
     0.5f, -0.5f,  0.0f, 1.0f, 0.0f, // vertex 2: Green
    -0.5f, -0.5f,  0.0f, 0.0f, 1.0f  // vertex 3: Blue
};

enum class ShaderType {vertex, fragment};

/**
 * Read |filename| from SHADERS_DIR, compile it as a shader and return its ID.
 */
GLuint compileShader(const std::string& filename, ShaderType type) {
    std::string source = readFile(SHADERS_DIR + filename);
    if (source.length() == 0)
      throw Exception("empty shader file");
    auto gl_type = GL_VERTEX_SHADER;
    if (type != ShaderType::vertex) gl_type = GL_FRAGMENT_SHADER;

    GLuint shader = glCreateShader(gl_type);
    const char* source_c = source.c_str();
    glShaderSource(shader, 1, &source_c, NULL);
    glCompileShader(shader);
    GLint status;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
    if (status != GL_TRUE) {
        std::cerr << "Failed to compile shader:\n";
        std::cerr << source << std::endl;
        std::cerr << "************************************\n";
        char buffer[512];
        glGetShaderInfoLog(shader, 512, NULL, buffer);
        std::cerr << buffer;
        throw Exception();
    }
    printGlErrors();
    return shader;
}

void initGlew() {
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    // ignore "invalid enumerant" error, it's a known bug
    // https://www.opengl.org/wiki/OpenGL_Loading_Library
    GLenum error = glGetError();
    if (error != GL_INVALID_ENUM)
        throw Exception("glewInit failed");
    printGlErrors();
    if(err != GLEW_OK) {
        throw Exception("glewInit failed");
    }
}

/**
 * Return ID of the linked and activated shader.
 */
GLuint initShaders() {
    auto vshader = compileShader("vshader.glsl", ShaderType::vertex);
    auto fshader = compileShader("fshader.glsl", ShaderType::fragment);
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vshader);
    glAttachShader(shaderProgram, fshader);
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);
    printGlErrors();
    return shaderProgram;
}

SDL_GLContext initContext(SDL_Window *window) {
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                        SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GLContext context = SDL_GL_CreateContext(window);
    printGlErrors();
    return context;
}

/**
 * Copy buffers to memory, set shader attributes, bind to VAO.
 * Return bound VAO ID.
 */
GLuint initBuffers(GLuint shaderProgram) {
    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                 GL_STATIC_DRAW);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), 0);

    GLint colorAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colorAttrib);
    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), (void*)(2*sizeof(float)));

    GLint uniColor = glGetUniformLocation(shaderProgram, "triangleColor");
    glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);
    printGlErrors();
    return vao;
}

void paint() {
    glDrawArrays(GL_TRIANGLES, 0, 3);
    printGlErrors();
}

int main(int argc, char *argv[]) {
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("Hello World",
                                           100, 100, 800, 600,
                                           SDL_WINDOW_OPENGL);
    auto context = initContext(window);
    initGlew();
    auto program = initShaders();
    initBuffers(program);

    paint();

    SDL_Event event;
    while (true) {
        if (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) break;
            if (event.type == SDL_KEYDOWN) break;
        }
        SDL_GL_SwapWindow(window);
    }

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
<|endoftext|>


<commit_before>#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP
# pragma once

#include <cassert>

#include <atomic>

#include <memory>

#include <utility>

#include <type_traits>

namespace generic
{

namespace detail
{
  using counter_type = unsigned;

  using atomic_type = ::std::atomic<counter_type>;

  template <typename T>
  using deleter_type = void (*)(T*);

  template <typename U>
  struct ref_type
  {
    using type = U&;
  };

  template <>
  struct ref_type<void>
  {
    using type = void;
  };
}

template <typename T>
class light_ptr
{
  template <typename U, typename V>
  struct deletion_type
  {
    using type = V;
  };

  template <typename U, typename V>
  struct deletion_type<U[], V>
  {
    using type = V[];
  };

  template <typename U, typename V, ::std::size_t N>
  struct deletion_type<U[N], V>
  {
    using type = V[];
  };

  template <typename U>
  struct is_array_type : ::std::false_type { };

  template <typename U>
  struct is_array_type<U[]> : ::std::true_type { };

  template <typename U, ::std::size_t N>
  struct is_array_type<U[N]> : ::std::true_type { };

  template <typename U>
  struct remove_array
  {
    using type = U;
  };

  template <typename U>
  struct remove_array<U[]>
  {
    using type = U;
  };

  template <typename U, ::std::size_t N>
  struct remove_array<U[N]>
  {
    using type = U;
  };

  using element_type = typename remove_array<T>::type;

  using deleter_type = detail::deleter_type<element_type>;

  class counter_base
  {
    friend class light_ptr;

    using invoker_type = void (*)(counter_base*, element_type*);

    detail::atomic_type counter_{};

    invoker_type const invoker_;

  protected:
    explicit counter_base(detail::counter_type const c,
      invoker_type const invoker) noexcept :
      counter_(c),
      invoker_(invoker)
    {
    }

  public:
    template <typename U>
    typename ::std::enable_if<!::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        using type_must_be_complete = char[sizeof(U) ? 1 : -1];
        (void)sizeof(type_must_be_complete);
        invoker_(this, ptr);
      }
      // else do nothing
    }

    template <typename U>
    typename ::std::enable_if<::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        invoker_(this, ptr);
      }
      // else do nothing
    }

    void inc_ref() noexcept
    {
      counter_.fetch_add(detail::counter_type(1),
        ::std::memory_order_relaxed);
    }
  };

  template <typename D>
  class counter : public counter_base
  {
    typename ::std::decay<D>::type const d_;

  public:
    explicit counter(detail::counter_type const c, D&& d) :
      counter_base(c, invoker),
      d_(::std::forward<D>(d))
    {
    }

  private:
    static void invoker(counter_base* const ptr, element_type* const e)
    {
      auto const c(static_cast<counter<D>*>(ptr));

      // invoke deleter on the element
      c->d_(e);

      // delete from a static member function
      delete c;
    }
  };

private:
  template <typename U> friend struct ::std::hash;

  counter_base* counter_{};

  element_type* ptr_{};

public:
  light_ptr() = default;

  template <typename U>
  explicit light_ptr(U* const p)
  {
    reset(p);
  }

  template <typename U, typename D>
  explicit light_ptr(U* const p, D&& d)
  {
    reset(p, ::std::forward<D>(d));
  }

  light_ptr(light_ptr const& other) { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }

  ~light_ptr()
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing
  }

  light_ptr& operator=(light_ptr const& rhs)
  {
    if (*this != rhs)
    {
      if (counter_)
      {
        counter_->dec_ref(ptr_);
      }
      // else do nothing

      if ((counter_ = rhs.counter_))
      {
        counter_->inc_ref();
      }
      // else do nothing

      ptr_ = rhs.ptr_;
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ = rhs.counter_;
    rhs.counter_ = nullptr;

    ptr_ = rhs.ptr_;
    rhs.ptr_ = nullptr;

    return *this;
  }

  light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }

  bool operator<(light_ptr const& rhs) const noexcept
  {
    return counter_ < rhs.counter_;
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ == rhs.counter_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  bool operator==(::std::nullptr_t const) const noexcept { return !ptr_; }

  bool operator!=(::std::nullptr_t const) const noexcept { return ptr_; }

  explicit operator bool() const noexcept { return ptr_; }

  typename detail::ref_type<T>::type
  operator*() const noexcept
  {
    return *reinterpret_cast<T*>(ptr_);
  }

  T* operator->() const noexcept { return reinterpret_cast<T*>(ptr_); }

  template <typename U = T, typename =
    typename ::std::enable_if<is_array_type<U>{}>::type>
  typename detail::ref_type<element_type>::type operator[](
    ::std::size_t const i) const noexcept
  {
    return ptr_[i];
  }

  element_type* get() const noexcept { return ptr_; }

  void reset() { reset(nullptr); }

  void reset(::std::nullptr_t const)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);

      counter_ = {};
    }
    // else do nothing

    ptr_ = {};
  }

  template <typename U>
  void reset(U* const p)
  {
    reset(p, [](element_type* const p) {
      ::std::default_delete<typename deletion_type<T, U>::type>()(
        static_cast<U*>(p));
    });
  }

  template <typename U, typename D>
  void reset(U* const p, D&& d)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing

    counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d));

    ptr_ = p;
  }

  void swap(light_ptr& other) noexcept
  {
    ::std::swap(counter_, other.counter_);
    ::std::swap(ptr_, other.ptr_);
  }

  bool unique() const noexcept
  {
    return detail::counter_type(1) == use_count();
  }

  detail::counter_type use_count() const noexcept
  {
    return counter_ ?
      counter_->counter_.load(::std::memory_order_relaxed) :
      detail::counter_type{};
  }
};

template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
  return light_ptr<T>(new T(::std::forward<Args>(args)...));
}

}

namespace std
{
  template <typename T>
  struct hash<::generic::light_ptr<T> >
  {
    size_t operator()(::generic::light_ptr<T> const& l) const noexcept
    {
      return hash<typename ::generic::light_ptr<T>::element_type*>()(
        l.counter_);
    }
  };
}

#endif // LIGHTPTR_HPP
<commit_msg>any fix<commit_after>#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP
# pragma once

#include <cassert>

#include <atomic>

#include <memory>

#include <utility>

#include <type_traits>

namespace generic
{

namespace detail
{
  using counter_type = unsigned;

  using atomic_type = ::std::atomic<counter_type>;

  template <typename T>
  using deleter_type = void (*)(T*);

  template <typename U>
  struct ref_type
  {
    using type = U&;
  };

  template <>
  struct ref_type<void>
  {
    using type = void;
  };
}

template <typename T>
class light_ptr
{
  template <typename U, typename V>
  struct deletion_type
  {
    using type = V;
  };

  template <typename U, typename V>
  struct deletion_type<U[], V>
  {
    using type = V[];
  };

  template <typename U, typename V, ::std::size_t N>
  struct deletion_type<U[N], V>
  {
    using type = V[];
  };

  using element_type = typename ::std::remove_extent<T>::type;

  using deleter_type = detail::deleter_type<element_type>;

  class counter_base
  {
    friend class light_ptr;

    using invoker_type = void (*)(counter_base*, element_type*);

    detail::atomic_type counter_{};

    invoker_type const invoker_;

  protected:
    explicit counter_base(detail::counter_type const c,
      invoker_type const invoker) noexcept :
      counter_(c),
      invoker_(invoker)
    {
    }

  public:
    template <typename U>
    typename ::std::enable_if<!::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        using type_must_be_complete = char[sizeof(U) ? 1 : -1];
        (void)sizeof(type_must_be_complete);
        invoker_(this, ptr);
      }
      // else do nothing
    }

    template <typename U>
    typename ::std::enable_if<::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        invoker_(this, ptr);
      }
      // else do nothing
    }

    void inc_ref() noexcept
    {
      counter_.fetch_add(detail::counter_type(1),
        ::std::memory_order_relaxed);
    }
  };

  template <typename D>
  class counter : public counter_base
  {
    typename ::std::decay<D>::type const d_;

  public:
    explicit counter(detail::counter_type const c, D&& d) :
      counter_base(c, invoker),
      d_(::std::forward<D>(d))
    {
    }

  private:
    static void invoker(counter_base* const ptr, element_type* const e)
    {
      auto const c(static_cast<counter<D>*>(ptr));

      // invoke deleter on the element
      c->d_(e);

      // delete from a static member function
      delete c;
    }
  };

private:
  template <typename U> friend struct ::std::hash;

  counter_base* counter_{};

  element_type* ptr_{};

public:
  light_ptr() = default;

  template <typename U>
  explicit light_ptr(U* const p)
  {
    reset(p);
  }

  template <typename U, typename D>
  explicit light_ptr(U* const p, D&& d)
  {
    reset(p, ::std::forward<D>(d));
  }

  light_ptr(light_ptr const& other) { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }

  ~light_ptr()
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing
  }

  light_ptr& operator=(light_ptr const& rhs)
  {
    if (*this != rhs)
    {
      if (counter_)
      {
        counter_->dec_ref(ptr_);
      }
      // else do nothing

      if ((counter_ = rhs.counter_))
      {
        counter_->inc_ref();
      }
      // else do nothing

      ptr_ = rhs.ptr_;
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ = rhs.counter_;
    rhs.counter_ = nullptr;

    ptr_ = rhs.ptr_;
    rhs.ptr_ = nullptr;

    return *this;
  }

  light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }

  bool operator<(light_ptr const& rhs) const noexcept
  {
    return counter_ < rhs.counter_;
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ == rhs.counter_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  bool operator==(::std::nullptr_t const) const noexcept { return !ptr_; }

  bool operator!=(::std::nullptr_t const) const noexcept { return ptr_; }

  explicit operator bool() const noexcept { return ptr_; }

  typename detail::ref_type<T>::type
  operator*() const noexcept
  {
    return *reinterpret_cast<T*>(ptr_);
  }

  T* operator->() const noexcept { return reinterpret_cast<T*>(ptr_); }

  template <typename U = T, typename =
    typename ::std::enable_if<::std::is_array<U>{}>::type>
  typename detail::ref_type<element_type>::type operator[](
    ::std::size_t const i) const noexcept
  {
    return ptr_[i];
  }

  element_type* get() const noexcept { return ptr_; }

  void reset() { reset(nullptr); }

  void reset(::std::nullptr_t const)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);

      counter_ = {};
    }
    // else do nothing

    ptr_ = {};
  }

  template <typename U>
  void reset(U* const p)
  {
    reset(p, [](element_type* const p) {
      ::std::default_delete<typename deletion_type<T, U>::type>()(
        static_cast<U*>(p));
    });
  }

  template <typename U, typename D>
  void reset(U* const p, D&& d)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing

    counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d));

    ptr_ = p;
  }

  void swap(light_ptr& other) noexcept
  {
    ::std::swap(counter_, other.counter_);
    ::std::swap(ptr_, other.ptr_);
  }

  bool unique() const noexcept
  {
    return detail::counter_type(1) == use_count();
  }

  detail::counter_type use_count() const noexcept
  {
    return counter_ ?
      counter_->counter_.load(::std::memory_order_relaxed) :
      detail::counter_type{};
  }
};

template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
  return light_ptr<T>(new T(::std::forward<Args>(args)...));
}

}

namespace std
{
  template <typename T>
  struct hash<::generic::light_ptr<T> >
  {
    size_t operator()(::generic::light_ptr<T> const& l) const noexcept
    {
      return hash<typename ::generic::light_ptr<T>::element_type*>()(
        l.counter_);
    }
  };
}

#endif // LIGHTPTR_HPP
<|endoftext|>


<commit_before>//=================================================================================================
//                    Copyright (C) 2017 Olivier Mallet - All Rights Reserved
//=================================================================================================

#ifndef RANDOMIZE_H
#define RANDOMIZE_H

namespace galgo {

//=================================================================================================

// template metaprogramming for getting maximum unsigned integral value from N bits
template <unsigned int N>
struct MAXVALUE
{
    enum : uint64_t{ value = 2 * MAXVALUE<N - 1>::value };
};

// template specialization for initial case N = 0
template <>
struct MAXVALUE<0>
{
    enum { value = 1 };
};

/*-------------------------------------------------------------------------------------------------*/

// Mersenne Twister 19937 pseudo-random number generator
std::random_device rand_dev;
std::mt19937_64 rng(rand_dev());

// generate uniform random probability in range [0,1)
std::uniform_real_distribution<> proba(0, 1);

/*-------------------------------------------------------------------------------------------------*/

// generate a uniform random number within the interval [min,max)
template <typename T>
inline T uniform(T min, T max)
{
    #ifndef NDEBUG
    if (min >= max) {
      throw std::invalid_argument("Error: in galgo::uniform(T, T), first argument must be < to second argument.");
    }
    #endif

    return min + proba(rng) * (max - min);
}

//=================================================================================================

}

#endif
<commit_msg>Delete Randomize.hpp<commit_after><|endoftext|>


<commit_before>#include<seq_view.h>

namespace SeqView {

    void SeqWindow::_scroll(int64_t newleft, int64_t newtop) {
        first_seq = newtop;
        first_pos = newleft;
        modified = true;
        display();
    }

    // Given the current window size and the width
    // of the names, figure out how many sequences and positions
    // should be displayed. Also recalculate last_pos and last_seq.
    void SeqWindow::_recalculate_num_displayed() {
        // Need to reserve three lines - two for positions and one
        // for the filename
        // Need to reserve names_width + 1 columns for names
        num_pos_displayed = width - names_width - 1;
        num_seqs_displayed = height - 3;
        last_pos = first_pos + num_pos_displayed - 1;
        last_seq = first_seq + num_seqs_displayed - 1;
        modified = true;
    }

    void SeqWindow::_display_names() {
        if(isfocal)
            wattron(window, A_BOLD);
        wattron(window, COLOR_PAIR(7));
        std::vector<string> names = seqs.nameSlice(first_seq, last_seq);
        for(int i = 0; i < num_seqs_displayed - 1; i++) {
            mvwprintw(window, i+2, 0, string(names_width + 1, ' ').c_str());
            if(names_width > names[i].length())
                mvwprintw(window, i+2, 0, names[i].c_str());
            else
                mvwprintw(window, i + 2, 0,
                        names[i].substr(0, names_width).c_str());
        }
        if(isfocal)
            wattroff(window, A_BOLD);
        wattroff(window, COLOR_PAIR(7));
    }

    void SeqWindow::_display_positions() {
        if(isfocal)
            wattron(window, A_BOLD);
        wattron(window, COLOR_PAIR(7));
        for(int i = 0; i < width; i++) {
            mvwprintw(window, 0, i, " ");
            mvwprintw(window, 1, i, " ");
        }
        int col = names_width + 1;
        int frame = seqs.get_frame();
        for(int i = first_pos + 1; i < last_pos + 2; i++) {
            if(!(i % 10)) {
                mvwprintw(window, 1, col, "|");
                mvwprintw(window, 0, col, "%i", i);
            } else if(!(i % 5)) {
                mvwprintw(window, 1, col, ":");
            } else {
                mvwprintw(window, 1, col, ".");
            }
            if(display_mode == CODON) {
                if((i - frame + 1) % 3 == 0) {
                    col++;
                    mvwprintw(window, 1, col, " ");
                }
            }
            col++;
            if(col >= width)
                break;
        }
        // Sometimes the numbers spill over to the next line - this
        // gets rid of that.
        mvwprintw(window, 1, 0, string(names_width, ' ').c_str());
        if(isfocal)
            wattroff(window, A_BOLD);
        wattroff(window, COLOR_PAIR(7));
    }

    void SeqWindow::_display_seqs() {
        // This function is more tricky - will require some added
        // arguments for formatting eventually.
        // Also may require some adjustment to color amino acid
        // sequences properly.
        std::pair< std::vector<string>, std::vector<bool> >
            s= seqs.slice(first_pos, last_pos, first_seq, last_seq,
                    display_mode, compare);
        std::vector<string> sequences = s.first;
        std::vector<bool> comps = s.second;
        int row = 2;
        char ch;
        int col;
        if(bolded)
            wattron(window, A_BOLD);
        for(int i = 0; i < num_seqs_displayed - 1; i++) {
            for(int j = 0; j < sequences[i].length(); j++) {
                if(compare && comps[j] && (i + first_seq) < seqs.numseqs())
                    wattron(window, A_REVERSE);
                ch = sequences[i][j];
                if(ch == 'A' || ch == 'a')
                    wattron(window, COLOR_PAIR(1));
                else if(ch == 'T' || ch == 't')
                    wattron(window, COLOR_PAIR(2));
                else if(ch == 'G' || ch == 'g')
                    wattron(window, COLOR_PAIR(3));
                else if(ch == 'C' || ch == 'c')
                    wattron(window, COLOR_PAIR(4));
                else
                    col = 7;
                mvwaddch(window, row, names_width + 1 + j, ch);
                wattroff(window, COLOR_PAIR(col));
                if(compare && comps[j])
                    wattroff(window, A_REVERSE);
            }
            row++;
        }
        if(bolded)
            wattroff(window, A_BOLD);
    }

    void SeqWindow::_display_filename() {
        // display at bottom
        wattron(window, COLOR_PAIR(7) | A_UNDERLINE);
        if(isfocal)
            wattron(window, A_REVERSE | A_BOLD);
        mvwprintw(window, height - 2, 0, seqs.filename.c_str());
        for(int i = seqs.filename.length() + 1; i <= width; i++)
            mvwprintw(window, height - 2, i - 1, " ");
        if(isfocal)
            wattroff(window, A_REVERSE | A_BOLD);
        wattroff(window, COLOR_PAIR(7) | A_UNDERLINE);
    }

    SeqWindow::SeqWindow() {
        modified = true;
        compare = false;
        bolded = true;
    }

    SeqWindow::SeqWindow(int upperleftX, int upperleftY,
            int _width, int _height, SeqSet &sq) {
        window = newwin(_height, _width, upperleftY, upperleftX);
        width = _width;
        height = _height;
        seqs = sq;
        scrollmode = 1;
        display_mode = NORMAL;
        names_width = 15;
        first_pos = 0;
        first_seq = 0;
        update_size();
        _recalculate_num_displayed();
        isfocal = true;
        bolded = true;
        modified = true;
        compare = false;
        display();
    }

    SeqWindow::SeqWindow(int upperleftX, int upperleftY,
            int _width, int _height, string filename,
            ParserFunction parser) {
        SeqSet sq;
        parser(filename, sq);
        window = newwin(_height, _width, upperleftY, upperleftX);
        width = _width + 1;
        height = _height + 1;
        seqs = sq;
        scrollmode = 1;
        display_mode = NORMAL;
        names_width = 15;
        first_pos = 0;
        first_seq = 0;
        update_size();
        _recalculate_num_displayed();
        bolded = true;
        modified = true;
        compare = false;
        display();
    }

    SeqWindow::~SeqWindow() {
        wattron(window, COLOR_PAIR(8));
        for(int i = 0; i < height; i++) {
            mvwprintw(window, i, 0, string(width, ' ').c_str());
        }
        wattroff(window, COLOR_PAIR(8));
        wrefresh(window);
        delwin(window);
    }

    void SeqWindow::set_focus(bool focal) {
        isfocal = focal;
        modified = true;
    }

    // scroll mode is in powers of 10
    void SeqWindow::set_scroll_mode(int mode) {
        if(mode < 0 || mode > 9)
            return;
        scrollmode = pow(10, mode);
    }

    void SeqWindow::update_size() {
        getmaxyx(window, height, width);
        height += 1;
        width += 1;
    }

    void SeqWindow::change_name_width(int newwidth) {
        if(newwidth < width - 5  && newwidth > 1) {
            names_width = newwidth;
            update_size();
            _recalculate_num_displayed();
        }
    }

    // Deal with commands that change SeqSet params
    void SeqWindow::handle_command(Command command) {
        Com com_name = command.first;
        int param = command.second;
        int newpos;
        if(com_name == SCROLLUP) {
            if(first_seq > 0) {
                newpos = first_seq - param;
                if(newpos < 0)
                    newpos = 0;
                _scroll(first_pos, newpos);
            }
        } else if(com_name == SCROLLDOWN) {
            if(first_seq < seqs.numseqs()) {
                newpos = first_seq + param;
                if(newpos >= seqs.numseqs())
                    newpos = seqs.numseqs() - 1;
                _scroll(first_pos, newpos);
            }
        } else if(com_name == SCROLLLEFT) {
            if(first_pos > 0) {
                newpos = first_pos - scrollmode * param;
                if(newpos < 0)
                    newpos = 0;
                _scroll(newpos, first_seq);
            }
        } else if(com_name == SCROLLRIGHT) {
            if(first_pos < seqs.length()) {
                newpos = first_pos + scrollmode * param;
                if(newpos >= seqs.length())
                    newpos = seqs.length() - 1;
                _scroll(newpos, first_seq);
            }
        } else if(com_name == SCROLLTOP) {
            _scroll(first_pos, 0);
        } else if(com_name == SCROLLBOTTOM) {
            _scroll(first_pos, seqs.numseqs() - 1);
        } else if(com_name == GOTOBEGIN) {
            _scroll(0, first_seq);
        } else if(com_name == GOTOEND) {
            _scroll(seqs.length() - 1, first_seq);
        } else if(com_name == GOTO) {
            newpos = param - 1 - (width - names_width) / 2;
            if(display_mode == CODON)
                newpos += (width - names_width) / 6;
            if(newpos < 0)
                newpos = 0;
            if(newpos > seqs.length() - 1)
                newpos = seqs.length() - 1;
            _scroll(newpos, first_seq);
        } else if(com_name == SCROLLMODE) {
            set_scroll_mode(param);
        } else if(com_name == NAMEWIDTH) {
            change_name_width(param);
        } else if(com_name == DISPLAYMODE) {
            if(param == 1)
                display_mode = NORMAL;
            else if(param == 2)
                display_mode = CODON;
            modified = true;
        } else if(com_name == SETFRAME) {
            seqs.set_frame(param);
            modified = true;
        } else if(com_name == COMPARE) {
            compare = !compare;
            modified = true;
        } else if(com_name == TOGGLEBOLD) {
            bolded = !bolded;
            modified = true;
        }
    }

    void SeqWindow::resize(int upperleftX, int upperleftY,
            int newwidth, int newheight) {
        wattron(window, COLOR_PAIR(8));
        for(int i = 0; i < height; i++) {
            mvwprintw(window, i, 0, string(width, ' ').c_str());
        }
        wrefresh(window);
        delwin(window);
        window = newwin(newheight, newwidth,
                upperleftY, upperleftX);
        height = newheight;
        width = newwidth;
        update_size();
        _recalculate_num_displayed();
        modified = true;
        display();
    }

    // Refresh, get the slice of the sequence, add the formatting,
    // and use wprintw to put everything on the screen.
    void SeqWindow::display() {
        int w = width;
        int h = height;
        update_size();
        if(w != width || h != height)
            modified = true;
        if(modified) {
            _recalculate_num_displayed();
            _display_names();
            _display_positions();
            _display_seqs();
            _display_filename();
            wrefresh(window);
        } else {
        }
    }
}
<commit_msg>Small fix to comparison display code.<commit_after>#include<seq_view.h>

namespace SeqView {

    void SeqWindow::_scroll(int64_t newleft, int64_t newtop) {
        first_seq = newtop;
        first_pos = newleft;
        modified = true;
        display();
    }

    // Given the current window size and the width
    // of the names, figure out how many sequences and positions
    // should be displayed. Also recalculate last_pos and last_seq.
    void SeqWindow::_recalculate_num_displayed() {
        // Need to reserve three lines - two for positions and one
        // for the filename
        // Need to reserve names_width + 1 columns for names
        num_pos_displayed = width - names_width - 1;
        num_seqs_displayed = height - 3;
        last_pos = first_pos + num_pos_displayed - 1;
        last_seq = first_seq + num_seqs_displayed - 1;
        modified = true;
    }

    void SeqWindow::_display_names() {
        if(isfocal)
            wattron(window, A_BOLD);
        wattron(window, COLOR_PAIR(7));
        std::vector<string> names = seqs.nameSlice(first_seq, last_seq);
        for(int i = 0; i < num_seqs_displayed - 1; i++) {
            mvwprintw(window, i+2, 0, string(names_width + 1, ' ').c_str());
            if(names_width > names[i].length())
                mvwprintw(window, i+2, 0, names[i].c_str());
            else
                mvwprintw(window, i + 2, 0,
                        names[i].substr(0, names_width).c_str());
        }
        if(isfocal)
            wattroff(window, A_BOLD);
        wattroff(window, COLOR_PAIR(7));
    }

    void SeqWindow::_display_positions() {
        if(isfocal)
            wattron(window, A_BOLD);
        wattron(window, COLOR_PAIR(7));
        for(int i = 0; i < width; i++) {
            mvwprintw(window, 0, i, " ");
            mvwprintw(window, 1, i, " ");
        }
        int col = names_width + 1;
        int frame = seqs.get_frame();
        for(int i = first_pos + 1; i < last_pos + 2; i++) {
            if(!(i % 10)) {
                mvwprintw(window, 1, col, "|");
                mvwprintw(window, 0, col, "%i", i);
            } else if(!(i % 5)) {
                mvwprintw(window, 1, col, ":");
            } else {
                mvwprintw(window, 1, col, ".");
            }
            if(display_mode == CODON) {
                if((i - frame + 1) % 3 == 0) {
                    col++;
                    mvwprintw(window, 1, col, " ");
                }
            }
            col++;
            if(col >= width)
                break;
        }
        // Sometimes the numbers spill over to the next line - this
        // gets rid of that.
        mvwprintw(window, 1, 0, string(names_width, ' ').c_str());
        if(isfocal)
            wattroff(window, A_BOLD);
        wattroff(window, COLOR_PAIR(7));
    }

    void SeqWindow::_display_seqs() {
        // This function is more tricky - will require some added
        // arguments for formatting eventually.
        // Also may require some adjustment to color amino acid
        // sequences properly.
        std::pair< std::vector<string>, std::vector<bool> >
            s= seqs.slice(first_pos, last_pos, first_seq, last_seq,
                    display_mode, compare);
        std::vector<string> sequences = s.first;
        std::vector<bool> comps = s.second;
        int row = 2;
        char ch;
        int col;
        if(bolded)
            wattron(window, A_BOLD);
        for(int i = 0; i < num_seqs_displayed - 1; i++) {
            for(int j = 0; j < sequences[i].length(); j++) {
                ch = sequences[i][j];
                if(compare && comps[j] && (i + first_seq) < seqs.numseqs() && ch != ' ')
                    wattron(window, A_REVERSE);
                if(ch == 'A' || ch == 'a')
                    wattron(window, COLOR_PAIR(1));
                else if(ch == 'T' || ch == 't')
                    wattron(window, COLOR_PAIR(2));
                else if(ch == 'G' || ch == 'g')
                    wattron(window, COLOR_PAIR(3));
                else if(ch == 'C' || ch == 'c')
                    wattron(window, COLOR_PAIR(4));
                else
                    col = 7;
                mvwaddch(window, row, names_width + 1 + j, ch);
                wattroff(window, COLOR_PAIR(col));
                if(compare && comps[j])
                    wattroff(window, A_REVERSE);
            }
            row++;
        }
        if(bolded)
            wattroff(window, A_BOLD);
    }

    void SeqWindow::_display_filename() {
        // display at bottom
        wattron(window, COLOR_PAIR(7) | A_UNDERLINE);
        if(isfocal)
            wattron(window, A_REVERSE | A_BOLD);
        mvwprintw(window, height - 2, 0, seqs.filename.c_str());
        for(int i = seqs.filename.length() + 1; i <= width; i++)
            mvwprintw(window, height - 2, i - 1, " ");
        if(isfocal)
            wattroff(window, A_REVERSE | A_BOLD);
        wattroff(window, COLOR_PAIR(7) | A_UNDERLINE);
    }

    SeqWindow::SeqWindow() {
        modified = true;
        compare = false;
        bolded = true;
    }

    SeqWindow::SeqWindow(int upperleftX, int upperleftY,
            int _width, int _height, SeqSet &sq) {
        window = newwin(_height, _width, upperleftY, upperleftX);
        width = _width;
        height = _height;
        seqs = sq;
        scrollmode = 1;
        display_mode = NORMAL;
        names_width = 15;
        first_pos = 0;
        first_seq = 0;
        update_size();
        _recalculate_num_displayed();
        isfocal = true;
        bolded = true;
        modified = true;
        compare = false;
        display();
    }

    SeqWindow::SeqWindow(int upperleftX, int upperleftY,
            int _width, int _height, string filename,
            ParserFunction parser) {
        SeqSet sq;
        parser(filename, sq);
        window = newwin(_height, _width, upperleftY, upperleftX);
        width = _width + 1;
        height = _height + 1;
        seqs = sq;
        scrollmode = 1;
        display_mode = NORMAL;
        names_width = 15;
        first_pos = 0;
        first_seq = 0;
        update_size();
        _recalculate_num_displayed();
        bolded = true;
        modified = true;
        compare = false;
        display();
    }

    SeqWindow::~SeqWindow() {
        wattron(window, COLOR_PAIR(8));
        for(int i = 0; i < height; i++) {
            mvwprintw(window, i, 0, string(width, ' ').c_str());
        }
        wattroff(window, COLOR_PAIR(8));
        wrefresh(window);
        delwin(window);
    }

    void SeqWindow::set_focus(bool focal) {
        isfocal = focal;
        modified = true;
    }

    // scroll mode is in powers of 10
    void SeqWindow::set_scroll_mode(int mode) {
        if(mode < 0 || mode > 9)
            return;
        scrollmode = pow(10, mode);
    }

    void SeqWindow::update_size() {
        getmaxyx(window, height, width);
        height += 1;
        width += 1;
    }

    void SeqWindow::change_name_width(int newwidth) {
        if(newwidth < width - 5  && newwidth > 1) {
            names_width = newwidth;
            update_size();
            _recalculate_num_displayed();
        }
    }

    // Deal with commands that change SeqSet params
    void SeqWindow::handle_command(Command command) {
        Com com_name = command.first;
        int param = command.second;
        int newpos;
        if(com_name == SCROLLUP) {
            if(first_seq > 0) {
                newpos = first_seq - param;
                if(newpos < 0)
                    newpos = 0;
                _scroll(first_pos, newpos);
            }
        } else if(com_name == SCROLLDOWN) {
            if(first_seq < seqs.numseqs()) {
                newpos = first_seq + param;
                if(newpos >= seqs.numseqs())
                    newpos = seqs.numseqs() - 1;
                _scroll(first_pos, newpos);
            }
        } else if(com_name == SCROLLLEFT) {
            if(first_pos > 0) {
                newpos = first_pos - scrollmode * param;
                if(newpos < 0)
                    newpos = 0;
                _scroll(newpos, first_seq);
            }
        } else if(com_name == SCROLLRIGHT) {
            if(first_pos < seqs.length()) {
                newpos = first_pos + scrollmode * param;
                if(newpos >= seqs.length())
                    newpos = seqs.length() - 1;
                _scroll(newpos, first_seq);
            }
        } else if(com_name == SCROLLTOP) {
            _scroll(first_pos, 0);
        } else if(com_name == SCROLLBOTTOM) {
            _scroll(first_pos, seqs.numseqs() - 1);
        } else if(com_name == GOTOBEGIN) {
            _scroll(0, first_seq);
        } else if(com_name == GOTOEND) {
            _scroll(seqs.length() - 1, first_seq);
        } else if(com_name == GOTO) {
            newpos = param - 1 - (width - names_width) / 2;
            if(display_mode == CODON)
                newpos += (width - names_width) / 6;
            if(newpos < 0)
                newpos = 0;
            if(newpos > seqs.length() - 1)
                newpos = seqs.length() - 1;
            _scroll(newpos, first_seq);
        } else if(com_name == SCROLLMODE) {
            set_scroll_mode(param);
        } else if(com_name == NAMEWIDTH) {
            change_name_width(param);
        } else if(com_name == DISPLAYMODE) {
            if(param == 1)
                display_mode = NORMAL;
            else if(param == 2)
                display_mode = CODON;
            modified = true;
        } else if(com_name == SETFRAME) {
            seqs.set_frame(param);
            modified = true;
        } else if(com_name == COMPARE) {
            compare = !compare;
            modified = true;
        } else if(com_name == TOGGLEBOLD) {
            bolded = !bolded;
            modified = true;
        }
    }

    void SeqWindow::resize(int upperleftX, int upperleftY,
            int newwidth, int newheight) {
        wattron(window, COLOR_PAIR(8));
        for(int i = 0; i < height; i++) {
            mvwprintw(window, i, 0, string(width, ' ').c_str());
        }
        wrefresh(window);
        delwin(window);
        window = newwin(newheight, newwidth,
                upperleftY, upperleftX);
        height = newheight;
        width = newwidth;
        update_size();
        _recalculate_num_displayed();
        modified = true;
        display();
    }

    // Refresh, get the slice of the sequence, add the formatting,
    // and use wprintw to put everything on the screen.
    void SeqWindow::display() {
        int w = width;
        int h = height;
        update_size();
        if(w != width || h != height)
            modified = true;
        if(modified) {
            _recalculate_num_displayed();
            _display_names();
            _display_positions();
            _display_seqs();
            _display_filename();
            wrefresh(window);
        } else {
        }
    }
}
<|endoftext|>


<commit_before>//#include <fstream>
//#include <TFile.h>
//#include <TSystem.h>

/*

  Process all jobs specified in the job.list file
  Concurent agents acces the list
  Once starting to procces given job the jonb is locked

*/

/*

.L $ALICE_ROOT/TPC/macros/testTPC/AliTPCjobs.cxx+

AliTPCJobs jobs;
jobs.fJobFile="job.list"
jobs.ProcessAllJobs();
*/

class AliTPCJobs : public TNamed{
public:
  AliTPCJobs();
  void ProcessAllJobs();
  Bool_t GetNextJob();
  void ProcessJob(TString jobID, TString inputData, TString outputDir, TString   action);

  void    SetLock(TString jobID);
  void    SetDone(TString jobID);
  void    SetFail(TString jobID);

  Int_t   Stage(TString inputData,TString jobID);

  Bool_t  IsLocked(TString jobID);
  Bool_t  IsFail(TString jobID);
  Bool_t  IsStaged(TString inputData);
  Bool_t  IsCastorFile(TString filename);

  TString  fJobFile;
  TString  fWorkDir;
  ClassDef(AliTPCJobs,0)
};

 ClassImp(AliTPCJobs)

AliTPCJobs::AliTPCJobs(){
  //
  //
  //
  gSystem->Load("libXrdClient.so");
  gSystem->Load("libNetx.so");
}

void AliTPCJobs::ProcessAllJobs(){
  //
  //
  //
  Int_t counter=0;
  while (GetNextJob()){
    //
    printf("PROCESSING JOB\t%d\n",counter);
    counter++;
    if (!GetNextJob()) break;
  }
}

Bool_t AliTPCJobs::GetNextJob(){
  //
  // GetNextJob  - get job from the list which is not locked
  //
  ifstream ins;
  ins.open(fJobFile);
  TString id;
  TString inputData;
  TString outputDir;
  TString action;
  Bool_t hasJob=kFALSE;
  while(ins.good()) {
    ins>>id;
    ins>>inputData;
    ins>>outputDir;
    ins>>action;
    if (!inputData.Contains(".root")) SetFail(id);
    if (!IsStaged(inputData)){
	Stage(inputData,id);
	continue;
    }
    if (IsFail(id)) continue;
    if (!IsLocked(id)){
      hasJob=kTRUE;
      break;
    }
  }
  printf("Process %s\n",id.Data());
  if (hasJob) ProcessJob(id,inputData,outputDir, action);
  return hasJob;
}

void    AliTPCJobs::SetLock(TString jobID){
  printf("touch out/%s.lock\n",jobID.Data());
  gSystem->Exec(Form("touch out/%s.lock",jobID.Data()));
}

void    AliTPCJobs::SetDone(TString jobID){
  printf("touch out/%s.done\n",jobID.Data());
  gSystem->Exec(Form("touch out/%s.done", jobID.Data()));
}

void    AliTPCJobs::SetFail(TString jobID){
  printf("touch out/%s.fail\n",jobID.Data());
  gSystem->Exec(Form("touch out/%s.fail", jobID.Data()));
}

void  AliTPCJobs::Stage(TString inputData, TString jobID){
  //
  // stage file
  //
  inputData.ReplaceAll("root://voalice04.cern.ch:1094/","");
  if ( !IsCastorFile(inputData) ) return;
  char command[1000];
  sprintf(command,"stager_get -M %s \| grep SUBREQUEST_FAILED ",inputData.Data());
  FILE *pipe = gSystem->OpenPipe(command,"r");
  TString result;
  result.Gets(pipe);
  gSystem->ClosePipe(pipe);
  if ( result.Contains("SUBREQUEST_FAILED") ){
      SetFail(jobID);
  }
}

Bool_t    AliTPCJobs::IsLocked(TString jobID){
  TString path = "out/";
  path+=jobID;
  path+=".lock";
  Long_t pid; Long_t psize; Long_t pflags; Long_t pmodtime;
  Int_t status = gSystem->GetPathInfo(path,&pid,&psize,&pflags,&pmodtime);
  return (status==0);
}

Bool_t    AliTPCJobs::IsFail(TString jobID){
  TString path = "out/";
  path+=jobID;
  path+=".fail";
  Long_t pid; Long_t psize; Long_t pflags; Long_t pmodtime;
  Int_t status = gSystem->GetPathInfo(path,&pid,&psize,&pflags,&pmodtime);
  return (status==0);
}

Bool_t  AliTPCJobs::IsStaged(TString inputData){
  //
  // check if file bname is staged
  //
  inputData.ReplaceAll("root://voalice04.cern.ch:1094/","");
  if ( !IsCastorFile(inputData) ) return kTRUE;
  char command[1000];
  sprintf(command,"stager_qry -M %s \| grep /castor \| gawk  \'{ print $3;}\'",inputData.Data());
  FILE *pipe = gSystem->OpenPipe(command,"r");
  TString result;
  result.Gets(pipe);
  gSystem->ClosePipe(pipe);
  if ( result.Contains("STAGED") ) return kTRUE;

  return kFALSE;
}

Bool_t  AliTPCJobs::IsCastorFile(TString filename){
  //
  // check if filename begins with 'castor'
  //
  return filename.BeginsWith("/castor/");
}

void AliTPCJobs::ProcessJob(TString jobID, TString inputData, TString outputDir, TString   action){
  //
  //
  // 1. Create lock file
  // 2. Get Input data
  // 3. Process data
  // 4. Create Done file
  SetLock(jobID);
  if (action.Contains("COPY")){
    char command[10000];
      sprintf(command,"xrdcp  -DIFirstConnectMaxCnt 4 -DIConnectTimeout 4 -DIRequestTimeout 4 -DIMaxRedirectcount 4 -DIRedirCntTimeout 4 %s\t%s\n",inputData.Data(), outputDir.Data());
    printf("Exec\t%s\n", command);
    gSystem->Exec(command);
    //TFile::Cp(inputData.Data(), outputDir.Data());
  }else{
    char command[10000];
    //sprintf(command,"$ALICE_ROOT/TPC/macros/testTPC/action.sh %s %s %s %s", jobID.Data(), inputData.Data(), outputDir.Data(), action.Data());
    sprintf(command,"/afs/cern.ch/user/w/wiechula/SOURCE/aliroot/job_agend/action.sh %s %s %s %s", jobID.Data(), inputData.Data(), outputDir.Data(), action.Data());
    printf("%s\n\n",command);
    gSystem->Exec(command);
    printf("\n\n");

    // create temp work dir
//    TString processDir=fWorkDir+jobID+action;
//    Int_t res = gSystem->mkdir(processDir,kTRUE);
//    if ( res==-1 ){
//	AliWarning(Form("Cannot create dir/already exists: '%s'",processDir.Data()));
//	return;
//    }
  }
  SetDone(jobID);
}

void AliTPCjobs(){
  //
  //
  //
  AliTPCJobs jobs;
  jobs.fJobFile="job.list";
  jobs.ProcessAllJobs();
}
<commit_msg>Don't call stage function (Marian)<commit_after>//#include <fstream>
//#include <TFile.h>
//#include <TSystem.h>

/*

  Process all jobs specified in the job.list file
  Concurent agents acces the list
  Once starting to procces given job the jonb is locked

*/

/*

.L $ALICE_ROOT/TPC/macros/testTPC/AliTPCjobs.cxx+

AliTPCJobs jobs;
jobs.fJobFile="job.list"
jobs.ProcessAllJobs();
*/

class AliTPCJobs : public TNamed{
public:
  AliTPCJobs();
  void ProcessAllJobs();
  Bool_t GetNextJob();
  void ProcessJob(TString jobID, TString inputData, TString outputDir, TString   action);

  void    SetLock(TString jobID);
  void    SetDone(TString jobID);
  void    SetFail(TString jobID);

  Int_t   Stage(TString inputData,TString jobID);

  Bool_t  IsLocked(TString jobID);
  Bool_t  IsFail(TString jobID);
  Bool_t  IsStaged(TString inputData);
  Bool_t  IsCastorFile(TString filename);

  TString  fJobFile;
  TString  fWorkDir;
  ClassDef(AliTPCJobs,0)
};

 ClassImp(AliTPCJobs)

AliTPCJobs::AliTPCJobs(){
  //
  //
  //
  gSystem->Load("libXrdClient.so");
  gSystem->Load("libNetx.so");
}

void AliTPCJobs::ProcessAllJobs(){
  //
  //
  //
  Int_t counter=0;
  while (GetNextJob()){
    //
    printf("PROCESSING JOB\t%d\n",counter);
    counter++;
    if (!GetNextJob()) break;
  }
}

Bool_t AliTPCJobs::GetNextJob(){
  //
  // GetNextJob  - get job from the list which is not locked
  //
  ifstream ins;
  ins.open(fJobFile);
  TString id;
  TString inputData;
  TString outputDir;
  TString action;
  Bool_t hasJob=kFALSE;
  while(ins.good()) {
    ins>>id;
    ins>>inputData;
    ins>>outputDir;
    ins>>action;
    if (!inputData.Contains(".root")) SetFail(id);
    if (IsFail(id)) continue;
    if (!IsLocked(id)){
      hasJob=kTRUE;
      break;
    }
    if (!IsStaged(inputData)){
      //Stage(inputData,id);
      continue;
    }
  }
  printf("Process %s\n",id.Data());
  if (hasJob) ProcessJob(id,inputData,outputDir, action);
  return hasJob;
}

void    AliTPCJobs::SetLock(TString jobID){
  printf("touch out/%s.lock\n",jobID.Data());
  gSystem->Exec(Form("touch out/%s.lock",jobID.Data()));
}

void    AliTPCJobs::SetDone(TString jobID){
  printf("touch out/%s.done\n",jobID.Data());
  gSystem->Exec(Form("touch out/%s.done", jobID.Data()));
}

void    AliTPCJobs::SetFail(TString jobID){
  printf("touch out/%s.fail\n",jobID.Data());
  gSystem->Exec(Form("touch out/%s.fail", jobID.Data()));
}

void  AliTPCJobs::Stage(TString inputData, TString jobID){
  //
  // stage file
  //
  inputData.ReplaceAll("root://voalice04.cern.ch:1094/","");
  if ( !IsCastorFile(inputData) ) return;
  char command[1000];
  sprintf(command,"stager_get -M %s \| grep SUBREQUEST_FAILED ",inputData.Data());
  FILE *pipe = gSystem->OpenPipe(command,"r");
  TString result;
  result.Gets(pipe);
  gSystem->ClosePipe(pipe);
  if ( result.Contains("SUBREQUEST_FAILED") ){
      SetFail(jobID);
  }
}

Bool_t    AliTPCJobs::IsLocked(TString jobID){
  TString path = "out/";
  path+=jobID;
  path+=".lock";
  Long_t pid; Long_t psize; Long_t pflags; Long_t pmodtime;
  Int_t status = gSystem->GetPathInfo(path,&pid,&psize,&pflags,&pmodtime);
  return (status==0);
}

Bool_t    AliTPCJobs::IsFail(TString jobID){
  TString path = "out/";
  path+=jobID;
  path+=".fail";
  Long_t pid; Long_t psize; Long_t pflags; Long_t pmodtime;
  Int_t status = gSystem->GetPathInfo(path,&pid,&psize,&pflags,&pmodtime);
  return (status==0);
}

Bool_t  AliTPCJobs::IsStaged(TString inputData){
  //
  // check if file bname is staged
  //
  inputData.ReplaceAll("root://voalice04.cern.ch:1094/","");
  if ( !IsCastorFile(inputData) ) return kTRUE;
  char command[1000];
  sprintf(command,"stager_qry -M %s \| grep /castor \| gawk  \'{ print $3;}\'",inputData.Data());
  FILE *pipe = gSystem->OpenPipe(command,"r");
  TString result;
  result.Gets(pipe);
  gSystem->ClosePipe(pipe);
  if ( result.Contains("STAGED") ) return kTRUE;

  return kFALSE;
}

Bool_t  AliTPCJobs::IsCastorFile(TString filename){
  //
  // check if filename begins with 'castor'
  //
  return filename.BeginsWith("/castor/");
}

void AliTPCJobs::ProcessJob(TString jobID, TString inputData, TString outputDir, TString   action){
  //
  //
  // 1. Create lock file
  // 2. Get Input data
  // 3. Process data
  // 4. Create Done file
  SetLock(jobID);
  if (action.Contains("COPY")){
    char command[10000];
      sprintf(command,"xrdcp  -DIFirstConnectMaxCnt 4 -DIConnectTimeout 4 -DIRequestTimeout 4 -DIMaxRedirectcount 4 -DIRedirCntTimeout 4 %s\t%s\n",inputData.Data(), outputDir.Data());
    printf("Exec\t%s\n", command);
    gSystem->Exec(command);
    //TFile::Cp(inputData.Data(), outputDir.Data());
  }else{
    char command[10000];
    sprintf(command,"$ALICE_ROOT/TPC/macros/testTPC/action.sh %s %s %s %s", jobID.Data(), inputData.Data(), outputDir.Data(), action.Data());
    printf("%s\n\n",command);
    gSystem->Exec(command);
    printf("\n\n");

    // create temp work dir
//    TString processDir=fWorkDir+jobID+action;
//    Int_t res = gSystem->mkdir(processDir,kTRUE);
//    if ( res==-1 ){
//	AliWarning(Form("Cannot create dir/already exists: '%s'",processDir.Data()));
//	return;
//    }
  }
  SetDone(jobID);
}

void AliTPCjobs(){
  //
  //
  //
  AliTPCJobs jobs;
  jobs.fJobFile="job.list";
  jobs.ProcessAllJobs();
}
<|endoftext|>


<commit_before>//
// Name: NodeDlg.cpp
//
// Copyright (c) 2002-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "NodeDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
	#pragma hdrstop
#endif

#include "NodeDlg.h"
#include "RoadLayer.h"
#include "Frame.h"
#include "BuilderView.h"

#define MULTIPLE	5000

static wxPoint buf[10];

void NodeDlgView::OnDraw(wxDC &dc)
{
	if (!m_pNode)
		return;

	wxPoint center;
	screen(m_pNode->m_p, center);
	m_pNode->Draw(&dc, this);

	wxString string;
	for (int i = 0; i < m_pNode->m_iLinks; i++)
	{
		LinkEdit *pR = m_pNode->GetLink(i);
		pR->Draw(&dc, this);

		//we need to use the original node here because the roads point to it.
		DPoint2 close = m_pNode->GetAdjacentLinkPoint2d(i);
		DPoint2 vector = close - m_pNode->m_p;
		vector.Normalize();
		IPoint2 vec;

		vec.x = (int)(center.x + vector.x*20);
		vec.y = (int)(center.y - vector.y*20);

		//draw signal lights or stop signs as necessary.
		dc.SetLogicalFunction(wxCOPY);
		wxPen pen;

		switch (m_pNode->GetIntersectType(i))
		{
		case IT_STOPSIGN:
			pen.SetColour(128,0,0);
			dc.SetPen(pen);
			vec.x += 2;
			vec.y += 6;
			buf[0].x = vec.x; buf[0].y = vec.y;
			vec.x -= 4;
			buf[1].x = vec.x; buf[1].y = vec.y;
			vec.x -= 3;
			vec.y -= 3;
			buf[2].x = vec.x; buf[2].y = vec.y;
			vec.y -= 4;
			buf[3].x = vec.x; buf[3].y = vec.y;
			vec.x += 3;
			vec.y -= 3;
			buf[4].x = vec.x; buf[4].y = vec.y;
			vec.x += 4;
			buf[5].x = vec.x; buf[5].y = vec.y;
			vec.x += 3;
			vec.y += 3;
			buf[6].x = vec.x; buf[6].y = vec.y;
			vec.y += 4;
			buf[7].x = vec.x; buf[7].y = vec.y;
			vec.x -= 3;
			vec.y += 3;
			buf[8].x = vec.x; buf[8].y = vec.y;
			dc.DrawLines(9, buf);
			break;
		case IT_LIGHT:
			wxBrush brush;
			switch (m_pNode->GetLightStatus(i))
			{
			case LT_INVALID:
				pen.SetColour(0,0,0);
				brush.SetColour(0,0,0);
				break;
			case LT_RED:
				pen.SetColour(128,0,0);
				brush.SetColour(128,0,0);
				break;
			case LT_YELLOW:
				pen.SetColour(0,128,128);
				brush.SetColour(0,128,128);
				break;
			case LT_GREEN:
				pen.SetColour(0,128,0);
				brush.SetColour(0,128,0);
				break;
			default:
				//unrecognized
				pen.SetColour(0,0,255);
				brush.SetColour(0,0,255);
				break;
			}

			dc.SetPen(pen);
			dc.SetBrush(brush);
			wxRect box;
			int radius = 4;
			box.y = vec.y - radius;
			box.height = (radius << 1);
			box.x = vec.x - radius;
			box.width = (radius << 1);
			dc.DrawEllipse(box.x, box.y, box.width, box.height);
			break;
		}

		//draw text labels
		vec.x = (int)(center.x + vector.x*40);
		vec.y = (int)(center.y - vector.y*40);
		string.Printf(_T("%i"), i);
		dc.DrawText(string, vec.x-10, vec.y-10);
	}
}

// WDR: class implementations

//----------------------------------------------------------------------------
// NodeDlg
//----------------------------------------------------------------------------

// WDR: event table for NodeDlg

BEGIN_EVENT_TABLE(NodeDlg, AutoDialog)
	EVT_INIT_DIALOG (NodeDlg::OnInitDialog)
	EVT_LISTBOX( ID_INTTYPE, NodeDlg::OnIntType )
	EVT_LISTBOX( ID_ROADNUM, NodeDlg::OnLinkNum )
	EVT_LISTBOX( ID_BEHAVIOR, NodeDlg::OnBehavior )
END_EVENT_TABLE()

NodeDlg::NodeDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	NodePropDialogFunc( this, TRUE );

	GetIntType()->Append(_("Unknown"));
	GetIntType()->Append(_("Uncontrolled"));
	GetIntType()->Append(_("All Traffic Light(s)"));
	GetIntType()->Append(_("All Stop Sign(s)"));
	GetIntType()->Append(_("Traffic Light(s)"));
	GetIntType()->Append(_("Stop Sign(s)"));
	GetIntType()->Append(_("(multiple)"));

	GetBehavior()->Append(_("Uncontrolled"));	// IT_NONE
	GetBehavior()->Append(_("Traffic Light"));	// IT_LIGHT
	GetBehavior()->Append(_("Stop Sign"));		// IT_STOPSIGN

	m_pView = (NodeDlgView *) FindWindow( ID_SCROLLED );

	vtScaledView *pMainView = GetMainFrame()->GetView();
	float fScale = pMainView->GetScale();
	m_pView->SetScale(fScale);
}

void NodeDlg::SetNode(NodeEdit *pSingleNode, vtRoadLayer *pLayer)
{
	m_pNode = pSingleNode;
	m_pLayer = pLayer;
	m_pView->m_pNode = m_pNode;
	if (NULL != m_pNode)
		m_pView->ZoomToPoint(m_pNode->m_p);
}

// WDR: handler implementations for NodeDlg

void NodeDlg::OnBehavior( wxCommandEvent &event )
{
	int sel = GetLinkNum()->GetSelection();
	//select new behavior and redraw it on the dialog.
	int itype = GetBehavior()->GetSelection();
	m_pNode->SetIntersectType(sel, (IntersectionType)itype );

	// this may have changed the VIT, so check
	m_pNode->DetermineVisualFromLinks();
	GetIntType()->SetSelection(m_pNode->GetVisual());

	Refresh();
}

void NodeDlg::OnLinkNum( wxCommandEvent &event )
{
	int sel = GetLinkNum()->GetSelection();
	//update what the behavior shows to match that of the road
	GetBehavior()->SetSelection(m_pNode->GetIntersectType(sel));
}

void NodeDlg::OnIntType( wxCommandEvent &event )
{
	//new node behavior
	VisualIntersectionType vitype;
	int sel = GetIntType()->GetSelection();
	if (sel == 0 || sel == 6)	// unknown or multiple not allowed
		return;

	vitype = (VisualIntersectionType) sel;

	if (m_pNode)
		ApplyVisualToNode(m_pNode, vitype);
	else
	{
		for (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())
		{
			if (!n->IsSelected())
				continue;
			ApplyVisualToNode(n, vitype);
		}
	}
	Refresh();
}

void NodeDlg::ApplyVisualToNode(NodeEdit *pNode, VisualIntersectionType vitype)
{
	int i;

	pNode->SetVisual(vitype);

	//overwrite all behaviors at the roads to match new assigned node behavior.
	switch (vitype)
	{
	case VIT_NONE:
		//make all intersections uncontrolled
		for (i = 0; i < pNode->m_iLinks; i++) {
			pNode->SetIntersectType(i, IT_NONE);
		}
		GetBehavior()->SetSelection(IT_NONE);
		break;
	case VIT_ALLSTOPS:
		//make all intersections stop signs
		for (i = 0; i < pNode->m_iLinks; i++) {
			pNode->SetIntersectType(i, IT_STOPSIGN);
		}
		GetBehavior()->SetSelection(IT_STOPSIGN);
		break;
	case VIT_ALLLIGHTS:
		//make all intersections lights
		for (i = 0; i < pNode->m_iLinks; i++) {
			pNode->SetIntersectType(i, IT_LIGHT);
		}
		GetBehavior()->SetSelection(IT_LIGHT);
		pNode->AdjustForLights();
		break;
	}
}

void NodeDlg::OnInitDialog(wxInitDialogEvent& event)
{
	// if we are editing multiple nodes at once, disable some of the
	// editing abilities
	if (!m_pNode)
	{
		GetLinkNum()->Enable(false);
		GetBehavior()->Enable(false);

		// Accumulate state
		int viz = -1;
		for (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())
		{
			if (!n->IsSelected())
				continue;
			if (viz == -1)
				viz = n->GetVisual();
			if (n->GetVisual() != viz)
				viz = MULTIPLE;
		}

		// Transfer state to control
		if (viz == MULTIPLE)
			GetIntType()->SetSelection(6);
		else
			GetIntType()->SetSelection(viz);
	}
	else
	{
		// single road
		wxString string;
		for (int i = 0; i < m_pNode->m_iLinks; i++)
		{
			string.Printf(_T("%i"), i);
			GetLinkNum()->Append(string);
		}
		GetLinkNum()->SetSelection(0);
		GetIntType()->SetSelection(m_pNode->GetVisual());
		int itype = m_pNode->GetIntersectType(0);
		GetBehavior()->SetSelection(itype);
	}
}

<commit_msg>safety check<commit_after>//
// Name: NodeDlg.cpp
//
// Copyright (c) 2002-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "NodeDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
	#pragma hdrstop
#endif

#include "NodeDlg.h"
#include "RoadLayer.h"
#include "Frame.h"
#include "BuilderView.h"

#define MULTIPLE	5000

static wxPoint buf[10];

void NodeDlgView::OnDraw(wxDC &dc)
{
	if (!m_pNode)
		return;

	wxPoint center;
	screen(m_pNode->m_p, center);
	m_pNode->Draw(&dc, this);

	wxString string;
	for (int i = 0; i < m_pNode->m_iLinks; i++)
	{
		LinkEdit *pR = m_pNode->GetLink(i);
		pR->Draw(&dc, this);

		//we need to use the original node here because the roads point to it.
		DPoint2 close = m_pNode->GetAdjacentLinkPoint2d(i);
		DPoint2 vector = close - m_pNode->m_p;
		vector.Normalize();
		IPoint2 vec;

		vec.x = (int)(center.x + vector.x*20);
		vec.y = (int)(center.y - vector.y*20);

		//draw signal lights or stop signs as necessary.
		dc.SetLogicalFunction(wxCOPY);
		wxPen pen;

		switch (m_pNode->GetIntersectType(i))
		{
		case IT_STOPSIGN:
			pen.SetColour(128,0,0);
			dc.SetPen(pen);
			vec.x += 2;
			vec.y += 6;
			buf[0].x = vec.x; buf[0].y = vec.y;
			vec.x -= 4;
			buf[1].x = vec.x; buf[1].y = vec.y;
			vec.x -= 3;
			vec.y -= 3;
			buf[2].x = vec.x; buf[2].y = vec.y;
			vec.y -= 4;
			buf[3].x = vec.x; buf[3].y = vec.y;
			vec.x += 3;
			vec.y -= 3;
			buf[4].x = vec.x; buf[4].y = vec.y;
			vec.x += 4;
			buf[5].x = vec.x; buf[5].y = vec.y;
			vec.x += 3;
			vec.y += 3;
			buf[6].x = vec.x; buf[6].y = vec.y;
			vec.y += 4;
			buf[7].x = vec.x; buf[7].y = vec.y;
			vec.x -= 3;
			vec.y += 3;
			buf[8].x = vec.x; buf[8].y = vec.y;
			dc.DrawLines(9, buf);
			break;
		case IT_LIGHT:
			wxBrush brush;
			switch (m_pNode->GetLightStatus(i))
			{
			case LT_INVALID:
				pen.SetColour(0,0,0);
				brush.SetColour(0,0,0);
				break;
			case LT_RED:
				pen.SetColour(128,0,0);
				brush.SetColour(128,0,0);
				break;
			case LT_YELLOW:
				pen.SetColour(0,128,128);
				brush.SetColour(0,128,128);
				break;
			case LT_GREEN:
				pen.SetColour(0,128,0);
				brush.SetColour(0,128,0);
				break;
			default:
				//unrecognized
				pen.SetColour(0,0,255);
				brush.SetColour(0,0,255);
				break;
			}

			dc.SetPen(pen);
			dc.SetBrush(brush);
			wxRect box;
			int radius = 4;
			box.y = vec.y - radius;
			box.height = (radius << 1);
			box.x = vec.x - radius;
			box.width = (radius << 1);
			dc.DrawEllipse(box.x, box.y, box.width, box.height);
			break;
		}

		//draw text labels
		vec.x = (int)(center.x + vector.x*40);
		vec.y = (int)(center.y - vector.y*40);
		string.Printf(_T("%i"), i);
		dc.DrawText(string, vec.x-10, vec.y-10);
	}
}

// WDR: class implementations

//----------------------------------------------------------------------------
// NodeDlg
//----------------------------------------------------------------------------

// WDR: event table for NodeDlg

BEGIN_EVENT_TABLE(NodeDlg, AutoDialog)
	EVT_INIT_DIALOG (NodeDlg::OnInitDialog)
	EVT_LISTBOX( ID_INTTYPE, NodeDlg::OnIntType )
	EVT_LISTBOX( ID_ROADNUM, NodeDlg::OnLinkNum )
	EVT_LISTBOX( ID_BEHAVIOR, NodeDlg::OnBehavior )
END_EVENT_TABLE()

NodeDlg::NodeDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	NodePropDialogFunc( this, TRUE );

	GetIntType()->Append(_("Unknown"));
	GetIntType()->Append(_("Uncontrolled"));
	GetIntType()->Append(_("All Traffic Light(s)"));
	GetIntType()->Append(_("All Stop Sign(s)"));
	GetIntType()->Append(_("Traffic Light(s)"));
	GetIntType()->Append(_("Stop Sign(s)"));
	GetIntType()->Append(_("(multiple)"));

	GetBehavior()->Append(_("Uncontrolled"));	// IT_NONE
	GetBehavior()->Append(_("Traffic Light"));	// IT_LIGHT
	GetBehavior()->Append(_("Stop Sign"));		// IT_STOPSIGN

	m_pView = (NodeDlgView *) FindWindow( ID_SCROLLED );

	vtScaledView *pMainView = GetMainFrame()->GetView();
	float fScale = pMainView->GetScale();
	m_pView->SetScale(fScale);
}

void NodeDlg::SetNode(NodeEdit *pSingleNode, vtRoadLayer *pLayer)
{
	m_pNode = pSingleNode;
	m_pLayer = pLayer;
	m_pView->m_pNode = m_pNode;
	if (NULL != m_pNode)
		m_pView->ZoomToPoint(m_pNode->m_p);
}

// WDR: handler implementations for NodeDlg

void NodeDlg::OnBehavior( wxCommandEvent &event )
{
	int sel = GetLinkNum()->GetSelection();
	//select new behavior and redraw it on the dialog.
	int itype = GetBehavior()->GetSelection();
	m_pNode->SetIntersectType(sel, (IntersectionType)itype );

	// this may have changed the VIT, so check
	m_pNode->DetermineVisualFromLinks();
	GetIntType()->SetSelection(m_pNode->GetVisual());

	Refresh();
}

void NodeDlg::OnLinkNum( wxCommandEvent &event )
{
	int sel = GetLinkNum()->GetSelection();
	//update what the behavior shows to match that of the road
	GetBehavior()->SetSelection(m_pNode->GetIntersectType(sel));
}

void NodeDlg::OnIntType( wxCommandEvent &event )
{
	//new node behavior
	VisualIntersectionType vitype;
	int sel = GetIntType()->GetSelection();
	if (sel == 0 || sel == 6)	// unknown or multiple not allowed
		return;

	vitype = (VisualIntersectionType) sel;

	if (m_pNode)
		ApplyVisualToNode(m_pNode, vitype);
	else
	{
		for (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())
		{
			if (!n->IsSelected())
				continue;
			ApplyVisualToNode(n, vitype);
		}
	}
	Refresh();
}

void NodeDlg::ApplyVisualToNode(NodeEdit *pNode, VisualIntersectionType vitype)
{
	int i;

	pNode->SetVisual(vitype);

	//overwrite all behaviors at the roads to match new assigned node behavior.
	switch (vitype)
	{
	case VIT_NONE:
		//make all intersections uncontrolled
		for (i = 0; i < pNode->m_iLinks; i++) {
			pNode->SetIntersectType(i, IT_NONE);
		}
		GetBehavior()->SetSelection(IT_NONE);
		break;
	case VIT_ALLSTOPS:
		//make all intersections stop signs
		for (i = 0; i < pNode->m_iLinks; i++) {
			pNode->SetIntersectType(i, IT_STOPSIGN);
		}
		GetBehavior()->SetSelection(IT_STOPSIGN);
		break;
	case VIT_ALLLIGHTS:
		//make all intersections lights
		for (i = 0; i < pNode->m_iLinks; i++) {
			pNode->SetIntersectType(i, IT_LIGHT);
		}
		GetBehavior()->SetSelection(IT_LIGHT);
		pNode->AdjustForLights();
		break;
	}
}

void NodeDlg::OnInitDialog(wxInitDialogEvent& event)
{
	// if we are editing multiple nodes at once, disable some of the
	// editing abilities
	if (!m_pNode)
	{
		GetLinkNum()->Enable(false);
		GetBehavior()->Enable(false);

		// Accumulate state
		int viz = -1;
		for (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())
		{
			if (!n->IsSelected())
				continue;
			if (viz == -1)
				viz = n->GetVisual();
			if (n->GetVisual() != viz)
				viz = MULTIPLE;
		}

		// Transfer state to control
		if (viz == MULTIPLE)
			GetIntType()->SetSelection(6);
		else
			GetIntType()->SetSelection(viz);
	}
	else
	{
		// single road
		wxString string;
		for (int i = 0; i < m_pNode->m_iLinks; i++)
		{
			string.Printf(_T("%i"), i);
			GetLinkNum()->Append(string);
		}
		if (m_pNode->m_iLinks > 0)
			GetLinkNum()->SetSelection(0);
		GetIntType()->SetSelection(m_pNode->GetVisual());
		int itype = m_pNode->GetIntersectType(0);
		GetBehavior()->SetSelection(itype);
	}
}

<|endoftext|>


<commit_before>#include <igloo/igloo_alt.h>
#include <Landmarks.hh>

namespace	Landmark_Result
{
  int		id = -1;
  int		life = LIFE;
  int		totalTimesObserved = 0;
  double	range = -1;
  double	bearing = -1;
  double	pos[2] = {0.0, 0.0};
};

namespace	Landmarks_Result
{
  int		DBSize = 0;
  int		EKFLandmarks = 0;
  double	defaultdegreePerScan = DEGREESPERSCAN;
  double	degreePerScan = 0.42;
  int		sizeIDtoID = MAXLANDMARKS;
  int		sizelandmarkDB = MAXLANDMARKS;
};

using namespace igloo;

When(creating_a_landmark)
{
  Then(it_should_have_default_value)
    {
      Assert::That(lm.id, Is().EqualTo(::Landmark_Result::id));
      Assert::That(lm.life, Is().EqualTo(::Landmark_Result::life));
      Assert::That(lm.totalTimeObserved, Is().EqualTo(::Landmark_Result::totalTimesObserved));
      Assert::That(lm.range, Is().EqualTo(::Landmark_Result::range));
      Assert::That(lm.bearing, Is().EqualTo(::Landmark_Result::bearing));
      Assert::That(lm.pos[0], Is().EqualTo(::Landmark_Result::pos[0]));
      Assert::That(lm.pos[1], Is().EqualTo(::Landmark_Result::pos[1]));
    }

  ::Landmarks::Landmark	lm;
};

When(creating_Landmarks)
{
  Then(it_should_have_default_landmarks_value)
  {
    Assert::That(lms.DBSize, Is().EqualTo(::Landmarks_Result::DBSize));
    Assert::That(lms.EKFLandmarks, Is().EqualTo(::Landmarks_Result::EKFLandmarks));
    Assert::That(lms.degreePerScan, Is().EqualTo(::Landmarks_Result::defaultdegreePerScan));
    Assert::That(lms.IDtoID.capacity(), Is().EqualTo(::Landmarks_Result::sizeIDtoID));
    Assert::That(lms.landmarkDB.capacity(), Is().EqualTo(::Landmarks_Result::sizelandmarkDB));
  }

  Landmarks lms;
};

When(creating_Landmarks_with_a_specific_degree_value_different_from_default)
{
  void SetUp()
  {
    lms = new ::Landmarks(::Landmarks_Result::degreePerScan);
  }

  Then(it_should_not_have_default_degree_value)
  {
    Assert::That(lms->degreePerScan, Is().Not().EqualTo(::Landmarks_Result::defaultdegreePerScan));
  }

  Then(it_should_have_this_specific_degree_value)
  {
    Assert::That(lms->degreePerScan, Is().EqualTo(::Landmarks_Result::degreePerScan));
  }

  void	TearDown()
  {
    delete lms;
  }

  Landmarks *lms;
};

<commit_msg>SLAM: Test: getDbSize()<commit_after>#include <igloo/igloo_alt.h>
#include <Landmarks.hh>

namespace	Landmark_Result
{
  int		id = -1;
  int		life = LIFE;
  int		totalTimesObserved = 0;
  double	range = -1;
  double	bearing = -1;
  double	pos[2] = {0.0, 0.0};
};

namespace	Landmarks_Result
{
  int		DBSize = 0;
  int		EKFLandmarks = 0;
  double	defaultdegreePerScan = DEGREESPERSCAN;
  double	degreePerScan = 0.42;
  int		sizeIDtoID = MAXLANDMARKS;
  int		sizelandmarkDB = MAXLANDMARKS;
};

using namespace igloo;

When(creating_a_landmark)
{
  Then(it_should_have_default_value)
    {
      Assert::That(lm.id, Is().EqualTo(::Landmark_Result::id));
      Assert::That(lm.life, Is().EqualTo(::Landmark_Result::life));
      Assert::That(lm.totalTimeObserved, Is().EqualTo(::Landmark_Result::totalTimesObserved));
      Assert::That(lm.range, Is().EqualTo(::Landmark_Result::range));
      Assert::That(lm.bearing, Is().EqualTo(::Landmark_Result::bearing));
      Assert::That(lm.pos[0], Is().EqualTo(::Landmark_Result::pos[0]));
      Assert::That(lm.pos[1], Is().EqualTo(::Landmark_Result::pos[1]));
    }

  ::Landmarks::Landmark	lm;
};

When(creating_Landmarks)
{
  Then(it_should_have_default_landmarks_value)
  {
    Assert::That(lms.DBSize, Is().EqualTo(::Landmarks_Result::DBSize));
    Assert::That(lms.EKFLandmarks, Is().EqualTo(::Landmarks_Result::EKFLandmarks));
    Assert::That(lms.degreePerScan, Is().EqualTo(::Landmarks_Result::defaultdegreePerScan));
    Assert::That(lms.IDtoID.capacity(), Is().EqualTo(::Landmarks_Result::sizeIDtoID));
    Assert::That(lms.landmarkDB.capacity(), Is().EqualTo(::Landmarks_Result::sizelandmarkDB));
  }

  Landmarks lms;
};

When(creating_Landmarks_with_a_specific_degree_value_different_from_default)
{
  void SetUp()
  {
    lms = new ::Landmarks(::Landmarks_Result::degreePerScan);
  }

  Then(it_should_not_have_default_degree_value)
  {
    Assert::That(lms->degreePerScan, Is().Not().EqualTo(::Landmarks_Result::defaultdegreePerScan));
  }

  Then(it_should_have_this_specific_degree_value)
  {
    Assert::That(lms->degreePerScan, Is().EqualTo(::Landmarks_Result::degreePerScan));
  }

  void	TearDown()
  {
    delete lms;
  }

  Landmarks *lms;
};

When(calling_getDBSize_after_construct)
{

  Then(it_should_be_equal_to_DBSize_value)
  {
    Assert::That(lms.getDBSize(), Is().EqualTo(lms.DBSize));
  }

  Landmarks lms;
};

When(calling_getDBSize_after_DBSize_changed)
{

  void	SetUp()
  {
    lms.DBSize += 1;
  }

  Then(it_should_be_equal_to_DBSize_value)
  {
    Assert::That(lms.getDBSize(), Is().EqualTo(lms.DBSize));
  }

  Landmarks lms;
};

<|endoftext|>