<commit_before>/**
 * @file
 * @author Jason Lingle
 * @brief Implementation of src/core/init_state.hxx
 */

#include <iostream>
#include <typeinfo>
#include <ctime>
#include <new>

#include <GL/gl.h>
#include <SDL.h>

#include <tcl.h>

#include "init_state.hxx"
#include "src/abendstern.hxx"
#include "src/globals.hxx"
#include "src/graphics/imgload.hxx"
#include "src/test_state.hxx"
#include "src/fasttrig.hxx"
#include "src/background/background_object.hxx"
#include "src/background/star_field.hxx"
#include "src/background/explosion_pool.hxx"
#include "src/ship/sys/system_textures.hxx"
#include "src/graphics/vec.hxx"
#include "src/graphics/mat.hxx"
#include "src/graphics/matops.hxx"
#include "src/graphics/shader.hxx"
#include "src/graphics/cmn_shaders.hxx"
#include "src/graphics/glhelp.hxx"
#include "src/graphics/gl32emu.hxx"
#include "src/graphics/font.hxx"
#include "src/graphics/asgi.hxx"
#include "src/audio/audio.hxx"
#include "src/secondary/namegen.hxx"
#include "src/tcl_iface/bridge.hxx"
#include "src/exit_conditions.hxx"

using namespace std;

#if defined(AB_OPENGL_14)
#define LOGO "images/a14.png"
#elif defined(AB_OPENGL_21)
#define LOGO "images/a21.png"
#else
#define LOGO "images/a.png"
#endif

#define PRELIM_LOGO "images/a.png"

//For LSD-mode Easter Egg
static bool hasPressedL=false, hasPressedS=false, hasPressedD=false;

InitState::InitState() {
  currStep = 0;
  currStepProgress = 0;

  static float (*const stepsToLoad[])() = {
    &InitState::miscLoader,
    &InitState::initFontLoader,
    &InitState::systexLoader,
    &InitState::starLoader,
    &InitState::backgroundLoader,
    &InitState::keyboardDelay,
  };
  steps = stepsToLoad;
  numSteps = lenof(stepsToLoad);

  hasPainted=headless;
  if (!headless) {
    if (!preliminaryRunMode)
      SDL_ShowCursor(SDL_DISABLE);
    glGenTextures(1, &logo);
    vao = newVAO();
    glBindVertexArray(vao);
    vbo = newVBO();
    const char* error=loadImage(preliminaryRunMode? PRELIM_LOGO : LOGO, logo);
    if (error) {
      cerr << error << endl;
      exit(EXIT_MALFORMED_DATA);
    }
    //We can't set the buffer up yet, because vheight
    //has not yet been calculated.
  }
}

InitState::~InitState() {
  if (!headless) {
    glDeleteTextures(1, &logo);
    glDeleteBuffers(1, &vbo);
    glDeleteVertexArrays(1, &vao);
  }
}

GameState* InitState::update(float) {
  if (!hasPainted && !headless) return NULL;

  if (currStep < numSteps) {
    currStepProgress = steps[currStep]();
    if (currStepProgress > 1.0f) {
      currStepProgress = 0;
      ++currStep;
    }
  } else {
    if (hasPressedL && hasPressedS && hasPressedD) {
      enableLSDMode();
      shader::textureReplace.unload();
      shader::basic.unload();
    }

    //Start the root interpreter
    Tcl_Interp* root=newInterpreter(false);
    if (TCL_ERROR == Tcl_EvalFile(root, "tcl/autoexec.tcl")) {
      cerr << "FATAL: Autoexec did not run successfully: " << Tcl_GetStringResult(root) << endl;
      Tcl_Obj* options=Tcl_GetReturnOptions(root, TCL_ERROR);
      Tcl_Obj* key=Tcl_NewStringObj("-errorinfo", -1);
      Tcl_Obj* stackTrace;
      Tcl_IncrRefCount(key);
      Tcl_DictObjGet(NULL, options, key, &stackTrace);
      Tcl_DecrRefCount(key);
      cerr << "Stack trace:\n" << Tcl_GetStringFromObj(stackTrace, NULL) << endl;
      exit(EXIT_SCRIPTING_BUG);
    }
    if (this == state) {
      cerr << "FATAL: Autoexec did not change GameState" << endl;
      exit(EXIT_SCRIPTING_BUG);
    }
    if (!headless) {
      SDL_EnableUNICODE(1);
      SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
      //Tcl is taking over in a somewhat rude way, so
      //handle as gracefully as possible
      state->configureGL();
    }
  }

  return NULL;
}

void InitState::draw() {
  hasPainted=true;

  const shader::textureReplaceV quad[4] = {
      { {{0.5f-vheight/2,0      ,0,1}}, {{0,1}} },
      { {{0.5f+vheight/2,0      ,0,1}}, {{1,1}} },
      { {{0.5f-vheight/2,vheight,0,1}}, {{0,0}} },
      { {{0.5f+vheight/2,vheight,0,1}}, {{1,0}} },
  };

  shader::textureReplaceU uni;
  uni.colourMap=0;

  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
  shader::textureReplace->setupVBO();
  glBindTexture(GL_TEXTURE_2D, logo);
  shader::textureReplace->activate(&uni);
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

  static const float progressH = 0.02f;
  static const float progressW = 0.3f;
  float currProgress = currStep/(float)numSteps + currStepProgress/numSteps;
  float baseX = 0.5f - progressW/2;
  #if defined(AB_OPENGL_14)
  asgi::colour(1.0f, 0.4f, 0.2f, 0.75f);
  #elif defined(AB_OPENGL_21)
  asgi::colour(0.2f, 1.0f, 0.4f, 0.75f);
  #else
  asgi::colour(0.2f, 0.3f, 0.9f, 0.75f);
  #endif
  asgi::begin(asgi::Quads);
  asgi::vertex(baseX, 4*progressH);
  asgi::vertex(baseX, 5*progressH);
  asgi::vertex(baseX + currProgress*progressW, 5*progressH);
  asgi::vertex(baseX + currProgress*progressW, 4*progressH);
  asgi::end();
  asgi::begin(asgi::Quads);
  asgi::vertex(baseX, 2.75f*progressH);
  asgi::vertex(baseX, 3.75f*progressH);
  asgi::vertex(baseX + currStepProgress*progressW, 3.75*progressH);
  asgi::vertex(baseX + currStepProgress*progressW, 2.75*progressH);
  asgi::end();
}

void InitState::keyboard(SDL_KeyboardEvent* e) {
  if (e->keysym.sym == SDLK_l)
    hasPressedL = true;
  else if (e->keysym.sym == SDLK_s)
    hasPressedS = true;
  else if (e->keysym.sym == SDLK_d)
    hasPressedD = true;
}

float InitState::miscLoader() {
  initTable(); //Trig tables
  sparkCountMultiplier=1;
  if (conf["conf"]["audio_enabled"]) audio::init();
  prepareTclBridge();
  namegenLoad();
  return 2;
}

float InitState::starLoader() {
  initStarLists();
  return 2;
}

float InitState::backgroundLoader() {
  if (!headless && !loadBackgroundObjects()) exit(EXIT_MALFORMED_DATA);
  return 2;
}

float InitState::systexLoader() {
  if (!headless)
    system_texture::load();
  return 2;
}

float InitState::initFontLoader() {
  float mult = (preliminaryRunMode? 2.0f : vheight);
  float size = conf["conf"]["hud"]["font_size"];
  new (sysfont)         Font("fonts/westm",   size*mult, false);
  new (sysfontStipple)  Font("fonts/westm",   size*mult, true );
  new (smallFont)       Font("fonts/unifont", size*mult/1.5f, false);
  new (smallFontStipple)Font("fonts/unifont", size*mult/1.5f, true );
  return 2;
}

//Delays for 500 ms to wait for keystrokes
float InitState::keyboardDelay() {
  if (preliminaryRunMode) return 2; //Don't wait

  static Uint32 start = SDL_GetTicks();
  Uint32 end = SDL_GetTicks();
  return (end-start)/512.0f;
}
<commit_msg>Don't increase font size for portrait-format screens.<commit_after>/**
 * @file
 * @author Jason Lingle
 * @brief Implementation of src/core/init_state.hxx
 */

#include <iostream>
#include <typeinfo>
#include <ctime>
#include <new>
#include <algorithm>

#include <GL/gl.h>
#include <SDL.h>

#include <tcl.h>

#include "init_state.hxx"
#include "src/abendstern.hxx"
#include "src/globals.hxx"
#include "src/graphics/imgload.hxx"
#include "src/test_state.hxx"
#include "src/fasttrig.hxx"
#include "src/background/background_object.hxx"
#include "src/background/star_field.hxx"
#include "src/background/explosion_pool.hxx"
#include "src/ship/sys/system_textures.hxx"
#include "src/graphics/vec.hxx"
#include "src/graphics/mat.hxx"
#include "src/graphics/matops.hxx"
#include "src/graphics/shader.hxx"
#include "src/graphics/cmn_shaders.hxx"
#include "src/graphics/glhelp.hxx"
#include "src/graphics/gl32emu.hxx"
#include "src/graphics/font.hxx"
#include "src/graphics/asgi.hxx"
#include "src/audio/audio.hxx"
#include "src/secondary/namegen.hxx"
#include "src/tcl_iface/bridge.hxx"
#include "src/exit_conditions.hxx"

using namespace std;

#if defined(AB_OPENGL_14)
#define LOGO "images/a14.png"
#elif defined(AB_OPENGL_21)
#define LOGO "images/a21.png"
#else
#define LOGO "images/a.png"
#endif

#define PRELIM_LOGO "images/a.png"

//For LSD-mode Easter Egg
static bool hasPressedL=false, hasPressedS=false, hasPressedD=false;

InitState::InitState() {
  currStep = 0;
  currStepProgress = 0;

  static float (*const stepsToLoad[])() = {
    &InitState::miscLoader,
    &InitState::initFontLoader,
    &InitState::systexLoader,
    &InitState::starLoader,
    &InitState::backgroundLoader,
    &InitState::keyboardDelay,
  };
  steps = stepsToLoad;
  numSteps = lenof(stepsToLoad);

  hasPainted=headless;
  if (!headless) {
    if (!preliminaryRunMode)
      SDL_ShowCursor(SDL_DISABLE);
    glGenTextures(1, &logo);
    vao = newVAO();
    glBindVertexArray(vao);
    vbo = newVBO();
    const char* error=loadImage(preliminaryRunMode? PRELIM_LOGO : LOGO, logo);
    if (error) {
      cerr << error << endl;
      exit(EXIT_MALFORMED_DATA);
    }
    //We can't set the buffer up yet, because vheight
    //has not yet been calculated.
  }
}

InitState::~InitState() {
  if (!headless) {
    glDeleteTextures(1, &logo);
    glDeleteBuffers(1, &vbo);
    glDeleteVertexArrays(1, &vao);
  }
}

GameState* InitState::update(float) {
  if (!hasPainted && !headless) return NULL;

  if (currStep < numSteps) {
    currStepProgress = steps[currStep]();
    if (currStepProgress > 1.0f) {
      currStepProgress = 0;
      ++currStep;
    }
  } else {
    if (hasPressedL && hasPressedS && hasPressedD) {
      enableLSDMode();
      shader::textureReplace.unload();
      shader::basic.unload();
    }

    //Start the root interpreter
    Tcl_Interp* root=newInterpreter(false);
    if (TCL_ERROR == Tcl_EvalFile(root, "tcl/autoexec.tcl")) {
      cerr << "FATAL: Autoexec did not run successfully: " << Tcl_GetStringResult(root) << endl;
      Tcl_Obj* options=Tcl_GetReturnOptions(root, TCL_ERROR);
      Tcl_Obj* key=Tcl_NewStringObj("-errorinfo", -1);
      Tcl_Obj* stackTrace;
      Tcl_IncrRefCount(key);
      Tcl_DictObjGet(NULL, options, key, &stackTrace);
      Tcl_DecrRefCount(key);
      cerr << "Stack trace:\n" << Tcl_GetStringFromObj(stackTrace, NULL) << endl;
      exit(EXIT_SCRIPTING_BUG);
    }
    if (this == state) {
      cerr << "FATAL: Autoexec did not change GameState" << endl;
      exit(EXIT_SCRIPTING_BUG);
    }
    if (!headless) {
      SDL_EnableUNICODE(1);
      SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
      //Tcl is taking over in a somewhat rude way, so
      //handle as gracefully as possible
      state->configureGL();
    }
  }

  return NULL;
}

void InitState::draw() {
  hasPainted=true;

  const shader::textureReplaceV quad[4] = {
      { {{0.5f-vheight/2,0      ,0,1}}, {{0,1}} },
      { {{0.5f+vheight/2,0      ,0,1}}, {{1,1}} },
      { {{0.5f-vheight/2,vheight,0,1}}, {{0,0}} },
      { {{0.5f+vheight/2,vheight,0,1}}, {{1,0}} },
  };

  shader::textureReplaceU uni;
  uni.colourMap=0;

  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
  shader::textureReplace->setupVBO();
  glBindTexture(GL_TEXTURE_2D, logo);
  shader::textureReplace->activate(&uni);
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

  static const float progressH = 0.02f;
  static const float progressW = 0.3f;
  float currProgress = currStep/(float)numSteps + currStepProgress/numSteps;
  float baseX = 0.5f - progressW/2;
  #if defined(AB_OPENGL_14)
  asgi::colour(1.0f, 0.4f, 0.2f, 0.75f);
  #elif defined(AB_OPENGL_21)
  asgi::colour(0.2f, 1.0f, 0.4f, 0.75f);
  #else
  asgi::colour(0.2f, 0.3f, 0.9f, 0.75f);
  #endif
  asgi::begin(asgi::Quads);
  asgi::vertex(baseX, 4*progressH);
  asgi::vertex(baseX, 5*progressH);
  asgi::vertex(baseX + currProgress*progressW, 5*progressH);
  asgi::vertex(baseX + currProgress*progressW, 4*progressH);
  asgi::end();
  asgi::begin(asgi::Quads);
  asgi::vertex(baseX, 2.75f*progressH);
  asgi::vertex(baseX, 3.75f*progressH);
  asgi::vertex(baseX + currStepProgress*progressW, 3.75*progressH);
  asgi::vertex(baseX + currStepProgress*progressW, 2.75*progressH);
  asgi::end();
}

void InitState::keyboard(SDL_KeyboardEvent* e) {
  if (e->keysym.sym == SDLK_l)
    hasPressedL = true;
  else if (e->keysym.sym == SDLK_s)
    hasPressedS = true;
  else if (e->keysym.sym == SDLK_d)
    hasPressedD = true;
}

float InitState::miscLoader() {
  initTable(); //Trig tables
  sparkCountMultiplier=1;
  if (conf["conf"]["audio_enabled"]) audio::init();
  prepareTclBridge();
  namegenLoad();
  return 2;
}

float InitState::starLoader() {
  initStarLists();
  return 2;
}

float InitState::backgroundLoader() {
  if (!headless && !loadBackgroundObjects()) exit(EXIT_MALFORMED_DATA);
  return 2;
}

float InitState::systexLoader() {
  if (!headless)
    system_texture::load();
  return 2;
}

float InitState::initFontLoader() {
  float mult = (preliminaryRunMode? 2.0f : min(vheight,1.0f));
  float size = conf["conf"]["hud"]["font_size"];
  new (sysfont)         Font("fonts/westm",   size*mult, false);
  new (sysfontStipple)  Font("fonts/westm",   size*mult, true );
  new (smallFont)       Font("fonts/unifont", size*mult/1.5f, false);
  new (smallFontStipple)Font("fonts/unifont", size*mult/1.5f, true );
  return 2;
}

//Delays for 500 ms to wait for keystrokes
float InitState::keyboardDelay() {
  if (preliminaryRunMode) return 2; //Don't wait

  static Uint32 start = SDL_GetTicks();
  Uint32 end = SDL_GetTicks();
  return (end-start)/512.0f;
}
<|endoftext|>


<commit_before>/** Copyright (c) 2015, Scality * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <nan.h>
#include "asyncencode.h"

class AsyncEncodeWorker : public Nan::AsyncWorker {
    public:
        AsyncEncodeWorker(Nan::Callback *callback, int instance_descriptor_id,
                int k, int m, char *orig_data, int orig_data_size) :
            Nan::AsyncWorker(callback),
            _instance_descriptor_id(instance_descriptor_id),
            _k(k),
            _m(m),
            _orig_data(orig_data),
            _orig_data_size(orig_data_size) {}

        ~AsyncEncodeWorker() {
            delete _orig_data;
        }

        void Execute() {
            _status = liberasurecode_encode(_instance_descriptor_id,
                    _orig_data, _orig_data_size,
                    &_encoded_data,
                    &_encoded_parity,
                    &_encoded_fragment_len);

            if (_status != 0) {
                SetErrorMessage("an error occured while encoding");
            }
        }

        void HandleOKCallback() {
            Nan::HandleScope scope;

            // FIXME: The uint64 to uint32 cast is anything but safe
            v8::Local<v8::Array> encoded_data_array = Nan::New<v8::Array>(_k);
            for (int i = 0; i < _k; i++) {
                Nan::Set(encoded_data_array, i,
                        Nan::NewBuffer(_encoded_data[i], _encoded_fragment_len)
                        .ToLocalChecked());
            }

            v8::Local<v8::Array> encoded_parity_array = Nan::New<v8::Array>(_m);
            for (int i = 0; i < _m; i++) {
                Nan::Set(encoded_parity_array, i, Nan::NewBuffer(_encoded_parity[i],
                            _encoded_fragment_len).ToLocalChecked());
            }

            free(_encoded_data);
            free(_encoded_parity);
            v8::Local<v8::Value> argv[] = {
                Nan::New<v8::Number>(_status),
                encoded_data_array,
                encoded_parity_array,
                Nan::New<v8::Number>(_encoded_fragment_len)
            };

            callback->Call(4, argv);
        }

        void HandleErrorCallback() {
            Nan::HandleScope scope;

            v8::Local<v8::Value> argv[] = {
                Nan::New<v8::Number>(_status)
            };

            callback->Call(1, argv);
        }

    private:
        // Input data.
        int _instance_descriptor_id;
        int _k;
        int _m;
        char *_orig_data;
        int _orig_data_size;
        // Output data.
        int _status;
        char **_encoded_data;
        char **_encoded_parity;
        uint64_t _encoded_fragment_len;
};

NAN_METHOD(EclEncode) {
    Nan::HandleScope scope;

    if (info.Length() < 6) {
        char msg[1024];
        sprintf(msg, "Wrong number of arguments (expected 6, got %d)",
                info.Length());
        Nan::ThrowTypeError(msg);
        return ;
    }

    int instance_descriptor_id = Nan::To<int>(info[0]).FromJust();
    int k = Nan::To<int>(info[1]).FromJust();
    int m = Nan::To<int>(info[2]).FromJust();
    int orig_data_size = Nan::To<int>(info[4]).FromJust();
    char *orig_data = node::Buffer::Data(info[3]);
    char *pass_orig_data = new char[orig_data_size];
    memcpy(pass_orig_data, orig_data, orig_data_size);

    Nan::Callback *callback = new Nan::Callback(info[5].As<v8::Function>());

    Nan::AsyncQueueWorker(new AsyncEncodeWorker(
                callback,
                instance_descriptor_id,
                k,
                m,
                pass_orig_data,
                orig_data_size
                ));
    return ;
}

NAN_METHOD(EclEncodeV) {
    Nan::HandleScope scope;

    if (info.Length() < 7) {
        char msg[1024];
        sprintf(msg, "Wrong number of arguments (expected 7, got %d)", info.Length());
        Nan::ThrowTypeError(msg);
        return ;
    }

    int instance_descriptor_id = Nan::To<int>(info[0]).FromJust();
    int k = Nan::To<int>(info[1]).FromJust();
    int m = Nan::To<int>(info[2]).FromJust();

    int orig_data_size = Nan::To<int>(info[5]).FromJust();
    char *orig_data = new char[orig_data_size];

    v8::Local<v8::Object>buf_array = Nan::To<v8::Object>(info[4]).ToLocalChecked();
    int n_buf = Nan::To<int>(info[3]).FromJust();
    int off = 0;
    for (int i = 0; i < n_buf; i++) {
        char *buf = node::Buffer::Data(Nan::Get(buf_array, i).ToLocalChecked());
        int buf_len = node::Buffer::Length(Nan::Get(buf_array, i).ToLocalChecked());
        memcpy(orig_data + off, buf, buf_len);
        off += buf_len;
    }

    Nan::Callback *callback = new Nan::Callback(info[6].As<v8::Function>());

    Nan::AsyncQueueWorker(new AsyncEncodeWorker(
                callback,
                instance_descriptor_id,
                k,
                m,
                orig_data,
                orig_data_size
                ));
    return ;
}
<commit_msg>Encode enhancement<commit_after>/** Copyright (c) 2015, Scality * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <nan.h>
#include "asyncencode.h"

class AsyncEncodeWorker : public Nan::AsyncWorker {
    public:
        AsyncEncodeWorker(Nan::Callback *callback, int instance_descriptor_id,
                int k, int m, v8::Local<v8::Object> &orig_data,
                int orig_data_size, int persistent_flag) :
            Nan::AsyncWorker(callback),
            _instance_descriptor_id(instance_descriptor_id),
            _k(k),
            _m(m),
            _orig_data_size(orig_data_size),
            _persistent_flag(persistent_flag) {
                if (_persistent_flag == 1) {
                    // make sure orig_data isn't GC'ed
                    SaveToPersistent("orig_data", orig_data);
                }
                _orig_data = node::Buffer::Data(orig_data);
            }

        ~AsyncEncodeWorker() {}

        void Execute() {
            _status = liberasurecode_encode(_instance_descriptor_id,
                    _orig_data, _orig_data_size,
                    &_encoded_data,
                    &_encoded_parity,
                    &_encoded_fragment_len);

            if (_status != 0) {
                SetErrorMessage("an error occured while encoding");
            }
        }

        void HandleOKCallback() {
            Nan::HandleScope scope;

            // FIXME: The uint64 to uint32 cast is anything but safe
            v8::Local<v8::Array> encoded_data_array = Nan::New<v8::Array>(_k);
            for (int i = 0; i < _k; i++) {
                Nan::Set(encoded_data_array, i,
                        Nan::NewBuffer(_encoded_data[i], _encoded_fragment_len)
                        .ToLocalChecked());
            }

            v8::Local<v8::Array> encoded_parity_array = Nan::New<v8::Array>(_m);
            for (int i = 0; i < _m; i++) {
                Nan::Set(encoded_parity_array, i, Nan::NewBuffer(_encoded_parity[i],
                            _encoded_fragment_len).ToLocalChecked());
            }

            free(_encoded_data);
            free(_encoded_parity);
            v8::Local<v8::Value> argv[] = {
                Nan::New<v8::Number>(_status),
                encoded_data_array,
                encoded_parity_array,
                Nan::New<v8::Number>(_encoded_fragment_len)
            };

            callback->Call(4, argv);
        }

        void HandleErrorCallback() {
            Nan::HandleScope scope;

            v8::Local<v8::Value> argv[] = {
                Nan::New<v8::Number>(_status)
            };

            callback->Call(1, argv);
        }

    private:
        // Input data.
        int _instance_descriptor_id;
        int _k;
        int _m;
        char *_orig_data;
        int _orig_data_size;
        int _persistent_flag;
        // Output data.
        int _status;
        char **_encoded_data;
        char **_encoded_parity;
        uint64_t _encoded_fragment_len;
};

NAN_METHOD(EclEncode) {
    Nan::HandleScope scope;

    if (info.Length() < 6) {
        char msg[1024];
        sprintf(msg, "Wrong number of arguments (expected 6, got %d)",
                info.Length());
        Nan::ThrowTypeError(msg);
        return ;
    }

    int instance_descriptor_id = Nan::To<int>(info[0]).FromJust();
    int k = Nan::To<int>(info[1]).FromJust();
    int m = Nan::To<int>(info[2]).FromJust();
    int persistent_flag = 1;
    int orig_data_size = Nan::To<int>(info[4]).FromJust();
    v8::Local<v8::Object> orig_data =
        Nan::To<v8::Object>(info[3]).ToLocalChecked();

    Nan::Callback *callback = new Nan::Callback(info[5].As<v8::Function>());

    Nan::AsyncQueueWorker(new AsyncEncodeWorker(
                callback,
                instance_descriptor_id,
                k,
                m,
                orig_data,
                orig_data_size,
                persistent_flag
                ));
    return ;
}

NAN_METHOD(EclEncodeV) {
    Nan::HandleScope scope;

    if (info.Length() < 7) {
        char msg[1024];
        sprintf(msg, "Wrong number of arguments (expected 7, got %d)", info.Length());
        Nan::ThrowTypeError(msg);
        return ;
    }

    int instance_descriptor_id = Nan::To<int>(info[0]).FromJust();
    int k = Nan::To<int>(info[1]).FromJust();
    int m = Nan::To<int>(info[2]).FromJust();

    int orig_data_size = Nan::To<int>(info[5]).FromJust();
    char *orig_data = new char[orig_data_size];
    int persistent_flag = 0;

    v8::Local<v8::Object>buf_array = Nan::To<v8::Object>(info[4]).ToLocalChecked();
    int n_buf = Nan::To<int>(info[3]).FromJust();
    int off = 0;
    for (int i = 0; i < n_buf; i++) {
        char *buf = node::Buffer::Data(Nan::Get(buf_array, i).ToLocalChecked());
        int buf_len = node::Buffer::Length(Nan::Get(buf_array, i).ToLocalChecked());
        memcpy(orig_data + off, buf, buf_len);
        off += buf_len;
    }
    v8::Local<v8::Object> ref_orig_data =
        Nan::NewBuffer(orig_data, orig_data_size).ToLocalChecked();

    Nan::Callback *callback = new Nan::Callback(info[6].As<v8::Function>());

    Nan::AsyncQueueWorker(new AsyncEncodeWorker(
                callback,
                instance_descriptor_id,
                k,
                m,
                ref_orig_data,
                orig_data_size,
                persistent_flag
                ));
    return;
}
<|endoftext|>


<commit_before>#include "lua-helpers.h"

namespace effil {

namespace
{

std::string luaError(int errCode)
{
    switch(errCode)
    {
        case LUA_ERRSYNTAX: return "Invalid syntax (LUA_ERRSYNTAX)";
        case LUA_ERRMEM:    return "Memory allocation error (LUA_ERRMEM)";
        case LUA_ERRRUN:    return "Execution error (LUA_ERRRUN)";
        case LUA_ERRGCMM:   return "Error in __gc method (LUA_ERRGCMM)";
        case LUA_ERRERR:    return "Recursive error (LUA_ERRERR)";
        default: return "Unknown";
    }
}

int dumpMemoryWriter(lua_State*, const void* batch, size_t batchSize, void* storage) {
    if (storage == nullptr || batch == nullptr)
        return 1;
    if (batchSize) {
        std::string& buff = *reinterpret_cast<std::string*>(storage);
        const char* newData = reinterpret_cast<const char*>(batch);
        buff.insert(buff.end(), newData, newData + batchSize);
    }
    return 0;
}

}

std::string dumpFunction(const sol::function& f) {
    sol::state_view lua(f.lua_state());
    sol::stack::push(lua, f);
    std::string result;
    int ret = lua_dump(lua, dumpMemoryWriter, &result);
    REQUIRE(ret == LUA_OK) << "Unable to dump Lua function: " << luaError(ret);
    sol::stack::remove(lua, -1, 1);
    return result;
}

sol::function loadString(const sol::state_view& lua, const std::string& str) {
    int ret = luaL_loadbuffer(lua, str.c_str(), str.size(), nullptr);
    REQUIRE(ret == LUA_OK) << "Unable to load function from string: " << luaError(ret);
    return sol::stack::pop<sol::function>(lua);
}

std::chrono::milliseconds fromLuaTime(int duration, const sol::optional<std::string>& period) {
    using namespace std::chrono;

    REQUIRE(duration >= 0) << "Invalid duration interval: " << duration;

    std::string metric = period ? period.value() : "s";
    if (metric == "ms") return milliseconds(duration);
    else if (metric == "s") return seconds(duration);
    else if (metric == "m") return minutes(duration);
    else throw sol::error("invalid time identification: " + metric);
}

} // namespace effil
<commit_msg>Fix sode style<commit_after>#include "lua-helpers.h"

namespace effil {

namespace {

std::string luaError(int errCode) {
    switch(errCode) {
        case LUA_ERRSYNTAX: return "Invalid syntax (LUA_ERRSYNTAX)";
        case LUA_ERRMEM:    return "Memory allocation error (LUA_ERRMEM)";
        case LUA_ERRRUN:    return "Execution error (LUA_ERRRUN)";
        case LUA_ERRGCMM:   return "Error in __gc method (LUA_ERRGCMM)";
        case LUA_ERRERR:    return "Recursive error (LUA_ERRERR)";
        default: return "Unknown";
    }
}

int dumpMemoryWriter(lua_State*, const void* batch, size_t batchSize, void* storage) {
    if (storage == nullptr || batch == nullptr)
        return 1;
    if (batchSize) {
        std::string& buff = *reinterpret_cast<std::string*>(storage);
        const char* newData = reinterpret_cast<const char*>(batch);
        buff.insert(buff.end(), newData, newData + batchSize);
    }
    return 0;
}

} // namespacce

std::string dumpFunction(const sol::function& f) {
    sol::state_view lua(f.lua_state());
    sol::stack::push(lua, f);
    std::string result;
    int ret = lua_dump(lua, dumpMemoryWriter, &result);
    REQUIRE(ret == LUA_OK) << "Unable to dump Lua function: " << luaError(ret);
    sol::stack::remove(lua, -1, 1);
    return result;
}

sol::function loadString(const sol::state_view& lua, const std::string& str) {
    int ret = luaL_loadbuffer(lua, str.c_str(), str.size(), nullptr);
    REQUIRE(ret == LUA_OK) << "Unable to load function from string: " << luaError(ret);
    return sol::stack::pop<sol::function>(lua);
}

std::chrono::milliseconds fromLuaTime(int duration, const sol::optional<std::string>& period) {
    using namespace std::chrono;

    REQUIRE(duration >= 0) << "Invalid duration interval: " << duration;

    std::string metric = period ? period.value() : "s";
    if (metric == "ms") return milliseconds(duration);
    else if (metric == "s") return seconds(duration);
    else if (metric == "m") return minutes(duration);
    else throw sol::error("invalid time identification: " + metric);
}

} // namespace effil
<|endoftext|>


<commit_before>/**
 * Copyright : falcon build system (c) 2014.
 * LICENSE : see accompanying LICENSE file for details.
 */

#include "daemon_instance.h"

#include "graphparser.h"
#include "server.h"

#include "watchman.h"
#include "exceptions.h"
#include "logging.h"

using namespace std::placeholders;

namespace falcon {

DaemonInstance::DaemonInstance(std::unique_ptr<GlobalConfig> gc)
    : buildId_(0), config_(std::move(gc)), isBuilding_(false),
      streamServer_() {

}

void DaemonInstance::loadConf(std::unique_ptr<Graph> gp) {
  graph_ = std::move(gp);
}

void DaemonInstance::start() {
  if (config_->runSequentialBuild()) {
    StdoutStreamConsumer consumer;
    GraphSequentialBuilder builder(*graph_.get(),
                                   config_->getWorkingDirectoryPath(),
                                   &consumer);
    builder.startBuild(graph_->getRoots(), false /* No callback. */);
    builder.wait();
    /* TODO: get build exit status. */
    return;
  }

  assert(!server_);

  { /* register to watchman every files */
    try {
      WatchmanServer watchmanServer(config_->getWorkingDirectoryPath());
      watchmanServer.startWatching(graph_.get());
    } catch (falcon::Exception e) {
      LOG(fatal) << e.getErrorMessage();
    }
  }

  /* Open the stream server's socket and accept clients in another thread. */
  streamServer_.openPort(config_->getNetworkStreamPort());
  std::thread streamServerThread = std::thread(&StreamServer::run,
                                               &streamServer_);

  /* Start the server. This will block until the server shuts down. */
  LOG(info) << "Starting server...";
  server_.reset(new Server(this, config_->getNetworkAPIPort()));
  server_->start();

  /* If we reach here, the server was shut down. */
  builder_->wait();
  streamServer_.stop();
  streamServerThread.join();
}

/* Commands */

StartBuildResult::type DaemonInstance::startBuild() {
  lock_guard g(mutex_);

  if (isBuilding_) {
     return StartBuildResult::BUSY;
  }

  isBuilding_ = true;

  streamServer_.newBuild(buildId_);

  builder_.reset(
      new GraphSequentialBuilder(*graph_.get(),
                                 config_->getWorkingDirectoryPath(),
                                 &streamServer_));
  builder_->startBuild(graph_->getRoots(),
      std::bind(&DaemonInstance::onBuildCompleted, this, _1));

  return StartBuildResult::OK;
}

void DaemonInstance::onBuildCompleted(BuildResult res) {
  lock_guard g(mutex_);

  isBuilding_ = false;

  streamServer_.endBuild(res);
  ++buildId_;

  LOG(info) << "Build completed. Status: " << toString(res);
}

FalconStatus::type DaemonInstance::getStatus() {
  lock_guard g(mutex_);

  return isBuilding_ ? FalconStatus::BUILDING : FalconStatus::IDLE;
}

void DaemonInstance::interruptBuild() {
  lock_guard g(mutex_);

  LOG(info) << "Interrupting build.";

  if (builder_) {
    builder_->interrupt();
  }
}

void DaemonInstance::getDirtySources(std::set<std::string>& sources) {
  lock_guard g(mutex_);

  NodeSet& src = graph_->getSources();
  for (auto it = src.begin(); it != src.end(); ++it) {
    if ((*it)->getState() == State::OUT_OF_DATE) {
      sources.insert((*it)->getPath());
    }
  }
}

void DaemonInstance::setDirty(const std::string& target) {
  lock_guard g(mutex_);

  LOG(debug) << target << " is marked dirty.";

  /* Find the target. */
  auto& map = graph_->getNodes();
  auto it = map.find(target);
  if (it == map.end()) {
    throw TargetNotFound();
  }
  it->second->markDirty();
}

void DaemonInstance::shutdown() {
  LOG(info) << "Shutting down.";

  /* Interrupt the current build. */
  interruptBuild();

  /* Stop the thrift server. */
  assert(server_);
  /* TODO: is this a problem to call stop from a thrift handler? */
  server_->stop();
}

} // namespace falcon
<commit_msg>fix crash when shutting down while no build was started<commit_after>/**
 * Copyright : falcon build system (c) 2014.
 * LICENSE : see accompanying LICENSE file for details.
 */

#include "daemon_instance.h"

#include "graphparser.h"
#include "server.h"

#include "watchman.h"
#include "exceptions.h"
#include "logging.h"

using namespace std::placeholders;

namespace falcon {

DaemonInstance::DaemonInstance(std::unique_ptr<GlobalConfig> gc)
    : buildId_(0), config_(std::move(gc)), isBuilding_(false),
      streamServer_() {

}

void DaemonInstance::loadConf(std::unique_ptr<Graph> gp) {
  graph_ = std::move(gp);
}

void DaemonInstance::start() {
  if (config_->runSequentialBuild()) {
    StdoutStreamConsumer consumer;
    GraphSequentialBuilder builder(*graph_.get(),
                                   config_->getWorkingDirectoryPath(),
                                   &consumer);
    builder.startBuild(graph_->getRoots(), false /* No callback. */);
    builder.wait();
    /* TODO: get build exit status. */
    return;
  }

  assert(!server_);

  { /* register to watchman every files */
    try {
      WatchmanServer watchmanServer(config_->getWorkingDirectoryPath());
      watchmanServer.startWatching(graph_.get());
    } catch (falcon::Exception e) {
      LOG(fatal) << e.getErrorMessage();
    }
  }

  /* Open the stream server's socket and accept clients in another thread. */
  streamServer_.openPort(config_->getNetworkStreamPort());
  std::thread streamServerThread = std::thread(&StreamServer::run,
                                               &streamServer_);

  /* Start the server. This will block until the server shuts down. */
  LOG(info) << "Starting server...";
  server_.reset(new Server(this, config_->getNetworkAPIPort()));
  server_->start();

  /* If we reach here, the server was shut down. */
  if (builder_) {
    builder_->wait();
  }
  streamServer_.stop();
  streamServerThread.join();
}

/* Commands */

StartBuildResult::type DaemonInstance::startBuild() {
  lock_guard g(mutex_);

  if (isBuilding_) {
     return StartBuildResult::BUSY;
  }

  isBuilding_ = true;

  streamServer_.newBuild(buildId_);

  builder_.reset(
      new GraphSequentialBuilder(*graph_.get(),
                                 config_->getWorkingDirectoryPath(),
                                 &streamServer_));
  builder_->startBuild(graph_->getRoots(),
      std::bind(&DaemonInstance::onBuildCompleted, this, _1));

  return StartBuildResult::OK;
}

void DaemonInstance::onBuildCompleted(BuildResult res) {
  lock_guard g(mutex_);

  isBuilding_ = false;

  streamServer_.endBuild(res);
  ++buildId_;

  LOG(info) << "Build completed. Status: " << toString(res);
}

FalconStatus::type DaemonInstance::getStatus() {
  lock_guard g(mutex_);

  return isBuilding_ ? FalconStatus::BUILDING : FalconStatus::IDLE;
}

void DaemonInstance::interruptBuild() {
  lock_guard g(mutex_);

  LOG(info) << "Interrupting build.";

  if (builder_) {
    builder_->interrupt();
  }
}

void DaemonInstance::getDirtySources(std::set<std::string>& sources) {
  lock_guard g(mutex_);

  NodeSet& src = graph_->getSources();
  for (auto it = src.begin(); it != src.end(); ++it) {
    if ((*it)->getState() == State::OUT_OF_DATE) {
      sources.insert((*it)->getPath());
    }
  }
}

void DaemonInstance::setDirty(const std::string& target) {
  lock_guard g(mutex_);

  LOG(debug) << target << " is marked dirty.";

  /* Find the target. */
  auto& map = graph_->getNodes();
  auto it = map.find(target);
  if (it == map.end()) {
    throw TargetNotFound();
  }
  it->second->markDirty();
}

void DaemonInstance::shutdown() {
  LOG(info) << "Shutting down.";

  /* Interrupt the current build. */
  interruptBuild();

  /* Stop the thrift server. */
  assert(server_);
  /* TODO: is this a problem to call stop from a thrift handler? */
  server_->stop();
}

} // namespace falcon
<|endoftext|>


<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// 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 <gtest/gtest.h>

#include "ngraph/op/add.hpp"
#include "ngraph/runtime/backend.hpp"
#include "ngraph/util.hpp"
#include "util/test_tools.hpp"

using namespace ngraph;
using namespace std;

TEST(async, execute)
{
    Shape shape{100000};
    auto A = make_shared<op::Parameter>(element::f32, shape);
    auto B = make_shared<op::Parameter>(element::f32, shape);
    auto f = make_shared<Function>(make_shared<op::Add>(A, B), ParameterVector{A, B});

    auto backend = runtime::Backend::create("INTERPRETER");

    vector<float> data(shape_size(shape), 2);
    vector<float> result_data(shape_size(shape), 0);

    // Create some tensors for input/output
    shared_ptr<runtime::Tensor> a = backend->create_tensor(element::f32, shape, data.data());
    shared_ptr<runtime::Tensor> b = backend->create_tensor(element::f32, shape, data.data());
    shared_ptr<runtime::Tensor> r = backend->create_tensor(element::f32, shape, result_data.data());

    auto handle = backend->compile(f);
    auto future = handle->begin_execute({r}, {a, b});
    ASSERT_TRUE(future.valid());
    bool rc = future.get();

    for (float x : result_data)
    {
        ASSERT_EQ(x, 4);
    }
}

TEST(async, tensor_write)
{
    Shape shape{100000};
    auto A = make_shared<op::Parameter>(element::f32, shape);
    auto B = make_shared<op::Parameter>(element::f32, shape);
    auto f = make_shared<Function>(make_shared<op::Add>(A, B), ParameterVector{A, B});

    auto backend = runtime::Backend::create("INTERPRETER");
    auto handle = backend->compile(f);

    vector<float> data(shape_size(shape), 2);
    vector<float> result_data(shape_size(shape), 0);

    // Create some tensors for input/output
    shared_ptr<runtime::Tensor> a = backend->create_tensor(element::f32, shape);
    shared_ptr<runtime::Tensor> b = backend->create_tensor(element::f32, shape);
    shared_ptr<runtime::Tensor> r = backend->create_tensor(element::f32, shape, result_data.data());

    auto future_a = a->begin_write(data.data(), data.size() * sizeof(float));
    auto future_b = b->begin_write(data.data(), data.size() * sizeof(float));
    ASSERT_TRUE(future_a.valid());
    ASSERT_TRUE(future_b.valid());

    chrono::milliseconds ten_ms(10);
    EXPECT_EQ(future_a.wait_for(ten_ms), future_status::timeout);
    EXPECT_EQ(future_b.wait_for(ten_ms), future_status::timeout);

    this_thread::sleep_for(chrono::milliseconds(500));

    EXPECT_EQ(future_a.wait_for(ten_ms), future_status::timeout);
    EXPECT_EQ(future_b.wait_for(ten_ms), future_status::timeout);

    auto future = handle->begin_execute({r}, {a, b});
    bool rc = future.get();

    EXPECT_EQ(future_a.wait_for(ten_ms), future_status::ready);
    EXPECT_EQ(future_b.wait_for(ten_ms), future_status::ready);

    for (float x : result_data)
    {
        ASSERT_EQ(x, 4);
    }
}

TEST(async, tensor_read)
{
}
<commit_msg>read/write test<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// 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 <gtest/gtest.h>

#include "ngraph/op/add.hpp"
#include "ngraph/runtime/backend.hpp"
#include "ngraph/util.hpp"
#include "util/test_tools.hpp"

using namespace ngraph;
using namespace std;

TEST(async, execute)
{
    Shape shape{100000};
    auto A = make_shared<op::Parameter>(element::f32, shape);
    auto B = make_shared<op::Parameter>(element::f32, shape);
    auto f = make_shared<Function>(make_shared<op::Add>(A, B), ParameterVector{A, B});

    auto backend = runtime::Backend::create("INTERPRETER");

    vector<float> data(shape_size(shape), 2);
    vector<float> result_data(shape_size(shape), 0);

    // Create some tensors for input/output
    shared_ptr<runtime::Tensor> a = backend->create_tensor(element::f32, shape, data.data());
    shared_ptr<runtime::Tensor> b = backend->create_tensor(element::f32, shape, data.data());
    shared_ptr<runtime::Tensor> r = backend->create_tensor(element::f32, shape, result_data.data());

    auto handle = backend->compile(f);
    auto future = handle->begin_execute({r}, {a, b});
    ASSERT_TRUE(future.valid());
    future.get();

    for (float x : result_data)
    {
        ASSERT_EQ(x, 4);
    }
}

TEST(async, tensor_read_write)
{
    Shape shape{100000};
    auto A = make_shared<op::Parameter>(element::f32, shape);
    auto B = make_shared<op::Parameter>(element::f32, shape);
    auto f = make_shared<Function>(make_shared<op::Add>(A, B), ParameterVector{A, B});

    auto backend = runtime::Backend::create("INTERPRETER");
    auto handle = backend->compile(f);

    vector<float> data(shape_size(shape), 2);
    vector<float> data_r(shape_size(shape), 0);

    // Create some tensors for input/output
    shared_ptr<runtime::Tensor> a = backend->create_tensor(element::f32, shape);
    shared_ptr<runtime::Tensor> b = backend->create_tensor(element::f32, shape);
    shared_ptr<runtime::Tensor> r = backend->create_tensor(element::f32, shape);

    auto future_a = a->begin_write(data.data(), data.size() * sizeof(float));
    auto future_b = b->begin_write(data.data(), data.size() * sizeof(float));
    auto future_r = r->begin_read(data_r.data(), data_r.size() * sizeof(float));
    ASSERT_TRUE(future_a.valid());
    ASSERT_TRUE(future_b.valid());
    ASSERT_TRUE(future_r.valid());

    chrono::milliseconds ten_ms(10);
    EXPECT_EQ(future_a.wait_for(ten_ms), future_status::timeout);
    EXPECT_EQ(future_b.wait_for(ten_ms), future_status::timeout);
    EXPECT_EQ(future_r.wait_for(ten_ms), future_status::timeout);

    this_thread::sleep_for(chrono::milliseconds(500));

    EXPECT_EQ(future_a.wait_for(ten_ms), future_status::timeout);
    EXPECT_EQ(future_b.wait_for(ten_ms), future_status::timeout);
    EXPECT_EQ(future_r.wait_for(ten_ms), future_status::timeout);

    auto future = handle->begin_execute({r}, {a, b});
    future.get();

    EXPECT_EQ(future_a.wait_for(ten_ms), future_status::ready);
    EXPECT_EQ(future_b.wait_for(ten_ms), future_status::ready);
    EXPECT_EQ(future_r.wait_for(ten_ms), future_status::ready);

    for (float x : data_r)
    {
        ASSERT_EQ(x, 4);
    }
}
<|endoftext|>


<commit_before>
#include "analysis.h"

#include <QDebug>

#include <boost/bind.hpp>

#include "options/options.h"

#include <QStringBuilder>

#include <boost/foreach.hpp>

using namespace boost::uuids;
using namespace boost;
using namespace std;

Analysis::Analysis(int id, string name)
{
	_id = id;
	_name = name;

	_status = Empty;

	_dataSet = NULL;
	_r = NULL;

	_options = NULL;
}

void Analysis::init()
{
	_status = Initing;

	_results = _r->init(_name, options()->asJSON());

	_status = Inited;
	resultsChanged(this);
}

void Analysis::run()
{
	_status = Running;
	_results = _r->run(_name, options()->asJSON(), boost::bind(&Analysis::callback, this, _1));

	// status can be changed by subsequent messages, so we have to see if the analysis has
	// changed. if it has, then we shouldn't bother sending the results

	if (_status == Running)
	{
		_status = Complete;
		resultsChanged(this);
	}
}

string Analysis::js()
{
	return "{"
			"    depends : [ 'tables' ],"
			"    render  : function(element, results)"
			"    {"
			"        element.tables( { tables : _.toArray(results) } )"
			"    }"
			"}";
}

void Analysis::setResults(Json::Value results)
{
	_results = results;
	resultsChanged(this);
}

Json::Value Analysis::results()
{
	return _results;
}

Json::Value Analysis::asJSON()
{
	Json::Value analysisAsJson = Json::objectValue;

	analysisAsJson["id"] = _id;
	analysisAsJson["name"] = _name;
	analysisAsJson["results"] = _results;

	return analysisAsJson;
}

Analysis::Status Analysis::status()
{
	return _status;
}

void Analysis::setStatus(Analysis::Status status)
{
	_status = status;
}

string Analysis::name()
{
	return _name;
}

int Analysis::id()
{
	return _id;
}

Options *Analysis::options()
{
	if (_options == NULL)
	{
		_options = createDefaultOptions();
		_options->changed.connect(boost::bind(&Analysis::optionsChangedHandler, this));
	}

	return _options;
}

void Analysis::optionsChangedHandler()
{
	_status = Empty;
	optionsChanged(this);
}

void Analysis::setRInterface(RInterface *r)
{
	_r = r;
}

void Analysis::setDataSet(DataSet *dataSet)
{
	_dataSet = dataSet;
}

int Analysis::callback(Json::Value results)
{
	if (_status != Empty && _status != Aborted)
	{
		if (results != Json::nullValue)
		{
			_results = results;
			resultsChanged(this);
		}
		return 0;
	}
	else
	{
		return 1;
	}
}

std::vector<string> Analysis::list(string one, string two, string three, string four, string five, string six, string seven, string eight, string nine, string ten)
{
	vector<string> result;

	result.push_back(one);
	result.push_back(two);

	if (three != "")
		result.push_back(three);
	if (four != "")
		result.push_back(four);
	if (five != "")
		result.push_back(five);
	if (six != "")
		result.push_back(six);
	if (seven != "")
		result.push_back(seven);
	if (eight != "")
		result.push_back(eight);
	if (nine != "")
		result.push_back(nine);
	if (ten != "")
		result.push_back(ten);

	return result;
}
<commit_msg>Update to the display of tables<commit_after>
#include "analysis.h"

#include <QDebug>

#include <boost/bind.hpp>

#include "options/options.h"

#include <QStringBuilder>

#include <boost/foreach.hpp>

using namespace boost::uuids;
using namespace boost;
using namespace std;

Analysis::Analysis(int id, string name)
{
	_id = id;
	_name = name;

	_status = Empty;

	_dataSet = NULL;
	_r = NULL;

	_options = NULL;
}

void Analysis::init()
{
	_status = Initing;

	_results = _r->init(_name, options()->asJSON());

	_status = Inited;
	resultsChanged(this);
}

void Analysis::run()
{
	_status = Running;
	_results = _r->run(_name, options()->asJSON(), boost::bind(&Analysis::callback, this, _1));

	// status can be changed by subsequent messages, so we have to see if the analysis has
	// changed. if it has, then we shouldn't bother sending the results

	if (_status == Running)
	{
		_status = Complete;
		resultsChanged(this);
	}
}

string Analysis::js()
{
	return "{"
			"    depends : [ 'tables' ],\n"
			"    render  : function(element, results)\n"
			"    {\n"
			"        var tables = [ ]\n"
			"        _.each(results, function(result) {\n"
			"            if (_.isArray(result))\n"
			"                _.each(result, function(table) {\n"
			"                    tables.push(table) })\n"
			"            else\n"
			"                tables.push(result)\n"
			"        })\n"
			"        element.tables( { tables : tables } )\n"
			"    }\n"
			"}\n";
}

void Analysis::setResults(Json::Value results)
{
	_results = results;
	resultsChanged(this);
}

Json::Value Analysis::results()
{
	return _results;
}

Json::Value Analysis::asJSON()
{
	Json::Value analysisAsJson = Json::objectValue;

	analysisAsJson["id"] = _id;
	analysisAsJson["name"] = _name;
	analysisAsJson["results"] = _results;

	return analysisAsJson;
}

Analysis::Status Analysis::status()
{
	return _status;
}

void Analysis::setStatus(Analysis::Status status)
{
	_status = status;
}

string Analysis::name()
{
	return _name;
}

int Analysis::id()
{
	return _id;
}

Options *Analysis::options()
{
	if (_options == NULL)
	{
		_options = createDefaultOptions();
		_options->changed.connect(boost::bind(&Analysis::optionsChangedHandler, this));
	}

	return _options;
}

void Analysis::optionsChangedHandler()
{
	_status = Empty;
	optionsChanged(this);
}

void Analysis::setRInterface(RInterface *r)
{
	_r = r;
}

void Analysis::setDataSet(DataSet *dataSet)
{
	_dataSet = dataSet;
}

int Analysis::callback(Json::Value results)
{
	if (_status != Empty && _status != Aborted)
	{
		if (results != Json::nullValue)
		{
			_results = results;
			resultsChanged(this);
		}
		return 0;
	}
	else
	{
		return 1;
	}
}

std::vector<string> Analysis::list(string one, string two, string three, string four, string five, string six, string seven, string eight, string nine, string ten)
{
	vector<string> result;

	result.push_back(one);
	result.push_back(two);

	if (three != "")
		result.push_back(three);
	if (four != "")
		result.push_back(four);
	if (five != "")
		result.push_back(five);
	if (six != "")
		result.push_back(six);
	if (seven != "")
		result.push_back(seven);
	if (eight != "")
		result.push_back(eight);
	if (nine != "")
		result.push_back(nine);
	if (ten != "")
		result.push_back(ten);

	return result;
}
<|endoftext|>


<commit_before>/* The MIT License (MIT)
 *
 * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "elf_file.hpp"
#include "elf_header_container.hpp"
#include "program_header_table_container.hpp"
#include "section_header_table_container.hpp"
#include "segment_contents_container.hpp"
#include "section_contents_container.hpp"
#include <utility>

//#include "code_container.hpp"

using namespace elf;

ELFFile::ELFFile(const std::string &filename) : FileUnit(filename)
{
    file = new ELFIO::elfio();
    open = file->load(filename);

    std::vector<Container *> &topLevelContainers = getTopLevelContainers();
    topLevelContainers.push_back(new ELFHeaderContainer(this, std::make_pair(0, 10)));
    topLevelContainers.push_back(new ProgramHeaderTableContainer(this, std::make_pair(10, 20)));
    //CodeContainer *c = new CodeContainer(this, std::make_pair(0, 10));
    //c->setName("first root with representation");
    //topLevelContainers.push_back(c);
    //topLevelContainers.push_back(c);
    topLevelContainers.push_back(new SectionHeaderTableContainer(this, std::make_pair(20, 30)));
    topLevelContainers.push_back(new SegmentContentsContainer(this));
    topLevelContainers.push_back(new SectionContentsContainer(this));
}

ELFFile::~ELFFile()
{
    delete file;
}

bool ELFFile::getOpenStatus()
{
    return open;
}

bool ELFFile::save(std::string &filename)
{
    return file->save(filename);
}

void ELFFile::modifyHex(size_t offset, std::string &newContent) {}
<commit_msg>Only open executable files<commit_after>/* The MIT License (MIT)
 *
 * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "elf_file.hpp"
#include "elf_header_container.hpp"
#include "program_header_table_container.hpp"
#include "section_header_table_container.hpp"
#include "segment_contents_container.hpp"
#include "section_contents_container.hpp"
#include <utility>

//#include "code_container.hpp"

using namespace elf;

ELFFile::ELFFile(const std::string &filename) : FileUnit(filename)
{
    file = new ELFIO::elfio();
    open = file->load(filename);
    if (file->get_type() != ET_EXEC)
        open = false;

    if (open)
    {
        std::vector<Container *> &topLevelContainers = getTopLevelContainers();
        topLevelContainers.push_back(new ELFHeaderContainer(this, std::make_pair(0, 10)));
        topLevelContainers.push_back(new ProgramHeaderTableContainer(this, std::make_pair(10, 20)));
        //CodeContainer *c = new CodeContainer(this, std::make_pair(0, 10));
        //c->setName("first root with representation");
        //topLevelContainers.push_back(c);
        //topLevelContainers.push_back(c);
        topLevelContainers.push_back(new SectionHeaderTableContainer(this, std::make_pair(20, 30)));
        topLevelContainers.push_back(new SegmentContentsContainer(this));
        topLevelContainers.push_back(new SectionContentsContainer(this));
    }
}

ELFFile::~ELFFile()
{
    delete file;
}

bool ELFFile::getOpenStatus()
{
    return open;
}

bool ELFFile::save(std::string &filename)
{
    return file->save(filename);
}

void ELFFile::modifyHex(size_t offset, std::string &newContent) {}
<|endoftext|>


<commit_before>/*
 * This file is part of the Yildiz-Engine project, licenced under the MIT License  (MIT)
 *
 * Copyright (c) 2019 Grégory Van den Borre
 *
 * More infos available: https://engine.yildiz-games.be
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT  HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  SOFTWARE.
 */

#include "../includes/yz_ogre_vfs_Archive.hpp"

bool yz::ogre::vfs::Archive::exists(const Ogre::String& filename) const {
    LOG_FUNCTION
    return this->vfs->exists(mName + '/' + filename);
}

Ogre::DataStreamPtr yz::ogre::vfs::Archive::open(const Ogre::String& filename, bool append) const {
    LOG_FUNCTION
    Ogre::String fullName = mName + '/' + filename;
    return Ogre::DataStreamPtr(new yz::ogre::vfs::DataStream(filename, fullName));
}

void yz::ogre::vfs::Archive::listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const {
    LOG_FUNCTION
    Ogre::String baseDir = mName + '/' + base;
    StringVector files = this->vfs->enumerateFiles(baseDir);

    Ogre::FileInfo fileInfo;
    fileInfo.archive = this;
    fileInfo.path = base;
    fileInfo.compressedSize = 0;

    // iterate over all files and directories in the given directory
    for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {
         fileInfo.basename = *it;
         fileInfo.filename = base + *it;
         if (this->vfs->isDirectory(*it)) {
             if (dirs) {
                 fileInfo.uncompressedSize = 0;
                 fileInfoList->push_back(fileInfo);
             }
             if (recursive) {
                 listInfoRecursive(base + *it + '/', recursive, dirs, fileInfoList);
             }
         } else {
             if (!dirs) {
                 // get file size
                 yz::physfs::File* file = new yz::physfs::File(mName + '/' + fileInfo.filename);
                 fileInfo.uncompressedSize = (size_t) file->getSize();
                 file->close();

                 fileInfoList->push_back(fileInfo);
             }
         }
     }
 }

void yz::ogre::vfs::Archive::listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const {
     LOG_FUNCTION

     Ogre::String baseDir = mName + '/' + base;
     StringVector files = this->vfs->enumerateFiles(baseDir);

     // iterate over all files and directories in the given directory
     for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {
         if (this->vfs->isDirectory(*it)) {
             if (dirs) {
                 fileList->push_back(base + *it);
             }
             if (recursive) {
                 listRecursive(base + *it + '/', recursive, dirs, fileList);
             }
         } else {
             if (!dirs) {
                 fileList->push_back(base + *it);
             }
         }
     }
 }

Ogre::FileInfoListPtr yz::ogre::vfs::Archive::listFileInfo(bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::FileInfoListPtr fileInfoList(new Ogre::FileInfoList());
     listInfoRecursive("", recursive, dirs, fileInfoList);
     return fileInfoList;
 }

Ogre::StringVectorPtr yz::ogre::vfs::Archive::list(bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::StringVectorPtr fileList(new Ogre::StringVector());
     listRecursive("", recursive, dirs, fileList);
     return fileList;
 }

Ogre::StringVectorPtr yz::ogre::vfs::Archive::find(const Ogre::String& pattern, bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::StringVectorPtr fileList = list(recursive, dirs);
     Ogre::StringVectorPtr ret(new Ogre::StringVector());

     for (Ogre::StringVector::iterator it = fileList->begin(); it != fileList->end(); ++it) {
         if (Ogre::StringUtil::match(*it, pattern))
             ret->push_back(*it);
     }
     return ret;
 }

Ogre::FileInfoListPtr yz::ogre::vfs::Archive::findFileInfo(const Ogre::String& pattern, bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::FileInfoListPtr fileList = const_cast<yz::ogre::vfs::Archive*>(this)->listFileInfo(recursive, dirs);
     Ogre::FileInfoListPtr ret(new Ogre::FileInfoList());

     for (Ogre::FileInfoList::iterator it = fileList->begin(); it != fileList->end(); ++it) {
         if (Ogre::StringUtil::match(it->filename, pattern))
             ret->push_back(*it);
     }

     return ret;
 }
<commit_msg>Update yz_ogre_vfs_Archive.cpp<commit_after>/*
 * This file is part of the Yildiz-Engine project, licenced under the MIT License  (MIT)
 *
 * Copyright (c) 2019 Grégory Van den Borre
 *
 * More infos available: https://engine.yildiz-games.be
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT  HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  SOFTWARE.
 */

#include "../includes/yz_ogre_vfs_Archive.hpp"

bool yz::ogre::vfs::Archive::exists(const Ogre::String& filename) const {
    LOG_FUNCTION
    return this->vfs->exists(mName + '/' + filename);
}

Ogre::DataStreamPtr yz::ogre::vfs::Archive::open(const Ogre::String& filename, bool append) const {
    LOG_FUNCTION
    Ogre::String fullName = mName + '/' + filename;
    return Ogre::DataStreamPtr(new yz::ogre::vfs::DataStream(filename, fullName));
}

void yz::ogre::vfs::Archive::listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const {
    LOG_FUNCTION
    Ogre::String baseDir = mName + '/' + base;
    Ogre::StringVector files = this->vfs->enumerateFiles(baseDir);

    Ogre::FileInfo fileInfo;
    fileInfo.archive = this;
    fileInfo.path = base;
    fileInfo.compressedSize = 0;

    // iterate over all files and directories in the given directory
    for (Ogre::StringVector::iterator it = files.begin(); it != files.end(); ++it) {
         fileInfo.basename = *it;
         fileInfo.filename = base + *it;
         if (this->vfs->isDirectory(*it)) {
             if (dirs) {
                 fileInfo.uncompressedSize = 0;
                 fileInfoList->push_back(fileInfo);
             }
             if (recursive) {
                 listInfoRecursive(base + *it + '/', recursive, dirs, fileInfoList);
             }
         } else {
             if (!dirs) {
                 // get file size
                 yz::physfs::File* file = new yz::physfs::File(mName + '/' + fileInfo.filename);
                 fileInfo.uncompressedSize = (size_t) file->getSize();
                 file->close();

                 fileInfoList->push_back(fileInfo);
             }
         }
     }
 }

void yz::ogre::vfs::Archive::listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const {
     LOG_FUNCTION

     Ogre::String baseDir = mName + '/' + base;
     Ogre::StringVector files = this->vfs->enumerateFiles(baseDir);

     // iterate over all files and directories in the given directory
     for (Ogre::StringVector::iterator it = files.begin(); it != files.end(); ++it) {
         if (this->vfs->isDirectory(*it)) {
             if (dirs) {
                 fileList->push_back(base + *it);
             }
             if (recursive) {
                 listRecursive(base + *it + '/', recursive, dirs, fileList);
             }
         } else {
             if (!dirs) {
                 fileList->push_back(base + *it);
             }
         }
     }
 }

Ogre::FileInfoListPtr yz::ogre::vfs::Archive::listFileInfo(bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::FileInfoListPtr fileInfoList(new Ogre::FileInfoList());
     listInfoRecursive("", recursive, dirs, fileInfoList);
     return fileInfoList;
 }

Ogre::StringVectorPtr yz::ogre::vfs::Archive::list(bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::StringVectorPtr fileList(new Ogre::StringVector());
     listRecursive("", recursive, dirs, fileList);
     return fileList;
 }

Ogre::StringVectorPtr yz::ogre::vfs::Archive::find(const Ogre::String& pattern, bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::StringVectorPtr fileList = list(recursive, dirs);
     Ogre::StringVectorPtr ret(new Ogre::StringVector());

     for (Ogre::StringVector::iterator it = fileList->begin(); it != fileList->end(); ++it) {
         if (Ogre::StringUtil::match(*it, pattern))
             ret->push_back(*it);
     }
     return ret;
 }

Ogre::FileInfoListPtr yz::ogre::vfs::Archive::findFileInfo(const Ogre::String& pattern, bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::FileInfoListPtr fileList = const_cast<yz::ogre::vfs::Archive*>(this)->listFileInfo(recursive, dirs);
     Ogre::FileInfoListPtr ret(new Ogre::FileInfoList());

     for (Ogre::FileInfoList::iterator it = fileList->begin(); it != fileList->end(); ++it) {
         if (Ogre::StringUtil::match(it->filename, pattern))
             ret->push_back(*it);
     }

     return ret;
 }
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

//
// OpenFlight loader for OpenSceneGraph
//
//  Copyright (C) 2005-2007  Brede Johansen
//

#include <assert.h>
#include <osg/Geode>
#include <osg/Geometry>
#include "Registry.h"
#include "Document.h"
#include "RecordInputStream.h"

namespace flt {

/** PushLevel
*/
class PushLevel : public Record
{
    public:

        PushLevel() {}

        META_Record(PushLevel)

        virtual void readRecord(RecordInputStream& /*in*/, Document& document)
        {
            document.pushLevel();
        }

    protected:

        virtual ~PushLevel() {}
};

RegisterRecordProxy<PushLevel> g_PushLevel(PUSH_LEVEL_OP);

/** PophLevel
*/
class PopLevel : public Record
{
    public:

        PopLevel() {}

        META_Record(PopLevel)

        virtual void read(RecordInputStream& /*in*/, Document& document)
        {
            // Finally call dispose() for primary with push, pop level pair.
            PrimaryRecord* primary = document.getTopOfLevelStack();
            if (primary)
            {
                primary->dispose(document);
            }

            document.popLevel();
        }

    protected:

        virtual ~PopLevel() {}
};

RegisterRecordProxy<PopLevel> g_PopLevel(POP_LEVEL_OP);

/** PushSubface
*/
class PushSubface : public Record
{
    public:

        PushSubface() {}

        META_Record(PushSubface)

        virtual void read(RecordInputStream& /*in*/, Document& document)
        {
            document.pushSubface();
        }

    protected:

        virtual ~PushSubface() {}
};

RegisterRecordProxy<PushSubface> g_PushSubface(PUSH_SUBFACE_OP);

/** PopSubface
*/
class PopSubface : public Record
{
    public:

        PopSubface() {}

        META_Record(PopSubface)

        virtual void read(RecordInputStream& /*in*/, Document& document)
        {
            document.popSubface();
        }

    protected:

        virtual ~PopSubface() {}
};

RegisterRecordProxy<PopSubface> g_PopSubface(POP_SUBFACE_OP);

/** PushExtension
*/
class PushExtension : public Record
{
    public:

        PushExtension() {}

        META_Record(PushExtension)

        virtual void read(RecordInputStream& in, Document& document)
        {
            readRecord(in,document);
            document.pushExtension();
        }

    protected:

        virtual ~PushExtension() {}
};

RegisterRecordProxy<PushExtension> g_PushExtension(PUSH_EXTENSION_OP);

/** PopExtension
*/
class PopExtension : public Record
{
    public:

        PopExtension() {}

        META_Record(PopExtension)

        virtual void read(RecordInputStream& in, Document& document)
        {
            readRecord(in,document);
            document.popExtension();
        }

    protected:

        virtual ~PopExtension() {}
};

RegisterRecordProxy<PopExtension> g_PopExtension(POP_EXTENSION_OP);

/** PushAttribute - Reserved subtree
*/
class PushAttribute : public Record
{
    public:

        PushAttribute() {}

        META_Record(PushAttribute)

        virtual void read(RecordInputStream& in, Document& document)
        {
            readRecord(in,document);
        }

    protected:

        virtual ~PushAttribute() {}
};

RegisterRecordProxy<PushAttribute> g_PushAttribute(PUSH_ATTRIBUTE_OP);

/** PopAttribute
*/
class PopAttribute : public Record
{
    public:

        PopAttribute() {}

        META_Record(PopAttribute)

        virtual void read(RecordInputStream& in, Document& document)
        {
            readRecord(in,document);
        }

    protected:

        virtual ~PopAttribute() {}
};

RegisterRecordProxy<PopAttribute> g_PopAttribute(POP_ATTRIBUTE_OP);

} // end namespace

<commit_msg>From Brede Johansen, "Here's a fix to the changes regarding the new dispose() function.  The last primary node inside a push-pop level would not get the dispose() call.  This would result in information from some ancillary records, like the matrix (transform), being lost.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

//
// OpenFlight loader for OpenSceneGraph
//
//  Copyright (C) 2005-2007  Brede Johansen
//

#include <assert.h>
#include <osg/Geode>
#include <osg/Geometry>
#include "Registry.h"
#include "Document.h"
#include "RecordInputStream.h"

namespace flt {

/** PushLevel
*/
class PushLevel : public Record
{
    public:

        PushLevel() {}

        META_Record(PushLevel)

        virtual void readRecord(RecordInputStream& /*in*/, Document& document)
        {
            document.pushLevel();
        }

    protected:

        virtual ~PushLevel() {}
};

RegisterRecordProxy<PushLevel> g_PushLevel(PUSH_LEVEL_OP);

/** PophLevel
*/
class PopLevel : public Record
{
    public:

        PopLevel() {}

        META_Record(PopLevel)

        virtual void read(RecordInputStream& /*in*/, Document& document)
        {
            PrimaryRecord* parentPrimary = document.getTopOfLevelStack();
            PrimaryRecord* currentPrimary = document.getCurrentPrimaryRecord();

            // Call dispose() for primary without push, pop level pair.
            if (currentPrimary && currentPrimary!=parentPrimary)
            {
                currentPrimary->dispose(document);
            }

            // Call dispose() for primary with push, pop level pair.
            if (parentPrimary)
            {
                parentPrimary->dispose(document);
            }

            document.popLevel();
        }

    protected:

        virtual ~PopLevel() {}
};

RegisterRecordProxy<PopLevel> g_PopLevel(POP_LEVEL_OP);

/** PushSubface
*/
class PushSubface : public Record
{
    public:

        PushSubface() {}

        META_Record(PushSubface)

        virtual void read(RecordInputStream& /*in*/, Document& document)
        {
            document.pushSubface();
        }

    protected:

        virtual ~PushSubface() {}
};

RegisterRecordProxy<PushSubface> g_PushSubface(PUSH_SUBFACE_OP);

/** PopSubface
*/
class PopSubface : public Record
{
    public:

        PopSubface() {}

        META_Record(PopSubface)

        virtual void read(RecordInputStream& /*in*/, Document& document)
        {
            document.popSubface();
        }

    protected:

        virtual ~PopSubface() {}
};

RegisterRecordProxy<PopSubface> g_PopSubface(POP_SUBFACE_OP);

/** PushExtension
*/
class PushExtension : public Record
{
    public:

        PushExtension() {}

        META_Record(PushExtension)

        virtual void read(RecordInputStream& in, Document& document)
        {
            readRecord(in,document);
            document.pushExtension();
        }

    protected:

        virtual ~PushExtension() {}
};

RegisterRecordProxy<PushExtension> g_PushExtension(PUSH_EXTENSION_OP);

/** PopExtension
*/
class PopExtension : public Record
{
    public:

        PopExtension() {}

        META_Record(PopExtension)

        virtual void read(RecordInputStream& in, Document& document)
        {
            readRecord(in,document);
            document.popExtension();
        }

    protected:

        virtual ~PopExtension() {}
};

RegisterRecordProxy<PopExtension> g_PopExtension(POP_EXTENSION_OP);

/** PushAttribute - Reserved subtree
*/
class PushAttribute : public Record
{
    public:

        PushAttribute() {}

        META_Record(PushAttribute)

        virtual void read(RecordInputStream& in, Document& document)
        {
            readRecord(in,document);
        }

    protected:

        virtual ~PushAttribute() {}
};

RegisterRecordProxy<PushAttribute> g_PushAttribute(PUSH_ATTRIBUTE_OP);

/** PopAttribute
*/
class PopAttribute : public Record
{
    public:

        PopAttribute() {}

        META_Record(PopAttribute)

        virtual void read(RecordInputStream& in, Document& document)
        {
            readRecord(in,document);
        }

    protected:

        virtual ~PopAttribute() {}
};

RegisterRecordProxy<PopAttribute> g_PopAttribute(POP_ATTRIBUTE_OP);

} // end namespace

<|endoftext|>


<commit_before>/*************************************************************************/
/*  string_name.cpp                                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "gdnative/string_name.h"

#include "core/string_name.h"
#include "core/ustring.h"

#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

static_assert(sizeof(godot_string_name) == sizeof(StringName), "StringName size mismatch");

void GDAPI godot_string_name_new(godot_string_name *r_dest, const godot_string *p_name) {
	StringName *dest = (StringName *)r_dest;
	const String *name = (const String *)p_name;
	memnew_placement(dest, StringName(*name));
}

void GDAPI godot_string_name_new_data(godot_string_name *r_dest, const char *p_name) {
	StringName *dest = (StringName *)r_dest;
	memnew_placement(dest, StringName(p_name));
}

godot_string GDAPI godot_string_name_get_name(const godot_string_name *p_self) {
	godot_string ret;
	const StringName *self = (const StringName *)p_self;
	memnew_placement(&ret, String(*self));
	return ret;
}

uint32_t GDAPI godot_string_name_get_hash(const godot_string_name *p_self) {
	const StringName *self = (const StringName *)p_self;
	return self->hash();
}

const void GDAPI *godot_string_name_get_data_unique_pointer(const godot_string_name *p_self) {
	const StringName *self = (const StringName *)p_self;
	return self->data_unique_pointer();
}

godot_bool GDAPI godot_string_name_operator_equal(const godot_string_name *p_self, const godot_string_name *p_other) {
	const StringName *self = (const StringName *)p_self;
	const StringName *other = (const StringName *)p_other;
	return self == other;
}

godot_bool GDAPI godot_string_name_operator_less(const godot_string_name *p_self, const godot_string_name *p_other) {
	const StringName *self = (const StringName *)p_self;
	const StringName *other = (const StringName *)p_other;
	return self < other;
}

void GDAPI godot_string_name_destroy(godot_string_name *p_self) {
	StringName *self = (StringName *)p_self;
	self->~StringName();
}

#ifdef __cplusplus
}
#endif
<commit_msg>GDNative: fix StringName equal and less operators<commit_after>/*************************************************************************/
/*  string_name.cpp                                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "gdnative/string_name.h"

#include "core/string_name.h"
#include "core/ustring.h"

#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

static_assert(sizeof(godot_string_name) == sizeof(StringName), "StringName size mismatch");

void GDAPI godot_string_name_new(godot_string_name *r_dest, const godot_string *p_name) {
	StringName *dest = (StringName *)r_dest;
	const String *name = (const String *)p_name;
	memnew_placement(dest, StringName(*name));
}

void GDAPI godot_string_name_new_data(godot_string_name *r_dest, const char *p_name) {
	StringName *dest = (StringName *)r_dest;
	memnew_placement(dest, StringName(p_name));
}

godot_string GDAPI godot_string_name_get_name(const godot_string_name *p_self) {
	godot_string ret;
	const StringName *self = (const StringName *)p_self;
	memnew_placement(&ret, String(*self));
	return ret;
}

uint32_t GDAPI godot_string_name_get_hash(const godot_string_name *p_self) {
	const StringName *self = (const StringName *)p_self;
	return self->hash();
}

const void GDAPI *godot_string_name_get_data_unique_pointer(const godot_string_name *p_self) {
	const StringName *self = (const StringName *)p_self;
	return self->data_unique_pointer();
}

godot_bool GDAPI godot_string_name_operator_equal(const godot_string_name *p_self, const godot_string_name *p_other) {
	const StringName *self = (const StringName *)p_self;
	const StringName *other = (const StringName *)p_other;
	return *self == *other;
}

godot_bool GDAPI godot_string_name_operator_less(const godot_string_name *p_self, const godot_string_name *p_other) {
	const StringName *self = (const StringName *)p_self;
	const StringName *other = (const StringName *)p_other;
	return *self < *other;
}

void GDAPI godot_string_name_destroy(godot_string_name *p_self) {
	StringName *self = (StringName *)p_self;
	self->~StringName();
}

#ifdef __cplusplus
}
#endif
<|endoftext|>