<commit_before>#include "entity.hpp"
#include "universe.hpp"
#include "code/ylikuutio/config/setting_master.hpp"

// Include standard headers
#include <iostream>      // std::cout, std::cin, std::cerr
#include <limits>        // std::numeric_limits
#include <memory>        // std::make_shared, std::shared_ptr
#include <string>        // std::string
#include <unordered_map> // std::unordered_map

namespace yli
{
    namespace ontology
    {
        Entity::Entity(yli::ontology::Universe* const universe)
        {
            // constructor.
            this->childID = std::numeric_limits<std::size_t>::max();
            this->universe = universe;
            this->prerender_callback = nullptr;
            this->postrender_callback = nullptr;
            this->setting_master = std::make_shared<yli::config::SettingMaster>(this);
            this->can_be_erased = false;
        }

        Entity::~Entity()
        {
            // destructor.
            std::cout << "Entity destructor called.\n";

            if (this->name.empty())
            {
                std::cerr << "ERROR: `Entity::~Entity`: `this->name` is empty.\n";
                return;
            }

            if (this->universe == nullptr)
            {
                std::cerr << "ERROR: `Entity::~Entity`: `this->universe` is `nullptr`.\n";
                return;
            }

            // OK, this `Entity` had a name, so it's name shall be erased.
            this->universe->erase_entity(this->name);
        }

        std::size_t Entity::get_childID() const
        {
            return this->childID;
        }

        std::string Entity::get_type() const
        {
            return this->type;
        }

        bool Entity::get_can_be_erased() const
        {
            return this->can_be_erased;
        }

        yli::ontology::Universe* Entity::get_universe() const
        {
            return this->universe;
        }

        yli::config::SettingMaster* Entity::get_setting_master() const
        {
            return this->setting_master.get();
        }

        void Entity::prerender() const
        {
            // requirements:
            // `this->prerender_callback` must not be `nullptr`.
            // `this->universe` must not be `nullptr`.
            // `this->universe->setting_master` must not be `nullptr`.

            if (this->prerender_callback != nullptr &&
                    this->universe != nullptr &&
                    this->universe->setting_master != nullptr)
            {
                this->prerender_callback(this->universe, this->universe->setting_master.get());
            }
        }

        void Entity::postrender() const
        {
            // requirements:
            // `this->postrender_callback` must not be `nullptr`.
            // `this->universe` must not be `nullptr`.
            // `this->universe->setting_master` must not be `nullptr`.

            if (this->postrender_callback != nullptr &&
                    this->universe != nullptr &&
                    this->universe->setting_master != nullptr)
            {
                this->postrender_callback(this->universe, this->universe->setting_master.get());
            }
        }

        void Entity::set_name(const std::string& name)
        {
            // requirements:
            // `this->universe` must not be `nullptr`.
            // `name` must not be already in use.

            if (this->universe == nullptr)
            {
                return;
            }

            if (this->universe->is_entity(name))
            {
                // The name is already in use.
                return;
            }

            this->name = name;
            this->universe->add_entity(name, this);
        }
    }
}
<commit_msg>`Entity::get_setting_master`: check `setting_master` for `nullptr`.<commit_after>#include "entity.hpp"
#include "universe.hpp"
#include "code/ylikuutio/config/setting_master.hpp"

// Include standard headers
#include <iostream>      // std::cout, std::cin, std::cerr
#include <limits>        // std::numeric_limits
#include <memory>        // std::make_shared, std::shared_ptr
#include <string>        // std::string
#include <unordered_map> // std::unordered_map

namespace yli
{
    namespace ontology
    {
        Entity::Entity(yli::ontology::Universe* const universe)
        {
            // constructor.
            this->childID = std::numeric_limits<std::size_t>::max();
            this->universe = universe;
            this->prerender_callback = nullptr;
            this->postrender_callback = nullptr;
            this->setting_master = std::make_shared<yli::config::SettingMaster>(this);
            this->can_be_erased = false;
        }

        Entity::~Entity()
        {
            // destructor.
            std::cout << "Entity destructor called.\n";

            if (this->name.empty())
            {
                std::cerr << "ERROR: `Entity::~Entity`: `this->name` is empty.\n";
                return;
            }

            if (this->universe == nullptr)
            {
                std::cerr << "ERROR: `Entity::~Entity`: `this->universe` is `nullptr`.\n";
                return;
            }

            // OK, this `Entity` had a name, so it's name shall be erased.
            this->universe->erase_entity(this->name);
        }

        std::size_t Entity::get_childID() const
        {
            return this->childID;
        }

        std::string Entity::get_type() const
        {
            return this->type;
        }

        bool Entity::get_can_be_erased() const
        {
            return this->can_be_erased;
        }

        yli::ontology::Universe* Entity::get_universe() const
        {
            return this->universe;
        }

        yli::config::SettingMaster* Entity::get_setting_master() const
        {
            if (this->setting_master == nullptr)
            {
                std::cerr << "ERROR: `Entity::get_setting_master`: `this->setting_master` is `nullptr`.\n";
                return nullptr;
            }

            return this->setting_master.get();
        }

        void Entity::prerender() const
        {
            // requirements:
            // `this->prerender_callback` must not be `nullptr`.
            // `this->universe` must not be `nullptr`.
            // `this->universe->setting_master` must not be `nullptr`.

            if (this->prerender_callback != nullptr &&
                    this->universe != nullptr &&
                    this->universe->setting_master != nullptr)
            {
                this->prerender_callback(this->universe, this->universe->setting_master.get());
            }
        }

        void Entity::postrender() const
        {
            // requirements:
            // `this->postrender_callback` must not be `nullptr`.
            // `this->universe` must not be `nullptr`.
            // `this->universe->setting_master` must not be `nullptr`.

            if (this->postrender_callback != nullptr &&
                    this->universe != nullptr &&
                    this->universe->setting_master != nullptr)
            {
                this->postrender_callback(this->universe, this->universe->setting_master.get());
            }
        }

        void Entity::set_name(const std::string& name)
        {
            // requirements:
            // `this->universe` must not be `nullptr`.
            // `name` must not be already in use.

            if (this->universe == nullptr)
            {
                return;
            }

            if (this->universe->is_entity(name))
            {
                // The name is already in use.
                return;
            }

            this->name = name;
            this->universe->add_entity(name, this);
        }
    }
}
<|endoftext|>


<commit_before>#include <boost/python.hpp>

#include <sm/PropertyTree.hpp>
#include <sm/value_store/ValueStore.hpp>
#include <functional>

void exportValueStoreRef()
{
  using namespace boost::python;
  using namespace sm::value_store;

  /// brief create a value store reference pointing to a fresh empty value store (based on @see sm::BoostPropertyTree)
  class_<ValueStoreRef>("ValueStoreRef", init<>())
    .def(init<ValueStoreRef>())
    .def(init<ValueStore::SharedPtr>())
    .def(init<sm::PropertyTree>())
    /// ValueStoreRef getChild(const std::string & key)
    .def("getChild", &ValueStoreRef::getChild)
    /// sm::ConstPropertyTree asPropertyTree() const
    .def("asPropertyTree", &ValueStoreRef::asPropertyTree)
    /// brief Create a ValueStoreRef to a BoostPropertyTree loaded from file using @see sm::BoostPropertyTree::load .
    /// static ValueStoreRef fromFile(const std::string & path)
    .def("fromFile", &ValueStoreRef::fromFile).staticmethod("fromFile")
    /// brief Create a ValueStoreRef to a BoostPropertyTree loaded from file using @see sm::BoostPropertyTree::load .
    /// static ValueStoreRef fromFile(const std::string & path)
    .def("fromString", &ValueStoreRef::fromString).staticmethod("fromString")
    /// ValueHandle<bool> getBool(const std::string & path, boost::optional<bool> def = boost::optional<bool>()) const;
    .def("getBool", +[](ValueStoreRef * vs, const std::string & path){return vs->getBool(path).get();})
    .def("getBool", +[](ValueStoreRef * vs, const std::string & path, bool defaultValue){return vs->getBool(path, defaultValue).get();})
    /// ValueHandle<int> getInt(const std::string & path, boost::optional<int> def = boost::optional<int>()) const;
    .def("getInt", +[](ValueStoreRef * vs, const std::string & path){return vs->getInt(path).get();})
    .def("getInt", +[](ValueStoreRef * vs, const std::string & path, int defaultValue){return vs->getInt(path, defaultValue).get();})
    /// ValueHandle<double> getDouble(const std::string & path, boost::optional<double> def = boost::optional<double>()) const;
    .def("getDouble", +[](ValueStoreRef * vs, const std::string & path){return vs->getDouble(path).get();})
    .def("getDouble", +[](ValueStoreRef * vs, const std::string & path, double defaultValue){return vs->getDouble(path, defaultValue).get();})
    /// ValueHandle<std::string> getString(const std::string & path, boost::optional<std::string> def = boost::optional<std::string>()) const;
    .def("getString", +[](ValueStoreRef * vs, const std::string & path){return vs->getString(path).get();})
    .def("getString", +[](ValueStoreRef * vs, const std::string & path, const std::string & defaultValue){return vs->getString(path, defaultValue).get();})
  ;
}
<commit_msg>additional exports required for conversion scripts from oomact<commit_after>#include <boost/python.hpp>

#include <sm/PropertyTree.hpp>
#include <sm/value_store/ValueStore.hpp>
#include <functional>

void exportValueStoreRef()
{
  using namespace boost::python;
  using namespace sm::value_store;

  /// brief create a value store reference pointing to a fresh empty value store (based on @see sm::BoostPropertyTree)
  class_<ValueStoreRef>("ValueStoreRef", init<>())
    .def(init<ValueStoreRef>())
    .def(init<ValueStore::SharedPtr>())
    .def(init<sm::PropertyTree>())
    /// ValueStoreRef getChild(const std::string & key)
    .def("getChild", &ValueStoreRef::getChild)
    /// sm::ConstPropertyTree asPropertyTree() const
    .def("asPropertyTree", &ValueStoreRef::asPropertyTree)
    /// brief Create a ValueStoreRef to a BoostPropertyTree loaded from file using @see sm::BoostPropertyTree::load .
    /// static ValueStoreRef fromFile(const std::string & path)
    .def("fromFile", &ValueStoreRef::fromFile).staticmethod("fromFile")
    /// brief Create a ValueStoreRef to a BoostPropertyTree loaded from file using @see sm::BoostPropertyTree::load .
    /// static ValueStoreRef fromFile(const std::string & path)
    .def("fromString", &ValueStoreRef::fromString).staticmethod("fromString")
    /// ValueHandle<bool> getBool(const std::string & path, boost::optional<bool> def = boost::optional<bool>()) const;
    .def("getBool", +[](ValueStoreRef * vs, const std::string & path){return vs->getBool(path).get();})
    .def("getBool", +[](ValueStoreRef * vs, const std::string & path, bool defaultValue){return vs->getBool(path, defaultValue).get();})
    /// ValueHandle<int> getInt(const std::string & path, boost::optional<int> def = boost::optional<int>()) const;
    .def("getInt", +[](ValueStoreRef * vs, const std::string & path){return vs->getInt(path).get();})
    .def("getInt", +[](ValueStoreRef * vs, const std::string & path, int defaultValue){return vs->getInt(path, defaultValue).get();})
    /// ValueHandle<double> getDouble(const std::string & path, boost::optional<double> def = boost::optional<double>()) const;
    .def("getDouble", +[](ValueStoreRef * vs, const std::string & path){return vs->getDouble(path).get();})
    .def("getDouble", +[](ValueStoreRef * vs, const std::string & path, double defaultValue){return vs->getDouble(path, defaultValue).get();})
    /// ValueHandle<std::string> getString(const std::string & path, boost::optional<std::string> def = boost::optional<std::string>()) const;
    .def("getString", +[](ValueStoreRef * vs, const std::string & path){return vs->getString(path).get();})
    .def("getString", +[](ValueStoreRef * vs, const std::string & path, const std::string & defaultValue){return vs->getString(path, defaultValue).get();})
    /// ValueHandle<bool> getBool(const std::string & path).update(bool newVal) const;
    .def("setBool", +[](ValueStoreRef * vs, const std::string & path, bool newVal){vs->getBool(path).update(newVal);})
    /// ValueHandle<int> getInt(const std::string & path).update(int newVal) const;
    .def("setInt", +[](ValueStoreRef * vs, const std::string & path, int newVal){vs->getInt(path).update(newVal);})
    /// ValueHandle<double> getDouble(const std::string & path).update(double newVal) const;
    .def("setDouble", +[](ValueStoreRef * vs, const std::string & path, double newVal){vs->getDouble(path).update(newVal);})
    /// ValueHandle<std::string> getString(const std::string & path).update(std::string newVal) const;
    .def("setString", +[](ValueStoreRef * vs, const std::string & path, const std::string& newVal){vs->getString(path).update(newVal);})
    /// void saveTo(const std::string & path) const;
    .def("saveTo", &ValueStoreRef::saveTo);
  ;
}
<|endoftext|>


<commit_before>//
//  main.m
//  ogam-january
//
//  Created by Steve Richey on 1/25/15.
//  Copyright (c) 2015 stvr. All rights reserved.
//

#import <iostream>
#import <SDL2/SDL.h>
#import <SDL2_image/SDL_image.h>
#import <SDL2_ttf/SDL_ttf.h>
#import <SDL2_mixer/SDL_mixer.h>

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
#define TILE_SIZE 32
#define MOVE_SPEED 2
#define DOUBLE_MOVE_SPEED MOVE_SPEED * 2
#define ANGLE_SPEED sqrt(DOUBLE_MOVE_SPEED)
#define FONT_SIZE 32
#define FONT_OFFSET 16
#define SCORE_PREFIX "Score "
#define ENTITY_SIZE 32
#define SCORE_INCREMENT_LIMIT 10

// log anything to the console
void log(const std::string &message) {
    std::cout << message << std::endl;
}

// log anything to the console, appends the SDL error message
void log_error(const std::string &message) {
    log(message + SDL_GetError());
}

// load a texture from a provided file path
SDL_Texture* load_texture(const std::string filename, SDL_Renderer *renderer) {
    SDL_Texture *texture = IMG_LoadTexture(renderer, filename.c_str());

    if (texture == nullptr) {
        log_error("IMG_LoadTexture error");
    }

    return texture;
}

TTF_Font* load_font(const std::string file_name, int font_size) {
    TTF_Font *font = TTF_OpenFont(file_name.c_str(), font_size);

    if (font == nullptr) {
        log_error("TTF open font error");
    }

    return font;
}

// render a texture at (x,y) with size w x h
void render_texture(SDL_Texture *texture, SDL_Renderer *renderer, int x, int y, int w, int h) {
    // create a target rect
    SDL_Rect dest;
    dest.x = x;
    dest.y = y;
    dest.w = w;
    dest.h = h;

    // really render!
    SDL_RenderCopy(renderer, texture, nullptr, &dest);
}

// render a texture at (x,y) with the texture's default width and height
void render_texture(SDL_Texture *texture, SDL_Renderer *renderer, int x, int y) {
    // create a destination rectangle
    int w;
    int h;

    // get width and height from texture
    SDL_QueryTexture(texture, nullptr, nullptr, &w, &h);

    // render!
    render_texture(texture, renderer, x, y, w, h);
}

void render_text(const std::string &message, TTF_Font *font, SDL_Color color, SDL_Renderer *renderer, int x, int y) {
    // render text to a surface
    SDL_Surface *surface = TTF_RenderText_Solid(font, message.c_str(), color);

    if (surface == nullptr){
        log_error("TTF_RenderText error");
    }

    SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface);

    if (texture == nullptr){
        log_error("CreateTexture error");
    }

    // clean up
    SDL_FreeSurface(surface);

    render_texture(texture, renderer, x, y);
}

// entry point
int main(int argc, const char * argv[]) {
    // initialize SDL
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        log_error("SDL Init Error");
        return 1;
    }

    // initialize SDL_Image
    if ((IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) != IMG_INIT_PNG){
        log_error("IMG_Init error");
        SDL_Quit();
        return 1;
    }

    // initialize SDL_TTF
    if (TTF_Init() != 0) {
        log_error("TTF_Init error");
        IMG_Quit();
        SDL_Quit();
        return 1;
    }

    // initialize SDL_Mixer
    if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096) != 0) {
        log_error("Mix_OpenAudio error!");
        IMG_Quit();
        TTF_Quit();
        SDL_Quit();
        return 1;
    }

    // create a window
    SDL_Window *window = SDL_CreateWindow("ogam-january", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

    // verify window
    if (window == nullptr){
        log_error("SDL Create Window Error");
        IMG_Quit();
        TTF_Quit();
        Mix_Quit();
        SDL_Quit();
        return 1;
    }

    // create a rendering context
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

    // verify rendering context
    if (renderer == nullptr){
        log_error("SDL Create Renderer Error");
        SDL_DestroyWindow(window);
        IMG_Quit();
        TTF_Quit();
        Mix_Quit();
        SDL_Quit();
        return 1;
    }

    // load textures
    std::string player_img_path = "Resources/player.png";
    SDL_Texture *player = load_texture(player_img_path, renderer);

    std::string bg_img_path = "Resources/bg.png";
    SDL_Texture *background = load_texture(bg_img_path, renderer);

    std::string enemy_img_path = "Resources/enemy.png";
    SDL_Texture *enemy = load_texture(enemy_img_path, renderer);

    if (player == nullptr || background == nullptr || enemy == nullptr) {
        log_error("Load texture error!");
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        IMG_Quit();
        TTF_Quit();
        SDL_Quit();
        return 1;
    }

    // score tracking
    int score = 0;
    int score_counter = 0;
    std::string score_string = "";

    // load font
    std::string font_path = "Resources/ivory.ttf";
    TTF_Font *game_font = load_font(font_path, FONT_SIZE);
    SDL_Color font_color = {255, 0, 255, 255};

    if (game_font == nullptr) {
        log_error("Font load error");
        SDL_DestroyTexture(player);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(enemy);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        IMG_Quit();
        TTF_Quit();
        SDL_Quit();
        return 1;
    }

    int player_w, player_h;
    SDL_QueryTexture(player, nullptr, nullptr, &player_w, &player_h);
    int player_x = (SCREEN_WIDTH - player_w) / 2;
    int player_y = (SCREEN_HEIGHT - player_h) / 2;

    // enemy position
    int enemy_x = 0;
    int enemy_y = 0;
    int enemy_move_x = -1;
    int enemy_move_y = -1;
    int enemy_move_x_speed = 1;
    int enemy_move_y_speed = 1;

    // calculate the number of tiles to fill the screen
    int xTiles = SCREEN_WIDTH / TILE_SIZE;
    int yTiles = SCREEN_HEIGHT / TILE_SIZE;

    // bg position values
    int bg_x = 0;
    int bg_y = 0;

    // create event for input
    SDL_Event event;
    bool quit = false;

    // input tracking
    bool down_pressed  = false;
    bool up_pressed    = false;
    bool right_pressed = false;
    bool left_pressed  = false;

    // MAIN GAME LOOP YO
    while (!quit) {
        // use input to set _pressed flags
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }

            if (event.type == SDL_KEYDOWN) {
                switch (event.key.keysym.sym) {
                    case SDLK_ESCAPE:
                        quit = true;
                        break;
                    case SDLK_DOWN:
                        down_pressed = true;
                        break;
                    case SDLK_UP:
                        up_pressed = true;
                        break;
                    case SDLK_RIGHT:
                        right_pressed = true;
                        break;
                    case SDLK_LEFT:
                        left_pressed = true;
                        break;
                }
            }

            if (event.type == SDL_KEYUP) {
                switch (event.key.keysym.sym) {
                    case SDLK_DOWN:
                        down_pressed = false;
                        break;
                    case SDLK_UP:
                        up_pressed = false;
                        break;
                    case SDLK_RIGHT:
                        right_pressed = false;
                        break;
                    case SDLK_LEFT:
                        left_pressed = false;
                        break;
                }
            }
        }

        // pressed flag processing
        if (down_pressed && right_pressed) {
            player_x += ANGLE_SPEED;
            player_y += ANGLE_SPEED;
        } else if (down_pressed && left_pressed) {
            player_x -= ANGLE_SPEED;
            player_y += ANGLE_SPEED;
        } else if (up_pressed && right_pressed) {
            player_x += ANGLE_SPEED;
            player_y -= ANGLE_SPEED;
        } else if (up_pressed && left_pressed) {
            player_x -= ANGLE_SPEED;
            player_y -= ANGLE_SPEED;
        } else if (down_pressed) {
            player_y += MOVE_SPEED;
        } else if (up_pressed) {
            player_y -= MOVE_SPEED;
        } else if (right_pressed) {
            player_x += MOVE_SPEED;
        } else if (left_pressed) {
            player_x -= MOVE_SPEED;
        }

        // player bounds checking
        if (player_x < 0) {
            player_x = 0;
        }

        if (player_x > SCREEN_WIDTH - player_w) {
            player_x = SCREEN_WIDTH - player_w;
        }

        if (player_y < 0) {
            player_y = 0;
        }

        if (player_y > SCREEN_HEIGHT - player_h) {
            player_y = SCREEN_HEIGHT - player_h;
        }

        // enemy positioning
        enemy_x += enemy_move_x * enemy_move_x_speed;
        enemy_y += enemy_move_y * enemy_move_y_speed;

        if (enemy_x < 0) {
            enemy_move_x = 1;
            enemy_move_x_speed++;
        }

        if (enemy_x > SCREEN_WIDTH - ENTITY_SIZE) {
            enemy_move_x = -1;
            enemy_move_x_speed++;
        }

        if (enemy_y < 0) {
            enemy_move_y = 1;
            enemy_move_y_speed++;
        }

        if (enemy_y > SCREEN_HEIGHT - ENTITY_SIZE) {
            enemy_move_y = -1;
            enemy_move_y_speed++;
        }

        // update score
        score_counter++;

        if (score_counter > SCORE_INCREMENT_LIMIT) {
            score_counter = 0;
            score++;
        }

        // clear renderer
        SDL_RenderClear(renderer);

        // render tiles to cover screen
        for (int i = 0; i < xTiles * yTiles; i++) {
            bg_x = i % xTiles;
            bg_y = i / xTiles;
            render_texture(background, renderer, bg_x * TILE_SIZE, bg_y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
        }

        // draw the enemy
        render_texture(enemy, renderer, enemy_x, enemy_y);

        // draw the player
        render_texture(player, renderer, player_x, player_y);

        // draw the text
        score_string = SCORE_PREFIX + std::to_string(score);
        render_text(score_string, game_font, font_color, renderer, FONT_OFFSET, FONT_OFFSET);

        // lose state checking
        if (player_x + ENTITY_SIZE > enemy_x) {
            if (player_y + ENTITY_SIZE > enemy_y) {
                if (player_x < enemy_x + ENTITY_SIZE) {
                    if (player_y < enemy_y + ENTITY_SIZE) {
                        abort();
                    }
                }
            }
        }

        // render things!
        SDL_RenderPresent(renderer);
    }

    // close down game
    TTF_CloseFont(game_font);
    SDL_DestroyTexture(enemy);
    SDL_DestroyTexture(player);
    SDL_DestroyTexture(background);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    TTF_Quit();
    IMG_Quit();
    SDL_Quit();

    return 0;
}<commit_msg>load the bounce sound<commit_after>//
//  main.m
//  ogam-january
//
//  Created by Steve Richey on 1/25/15.
//  Copyright (c) 2015 stvr. All rights reserved.
//

#import <iostream>
#import <SDL2/SDL.h>
#import <SDL2_image/SDL_image.h>
#import <SDL2_ttf/SDL_ttf.h>
#import <SDL2_mixer/SDL_mixer.h>

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
#define TILE_SIZE 32
#define MOVE_SPEED 2
#define DOUBLE_MOVE_SPEED MOVE_SPEED * 2
#define ANGLE_SPEED sqrt(DOUBLE_MOVE_SPEED)
#define FONT_SIZE 32
#define FONT_OFFSET 16
#define SCORE_PREFIX "Score "
#define ENTITY_SIZE 32
#define SCORE_INCREMENT_LIMIT 10

// log anything to the console
void log(const std::string &message) {
    std::cout << message << std::endl;
}

// log anything to the console, appends the SDL error message
void log_error(const std::string &message) {
    log(message + SDL_GetError());
}

// load a texture from a provided file path
SDL_Texture* load_texture(const std::string filename, SDL_Renderer *renderer) {
    SDL_Texture *texture = IMG_LoadTexture(renderer, filename.c_str());

    if (texture == nullptr) {
        log_error("IMG_LoadTexture error");
    }

    return texture;
}

TTF_Font* load_font(const std::string file_name, int font_size) {
    TTF_Font *font = TTF_OpenFont(file_name.c_str(), font_size);

    if (font == nullptr) {
        log_error("TTF open font error");
    }

    return font;
}

// render a texture at (x,y) with size w x h
void render_texture(SDL_Texture *texture, SDL_Renderer *renderer, int x, int y, int w, int h) {
    // create a target rect
    SDL_Rect dest;
    dest.x = x;
    dest.y = y;
    dest.w = w;
    dest.h = h;

    // really render!
    SDL_RenderCopy(renderer, texture, nullptr, &dest);
}

// render a texture at (x,y) with the texture's default width and height
void render_texture(SDL_Texture *texture, SDL_Renderer *renderer, int x, int y) {
    // create a destination rectangle
    int w;
    int h;

    // get width and height from texture
    SDL_QueryTexture(texture, nullptr, nullptr, &w, &h);

    // render!
    render_texture(texture, renderer, x, y, w, h);
}

void render_text(const std::string &message, TTF_Font *font, SDL_Color color, SDL_Renderer *renderer, int x, int y) {
    // render text to a surface
    SDL_Surface *surface = TTF_RenderText_Solid(font, message.c_str(), color);

    if (surface == nullptr){
        log_error("TTF_RenderText error");
    }

    SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface);

    if (texture == nullptr){
        log_error("CreateTexture error");
    }

    // clean up
    SDL_FreeSurface(surface);

    render_texture(texture, renderer, x, y);
}

// entry point
int main(int argc, const char * argv[]) {
    // initialize SDL
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        log_error("SDL Init Error");
        return 1;
    }

    // initialize SDL_Image
    if ((IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) != IMG_INIT_PNG){
        log_error("IMG_Init error");
        SDL_Quit();
        return 1;
    }

    // initialize SDL_TTF
    if (TTF_Init() != 0) {
        log_error("TTF_Init error");
        IMG_Quit();
        SDL_Quit();
        return 1;
    }

    // initialize SDL_Mixer
    if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096) != 0) {
        log_error("Mix_OpenAudio error!");
        IMG_Quit();
        TTF_Quit();
        SDL_Quit();
        return 1;
    }

    // create a window
    SDL_Window *window = SDL_CreateWindow("ogam-january", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

    // verify window
    if (window == nullptr){
        log_error("SDL Create Window Error");
        IMG_Quit();
        TTF_Quit();
        Mix_Quit();
        SDL_Quit();
        return 1;
    }

    // create a rendering context
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

    // verify rendering context
    if (renderer == nullptr){
        log_error("SDL Create Renderer Error");
        SDL_DestroyWindow(window);
        IMG_Quit();
        TTF_Quit();
        Mix_Quit();
        SDL_Quit();
        return 1;
    }

    // load textures
    std::string player_img_path = "Resources/player.png";
    SDL_Texture *player = load_texture(player_img_path, renderer);

    std::string bg_img_path = "Resources/bg.png";
    SDL_Texture *background = load_texture(bg_img_path, renderer);

    std::string enemy_img_path = "Resources/enemy.png";
    SDL_Texture *enemy = load_texture(enemy_img_path, renderer);

    if (player == nullptr || background == nullptr || enemy == nullptr) {
        log_error("Load texture error!");
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        IMG_Quit();
        TTF_Quit();
        SDL_Quit();
        return 1;
    }

    // score tracking
    int score = 0;
    int score_counter = 0;
    std::string score_string = "";

    // load font
    std::string font_path = "Resources/ivory.ttf";
    TTF_Font *game_font = load_font(font_path, FONT_SIZE);
    SDL_Color font_color = {255, 0, 255, 255};

    if (game_font == nullptr) {
        log_error("Font load error");
        SDL_DestroyTexture(player);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(enemy);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        IMG_Quit();
        TTF_Quit();
        SDL_Quit();
        return 1;
    }

    int player_w, player_h;
    SDL_QueryTexture(player, nullptr, nullptr, &player_w, &player_h);
    int player_x = (SCREEN_WIDTH - player_w) / 2;
    int player_y = (SCREEN_HEIGHT - player_h) / 2;

    // enemy position
    int enemy_x = 0;
    int enemy_y = 0;
    int enemy_move_x = -1;
    int enemy_move_y = -1;
    int enemy_move_x_speed = 1;
    int enemy_move_y_speed = 1;
    Mix_Chunk *bounce = Mix_LoadWAV("Resources/bounce.wav");

    //if (music == nullptr || bounce == nullptr) {
    if (bounce == nullptr) {
        log_error("Sound load error");
        TTF_CloseFont(game_font);
        SDL_DestroyTexture(player);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(enemy);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        Mix_CloseAudio();
        IMG_Quit();
        TTF_Quit();
        SDL_Quit();
        return 1;
    }

    // calculate the number of tiles to fill the screen
    int xTiles = SCREEN_WIDTH / TILE_SIZE;
    int yTiles = SCREEN_HEIGHT / TILE_SIZE;

    // bg position values
    int bg_x = 0;
    int bg_y = 0;

    // create event for input
    SDL_Event event;
    bool quit = false;

    // input tracking
    bool down_pressed  = false;
    bool up_pressed    = false;
    bool right_pressed = false;
    bool left_pressed  = false;

    // MAIN GAME LOOP YO
    while (!quit) {
        // use input to set _pressed flags
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }

            if (event.type == SDL_KEYDOWN) {
                switch (event.key.keysym.sym) {
                    case SDLK_ESCAPE:
                        quit = true;
                        break;
                    case SDLK_DOWN:
                        down_pressed = true;
                        break;
                    case SDLK_UP:
                        up_pressed = true;
                        break;
                    case SDLK_RIGHT:
                        right_pressed = true;
                        break;
                    case SDLK_LEFT:
                        left_pressed = true;
                        break;
                }
            }

            if (event.type == SDL_KEYUP) {
                switch (event.key.keysym.sym) {
                    case SDLK_DOWN:
                        down_pressed = false;
                        break;
                    case SDLK_UP:
                        up_pressed = false;
                        break;
                    case SDLK_RIGHT:
                        right_pressed = false;
                        break;
                    case SDLK_LEFT:
                        left_pressed = false;
                        break;
                }
            }
        }

        // pressed flag processing
        if (down_pressed && right_pressed) {
            player_x += ANGLE_SPEED;
            player_y += ANGLE_SPEED;
        } else if (down_pressed && left_pressed) {
            player_x -= ANGLE_SPEED;
            player_y += ANGLE_SPEED;
        } else if (up_pressed && right_pressed) {
            player_x += ANGLE_SPEED;
            player_y -= ANGLE_SPEED;
        } else if (up_pressed && left_pressed) {
            player_x -= ANGLE_SPEED;
            player_y -= ANGLE_SPEED;
        } else if (down_pressed) {
            player_y += MOVE_SPEED;
        } else if (up_pressed) {
            player_y -= MOVE_SPEED;
        } else if (right_pressed) {
            player_x += MOVE_SPEED;
        } else if (left_pressed) {
            player_x -= MOVE_SPEED;
        }

        // player bounds checking
        if (player_x < 0) {
            player_x = 0;
        }

        if (player_x > SCREEN_WIDTH - player_w) {
            player_x = SCREEN_WIDTH - player_w;
        }

        if (player_y < 0) {
            player_y = 0;
        }

        if (player_y > SCREEN_HEIGHT - player_h) {
            player_y = SCREEN_HEIGHT - player_h;
        }

        // enemy positioning
        enemy_x += enemy_move_x * enemy_move_x_speed;
        enemy_y += enemy_move_y * enemy_move_y_speed;

        if (enemy_x < 0) {
            enemy_move_x = 1;
            enemy_move_x_speed++;
        }

        if (enemy_x > SCREEN_WIDTH - ENTITY_SIZE) {
            enemy_move_x = -1;
            enemy_move_x_speed++;
        }

        if (enemy_y < 0) {
            enemy_move_y = 1;
            enemy_move_y_speed++;
        }

        if (enemy_y > SCREEN_HEIGHT - ENTITY_SIZE) {
            enemy_move_y = -1;
            enemy_move_y_speed++;
        }

        // update score
        score_counter++;

        if (score_counter > SCORE_INCREMENT_LIMIT) {
            score_counter = 0;
            score++;
        }

        // clear renderer
        SDL_RenderClear(renderer);

        // render tiles to cover screen
        for (int i = 0; i < xTiles * yTiles; i++) {
            bg_x = i % xTiles;
            bg_y = i / xTiles;
            render_texture(background, renderer, bg_x * TILE_SIZE, bg_y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
        }

        // draw the enemy
        render_texture(enemy, renderer, enemy_x, enemy_y);

        // draw the player
        render_texture(player, renderer, player_x, player_y);

        // draw the text
        score_string = SCORE_PREFIX + std::to_string(score);
        render_text(score_string, game_font, font_color, renderer, FONT_OFFSET, FONT_OFFSET);

        // lose state checking
        if (player_x + ENTITY_SIZE > enemy_x) {
            if (player_y + ENTITY_SIZE > enemy_y) {
                if (player_x < enemy_x + ENTITY_SIZE) {
                    if (player_y < enemy_y + ENTITY_SIZE) {
                        abort();
                    }
                }
            }
        }

        // render things!
        SDL_RenderPresent(renderer);
    }

    // close down game
    TTF_CloseFont(game_font);
    SDL_DestroyTexture(enemy);
    SDL_DestroyTexture(player);
    SDL_DestroyTexture(background);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    TTF_Quit();
    IMG_Quit();
    SDL_Quit();

    return 0;
}<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>

#define MAXT 10
#define MAXN 1000
#define MAXE 100000

//#define MAXN 30
//#define MAXE 100

#define Zero(v) memset(v, 0, sizeof(v))

bool g[MAXN][MAXN];

void test_case()
{
    Zero(g);
    int n = rand() % (MAXN + 1);

    printf("\n%d\n", n);
    if (n == 0) return;

    int e = rand() % MAXE;
    while (e--) {
        if (n == 1) break;

        int u, v;
        do {
            u = rand() % n;
            v = rand() % n;
        } while (u == v);

        g[u][v] = true;
        g[v][u] = true;
    }

    for (int i = 0; i < n; ++i) {
        int ne = 0;
        for (int j = 0; j < n; ++j)
            if (g[i][j]) ++ne;

        printf("%d (%d)", i, ne);
        for (int j = 0; j < n; ++j)
            if (g[i][j]) printf(" %d", j);
        putchar('\n');
    }
}

int main()
{
    srand(time(NULL));

    int T = MAXT;
    printf("%d\n", T);

    while (T--) test_case();

    return 0;
}
<commit_msg>Refined generator<commit_after>#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;

#define MAXT 10
#define MAXN 1000
#define MAXE 100000

/*
#define MAXT 20
#define MAXN 500
#define MAXE 100000
*/

#define Zero(v) memset(v, 0, sizeof(v))

bool g[MAXN][MAXN];

void test_case()
{
    Zero(g);
    int n = rand() % (MAXN + 1);

    printf("\n%d\n", n);
    if (n == 0) return;

    int MaxEdges = n;

    if (rand() % 3 == 0)
        MaxEdges = min(n + n/10, MAXE);
    if (rand() % 4 == 0)
        MaxEdges = min(n*(n-1)/2, MAXE);

    int e = rand() % MaxEdges;
    while (e--) {
        if (n == 1) break;

        int u, v;
        do {
            u = rand() % n;
            v = rand() % n;
        } while (u == v);

        g[u][v] = true;
        g[v][u] = true;
    }

    for (int i = 0; i < n; ++i) {
        int ne = 0;
        for (int j = 0; j < n; ++j)
            if (g[i][j]) ++ne;

        printf("%d (%d)", i, ne);
        for (int j = 0; j < n; ++j)
            if (g[i][j]) printf(" %d", j);
        putchar('\n');
    }
}

int main()
{
    srand(time(NULL));

    int T = MAXT;
    printf("%d\n", T);

    while (T--) test_case();

    return 0;
}
<|endoftext|>


<commit_before>#ifndef ADD_TWO_NUMBERS_HPP_
#define ifndef ADD_TWO_NUMBERS_HPP_

struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(nullptr) {}
};

class AddTwoNumbers {
public:
  ListNode* addTwoNumbers(ListNode* l1, ListNode* l2);
};

#endif // ifndef ADD_TWO_NUMBERS_HPP_
<commit_msg>Update Two Numbers header<commit_after>#ifndef ADD_TWO_NUMBERS_HPP_
#define ADD_TWO_NUMBERS_HPP_

struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(nullptr) {}
};

class AddTwoNumbers {
public:
  ListNode* addTwoNumbers(ListNode* l1, ListNode* l2);
};

#endif // ADD_TWO_NUMBERS_HPP_
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "AnnFilesystem.hpp"
#include "AnnLogger.hpp"
#include "AnnGetter.hpp"

using namespace Annwvyn;
using namespace std;

vector<char> AnnFilesystemManager::charToEscape;
vector<char> AnnFilesystemManager::charToStrip;

AnnFileWriter::AnnFileWriter()
{
	AnnDebug() << "FileWriter instantiated";
}

void AnnFileWriter::write(shared_ptr<AnnSaveFileData> data)
{
	//Create the resources needed for the write operation
	auto fsmanager(AnnGetFileSystemManager());
	auto path(fsmanager->getPathForFileName(data->fileName));
	ofstream saveFile;

	//Make sure the "user save" directory as been created on the user's personal folder
	fsmanager->createSaveDirectory();

	//Open the file, abort if the file isn't openable
	saveFile.open(path); if (!saveFile.is_open())return;
	//push as plain text all key and data in a "key=data\n" format
	for (auto storedData : data->storedTextData)
		saveFile << storedData.first
		<< "="
		<< storedData.second
		<< endl;
	data->changed = false;
}

AnnFileReader::AnnFileReader()
{
	AnnDebug() << "FileReader instantiated";
}

AnnSaveFileDataPtr AnnFileReader::read(string fileName) const
{
	AnnDebug() << "Reading file " << fileName << " to memory";

	//Create the resource needed to the read operation
	auto fsmanager(AnnGetFileSystemManager());

	//Open the file
	ifstream ifile;
	auto fullPath = fsmanager->getPathForFileName(fileName);
	ifile.open(fullPath);

	if (!ifile)
	{
		AnnDebug() << "file " << fullPath << " doesn't exist or is not openable.";
		return nullptr;
	}

	auto fileData(fsmanager->crateSaveFileDataObject(fileName));
	if (!fileData) return nullptr;
	string buffer, key, value;

	//make sure the dataObject don't contain old content
	fileData->storedTextData.clear();

	//While we've not reach the end of the file
	while (!ifile.eof())
	{
		//Read a line
		getline(ifile, buffer);
		//Don't try to extract data from empty lines on the file
		if (buffer.empty()) continue;

		//Create a string stream on the buffer
		stringstream readStream(buffer);

		//Getline permit you to specify the "end-line" character. We use this to split the sting at the '=' in the file
		getline(readStream, key, '=');
		getline(readStream, value);

		//Store on the file data object the given key
		fileData->storedTextData[key] = value;
	}

	fileData->changed = false;
	return fileData;
}

AnnFilesystemManager::AnnFilesystemManager(string title) : AnnSubSystem("FilesystemManager"),
fileWriter(nullptr),
fileReader(nullptr)
{
	//get from the OS the user's personal directory
#ifdef WIN32
#pragma warning (disable : 4996) //Remove warning at usage of function "getenv"
	// ReSharper disable CppDeprecatedEntity
	pathToUserDir = getenv("USERPROFILE");
	// ReSharper restore CppDeprecatedEntity
#pragma warning (default : 4996)
#endif

#ifdef __linux__
	pathToUserDir = getenv("HOME");
#endif

	AnnDebug() << "Path got from operating system : " << pathToUserDir;

	//Forbidden characters in filename
	charToEscape.push_back(' ');
	charToEscape.push_back('&');
	charToEscape.push_back('<');
	charToEscape.push_back('>');
	charToEscape.push_back(':');
	charToEscape.push_back('|');
	charToEscape.push_back('?');
	charToEscape.push_back('*');
	charToEscape.push_back('"');
	charToEscape.push_back(':');
	charToEscape.push_back('%');

	//Forbidden characters in text "key=value" file
	charToStrip.push_back('=');
	charToStrip.push_back('\n');

	fileWriter = make_shared<AnnFileWriter>();
	fileReader = make_shared<AnnFileReader>();

	setSaveDirectoryName(title);
}

void AnnFilesystemManager::setSaveDirectoryName(string dirname)
{
	for (auto achar : charToEscape)
		replace(begin(dirname), end(dirname), achar, '_');
	saveDirectoryName = dirname;
#ifdef __linux__
	//Put the save directory as "hidden" in user's home directory on Linux.
	saveDirectoryName = "." + saveDirectoryName;
#endif

	AnnDebug() << "Save directory : " << saveDirectoryName;
	AnnDebug() << "Save directory location : " << getSaveDirectoryFullPath();
}

string AnnFilesystemManager::getPathForFileName(string filename) const
{
	if (!pathToUserDir.empty())
		return pathToUserDir + "/" + saveDirectoryName + "/" + filename;
	return "";
}

string AnnFilesystemManager::getSaveDirectoryFullPath() const
{
	return pathToUserDir + "/" + saveDirectoryName;
}

void AnnFilesystemManager::createDirectory(string path)
{
	//TODO clean that when upgrading to C++17
#ifdef WIN32
	//Win32 call to create a directory
	CreateDirectory(wstring{ begin(path), end(path) }.c_str(), nullptr);
#endif
#ifdef __linux__
	//POSIX call to create a directory
	auto status = mkdir(path.c_str(), S_IRWXU);
	if (status == 0 || status == EEXIST) return;
	AnnDebug() << "Warning: mkdir() did not return 0 or EEXIST.";
#endif
}

void AnnFilesystemManager::createSaveDirectory() const
{
	createDirectory(getSaveDirectoryFullPath());
}

void AnnFilesystemManager::releaseSaveFileDataObject(shared_ptr<AnnSaveFileData> data)
{
	cachedData.remove(data);
}

AnnSaveFileDataPtr AnnFilesystemManager::crateSaveFileDataObject(string filename)
{
	auto data = make_shared<AnnSaveFileData>(filename);
	cachedData.push_back(data);
	return data;
}

AnnSaveFileDataPtr AnnFilesystemManager::getCachedSaveFileDataObject(string filename)
{
	for (auto dataObject : cachedData)
		if (dataObject->getFilename() == filename)
			return dataObject;
	return nullptr;
}

AnnFileReaderPtr AnnFilesystemManager::getFileReader() const
{
	return fileReader;
}

AnnFileWriterPtr AnnFilesystemManager::getFileWriter() const
{
	return fileWriter;
}

AnnSaveFileData::AnnSaveFileData(string name) :
	fileName(name),
	changed(false)
{
	AnnDebug() << "AnnSaveFileData object for file " << name << " created (not on disk!)";
}

bool AnnSaveFileData::hasUnsavedChanges() const
{
	return changed;
}

string AnnSaveFileData::getFilename() const
{
	return fileName;
}

string AnnSaveFileData::getValue(string key)
{
	//if key exist:
	if (storedTextData.find(key) != end(storedTextData))
		return storedTextData[key];
	//else:
	return "";
}

void AnnSaveFileData::setValue(string key, string value)
{
	for (auto achar : AnnFilesystemManager::charToStrip)
	{
		replace(begin(key), end(key), achar, '_');
		replace(begin(value), end(value), achar, '_');
	}
	storedTextData[key] = value;
	changed = true;
}

void AnnSaveFileData::setValue(string key, int value)
{
	stringstream sstream;
	sstream << value;
	setValue(key, sstream.str());
}

void AnnSaveFileData::setValue(string key, float value)
{
	stringstream sstream;
	sstream.precision(2 + numeric_limits<float>::max_digits10);
	sstream << fixed << value;
	setValue(key, sstream.str());
}

void AnnSaveFileData::setValue(string key, AnnVect3 vector)
{
	setValue(key + ".x", vector.x);
	setValue(key + ".y", vector.y);
	setValue(key + ".z", vector.z);
}

void AnnSaveFileData::setValue(string key, AnnQuaternion quaternion)
{
	setValue(key + ".x", quaternion.x);
	setValue(key + ".y", quaternion.y);
	setValue(key + ".z", quaternion.z);
	setValue(key + ".w", quaternion.w);
}

void AnnSaveFileData::setValue(string key, const char* value)
{
	setValue(key, string(value));
}

void AnnSaveFileData::clearValue(string key)
{
	storedTextData.erase(key);
	changed = true;
}

void AnnSaveFileData::clearVectorValue(string key)
{
	clearValue(key + ".x");
	clearValue(key + ".y");
	clearValue(key + ".z");
}

void AnnSaveFileData::clearQuaternionValue(string key)
{
	//like vectors, quaternion have x, y, and z, component. they just add a 'w' one
	clearValue(key + ".w"); clearVectorValue(key);
}

AnnSaveDataInterpretor::AnnSaveDataInterpretor(shared_ptr<AnnSaveFileData> data) :
	dataObject(data)
{
}

float AnnSaveDataInterpretor::stringToFloat(string text) const
{
	return stof(text);
}

int AnnSaveDataInterpretor::stringToInt(string text) const
{
	return stoi(text);
}

float AnnSaveDataInterpretor::keyStringToFloat(string key) const
{
	return stringToFloat(dataObject->getValue(key));
}

int AnnSaveDataInterpretor::keyStringToInt(string key) const
{
	return stringToInt(dataObject->getValue(key));
}

AnnVect3 AnnSaveDataInterpretor::keyStringToVect3(string key) const
{
	//Get text data from the dataObject return an invalid vector if the keyvalue wanted is not found
	string x, y, z;
	if ((x = dataObject->getValue(key + ".x")).empty()) return AnnVect3(false);
	if ((y = dataObject->getValue(key + ".y")).empty()) return AnnVect3(false);
	if ((z = dataObject->getValue(key + ".z")).empty()) return AnnVect3(false);

	//Convert the text data to floats and send them to the AnnVect3 constructor and return the object
	return AnnVect3(
		stringToFloat(x),
		stringToFloat(y),
		stringToFloat(z));
}

AnnQuaternion AnnSaveDataInterpretor::keyStringToQuaternion(string key) const
{
	//Get text data from the dataObject return an invalid quaternion if the keyvalue wanted is not found
	string x, y, z, w;
	if ((x = dataObject->getValue(key + ".x")).empty()) return AnnQuaternion(false);
	if ((y = dataObject->getValue(key + ".y")).empty()) return AnnQuaternion(false);
	if ((z = dataObject->getValue(key + ".z")).empty()) return AnnQuaternion(false);
	if ((w = dataObject->getValue(key + ".w")).empty()) return AnnQuaternion(false);

	//Convert the text data to floats and send them to the AnnQuaternion constructor and return the object
	return AnnQuaternion(
		stringToFloat(w),
		stringToFloat(x),
		stringToFloat(y),
		stringToFloat(z));
}
<commit_msg>Add "ISSUE" in TODO comment<commit_after>#include "stdafx.h"
#include "AnnFilesystem.hpp"
#include "AnnLogger.hpp"
#include "AnnGetter.hpp"

using namespace Annwvyn;
using namespace std;

vector<char> AnnFilesystemManager::charToEscape;
vector<char> AnnFilesystemManager::charToStrip;

AnnFileWriter::AnnFileWriter()
{
	AnnDebug() << "FileWriter instantiated";
}

void AnnFileWriter::write(shared_ptr<AnnSaveFileData> data)
{
	//Create the resources needed for the write operation
	auto fsmanager(AnnGetFileSystemManager());
	auto path(fsmanager->getPathForFileName(data->fileName));
	ofstream saveFile;

	//Make sure the "user save" directory as been created on the user's personal folder
	fsmanager->createSaveDirectory();

	//Open the file, abort if the file isn't openable
	saveFile.open(path); if (!saveFile.is_open())return;
	//push as plain text all key and data in a "key=data\n" format
	for (auto storedData : data->storedTextData)
		saveFile << storedData.first
		<< "="
		<< storedData.second
		<< endl;
	data->changed = false;
}

AnnFileReader::AnnFileReader()
{
	AnnDebug() << "FileReader instantiated";
}

AnnSaveFileDataPtr AnnFileReader::read(string fileName) const
{
	AnnDebug() << "Reading file " << fileName << " to memory";

	//Create the resource needed to the read operation
	auto fsmanager(AnnGetFileSystemManager());

	//Open the file
	ifstream ifile;
	auto fullPath = fsmanager->getPathForFileName(fileName);
	ifile.open(fullPath);

	if (!ifile)
	{
		AnnDebug() << "file " << fullPath << " doesn't exist or is not openable.";
		return nullptr;
	}

	auto fileData(fsmanager->crateSaveFileDataObject(fileName));
	if (!fileData) return nullptr;
	string buffer, key, value;

	//make sure the dataObject don't contain old content
	fileData->storedTextData.clear();

	//While we've not reach the end of the file
	while (!ifile.eof())
	{
		//Read a line
		getline(ifile, buffer);
		//Don't try to extract data from empty lines on the file
		if (buffer.empty()) continue;

		//Create a string stream on the buffer
		stringstream readStream(buffer);

		//Getline permit you to specify the "end-line" character. We use this to split the sting at the '=' in the file
		getline(readStream, key, '=');
		getline(readStream, value);

		//Store on the file data object the given key
		fileData->storedTextData[key] = value;
	}

	fileData->changed = false;
	return fileData;
}

AnnFilesystemManager::AnnFilesystemManager(string title) : AnnSubSystem("FilesystemManager"),
fileWriter(nullptr),
fileReader(nullptr)
{
	//get from the OS the user's personal directory
#ifdef WIN32
#pragma warning (disable : 4996) //Remove warning at usage of function "getenv"
	// ReSharper disable CppDeprecatedEntity
	pathToUserDir = getenv("USERPROFILE");
	// ReSharper restore CppDeprecatedEntity
#pragma warning (default : 4996)
#endif

#ifdef __linux__
	pathToUserDir = getenv("HOME");
#endif

	AnnDebug() << "Path got from operating system : " << pathToUserDir;

	//Forbidden characters in filename
	charToEscape.push_back(' ');
	charToEscape.push_back('&');
	charToEscape.push_back('<');
	charToEscape.push_back('>');
	charToEscape.push_back(':');
	charToEscape.push_back('|');
	charToEscape.push_back('?');
	charToEscape.push_back('*');
	charToEscape.push_back('"');
	charToEscape.push_back(':');
	charToEscape.push_back('%');

	//Forbidden characters in text "key=value" file
	charToStrip.push_back('=');
	charToStrip.push_back('\n');

	fileWriter = make_shared<AnnFileWriter>();
	fileReader = make_shared<AnnFileReader>();

	setSaveDirectoryName(title);
}

void AnnFilesystemManager::setSaveDirectoryName(string dirname)
{
	for (auto achar : charToEscape)
		replace(begin(dirname), end(dirname), achar, '_');
	saveDirectoryName = dirname;
#ifdef __linux__
	//Put the save directory as "hidden" in user's home directory on Linux.
	saveDirectoryName = "." + saveDirectoryName;
#endif

	AnnDebug() << "Save directory : " << saveDirectoryName;
	AnnDebug() << "Save directory location : " << getSaveDirectoryFullPath();
}

string AnnFilesystemManager::getPathForFileName(string filename) const
{
	if (!pathToUserDir.empty())
		return pathToUserDir + "/" + saveDirectoryName + "/" + filename;
	return "";
}

string AnnFilesystemManager::getSaveDirectoryFullPath() const
{
	return pathToUserDir + "/" + saveDirectoryName;
}

void AnnFilesystemManager::createDirectory(string path)
{
	//TODO ISSUE clean that when upgrading to C++17
#ifdef WIN32
	//Win32 call to create a directory
	CreateDirectory(wstring{ begin(path), end(path) }.c_str(), nullptr);
#endif
#ifdef __linux__
	//POSIX call to create a directory
	auto status = mkdir(path.c_str(), S_IRWXU);
	if (status == 0 || status == EEXIST) return;
	AnnDebug() << "Warning: mkdir() did not return 0 or EEXIST.";
#endif
}

void AnnFilesystemManager::createSaveDirectory() const
{
	createDirectory(getSaveDirectoryFullPath());
}

void AnnFilesystemManager::releaseSaveFileDataObject(shared_ptr<AnnSaveFileData> data)
{
	cachedData.remove(data);
}

AnnSaveFileDataPtr AnnFilesystemManager::crateSaveFileDataObject(string filename)
{
	auto data = make_shared<AnnSaveFileData>(filename);
	cachedData.push_back(data);
	return data;
}

AnnSaveFileDataPtr AnnFilesystemManager::getCachedSaveFileDataObject(string filename)
{
	for (auto dataObject : cachedData)
		if (dataObject->getFilename() == filename)
			return dataObject;
	return nullptr;
}

AnnFileReaderPtr AnnFilesystemManager::getFileReader() const
{
	return fileReader;
}

AnnFileWriterPtr AnnFilesystemManager::getFileWriter() const
{
	return fileWriter;
}

AnnSaveFileData::AnnSaveFileData(string name) :
	fileName(name),
	changed(false)
{
	AnnDebug() << "AnnSaveFileData object for file " << name << " created (not on disk!)";
}

bool AnnSaveFileData::hasUnsavedChanges() const
{
	return changed;
}

string AnnSaveFileData::getFilename() const
{
	return fileName;
}

string AnnSaveFileData::getValue(string key)
{
	//if key exist:
	if (storedTextData.find(key) != end(storedTextData))
		return storedTextData[key];
	//else:
	return "";
}

void AnnSaveFileData::setValue(string key, string value)
{
	for (auto achar : AnnFilesystemManager::charToStrip)
	{
		replace(begin(key), end(key), achar, '_');
		replace(begin(value), end(value), achar, '_');
	}
	storedTextData[key] = value;
	changed = true;
}

void AnnSaveFileData::setValue(string key, int value)
{
	stringstream sstream;
	sstream << value;
	setValue(key, sstream.str());
}

void AnnSaveFileData::setValue(string key, float value)
{
	stringstream sstream;
	sstream.precision(2 + numeric_limits<float>::max_digits10);
	sstream << fixed << value;
	setValue(key, sstream.str());
}

void AnnSaveFileData::setValue(string key, AnnVect3 vector)
{
	setValue(key + ".x", vector.x);
	setValue(key + ".y", vector.y);
	setValue(key + ".z", vector.z);
}

void AnnSaveFileData::setValue(string key, AnnQuaternion quaternion)
{
	setValue(key + ".x", quaternion.x);
	setValue(key + ".y", quaternion.y);
	setValue(key + ".z", quaternion.z);
	setValue(key + ".w", quaternion.w);
}

void AnnSaveFileData::setValue(string key, const char* value)
{
	setValue(key, string(value));
}

void AnnSaveFileData::clearValue(string key)
{
	storedTextData.erase(key);
	changed = true;
}

void AnnSaveFileData::clearVectorValue(string key)
{
	clearValue(key + ".x");
	clearValue(key + ".y");
	clearValue(key + ".z");
}

void AnnSaveFileData::clearQuaternionValue(string key)
{
	//like vectors, quaternion have x, y, and z, component. they just add a 'w' one
	clearValue(key + ".w"); clearVectorValue(key);
}

AnnSaveDataInterpretor::AnnSaveDataInterpretor(shared_ptr<AnnSaveFileData> data) :
	dataObject(data)
{
}

float AnnSaveDataInterpretor::stringToFloat(string text) const
{
	return stof(text);
}

int AnnSaveDataInterpretor::stringToInt(string text) const
{
	return stoi(text);
}

float AnnSaveDataInterpretor::keyStringToFloat(string key) const
{
	return stringToFloat(dataObject->getValue(key));
}

int AnnSaveDataInterpretor::keyStringToInt(string key) const
{
	return stringToInt(dataObject->getValue(key));
}

AnnVect3 AnnSaveDataInterpretor::keyStringToVect3(string key) const
{
	//Get text data from the dataObject return an invalid vector if the keyvalue wanted is not found
	string x, y, z;
	if ((x = dataObject->getValue(key + ".x")).empty()) return AnnVect3(false);
	if ((y = dataObject->getValue(key + ".y")).empty()) return AnnVect3(false);
	if ((z = dataObject->getValue(key + ".z")).empty()) return AnnVect3(false);

	//Convert the text data to floats and send them to the AnnVect3 constructor and return the object
	return AnnVect3(
		stringToFloat(x),
		stringToFloat(y),
		stringToFloat(z));
}

AnnQuaternion AnnSaveDataInterpretor::keyStringToQuaternion(string key) const
{
	//Get text data from the dataObject return an invalid quaternion if the keyvalue wanted is not found
	string x, y, z, w;
	if ((x = dataObject->getValue(key + ".x")).empty()) return AnnQuaternion(false);
	if ((y = dataObject->getValue(key + ".y")).empty()) return AnnQuaternion(false);
	if ((z = dataObject->getValue(key + ".z")).empty()) return AnnQuaternion(false);
	if ((w = dataObject->getValue(key + ".w")).empty()) return AnnQuaternion(false);

	//Convert the text data to floats and send them to the AnnQuaternion constructor and return the object
	return AnnQuaternion(
		stringToFloat(w),
		stringToFloat(x),
		stringToFloat(y),
		stringToFloat(z));
}
<|endoftext|>


<commit_before>/*
***************************************
*   Asylum Project @ 2013-12-09
***************************************
*/

#ifndef __ASYLUM_HPP__
#define __ASYLUM_HPP__

#include "defs.h"

/* System Filter */
#if !defined(_CR_SYS32_) && \
    !defined(_CR_SYS64_)
    #error "asylum.hpp: system not supported!"
#endif
#if !defined(_CR_CC_MSC_) && \
    !defined(_CR_CC_GCC_)
    #error "asylum.hpp: compiler not supported!"
#endif
#if !defined(_CR_OS_UNIX_) && \
    !defined(_CR_OS_WIN32_) && \
    !defined(_CR_OS_WIN64_)
    #error "asylum.hpp: os type not supported!"
#endif

/* Import CrHack Library */
#ifndef ASY_NO_CRHACK
    #ifndef _CR_NO_PRAGMA_LIB_
        #ifndef ASY_USE_STATIC
            #pragma comment (lib, "CrH_CORE.lib")
        #else
            #pragma comment (lib, "COREs.lib")
        #endif
    #endif
#else
    #include <stdlib.h>
    #include <string.h>
    /* ======================================= */
    cr_inline void_t mem_free (const void_t* ptr)
    {
        ::free((void*)ptr);
    }

    #if defined(_CR_NO_STDC_)
        #define mem_set     ::memset
        #define mem_cpy     ::memcpy
        #define mem_cmp     ::memcmp
        #define mem_mov     ::memmove
    #endif
    #define mem_malloc      ::malloc
    #define mem_calloc      ::calloc
    #define mem_malloc32    ::malloc
    #define mem_calloc32    ::calloc
    #define mem_realloc     ::realloc

#ifndef _CR_SYS32_
    #define mem_malloc64    ::malloc
    #define mem_calloc64    ::calloc
#else
    /* ====================================== */
    cr_inline void_t* mem_malloc64 (int64u size)
    {
        if (size > CR_ULL(0xFFFFFFFF))
            return (NULL);
        return (mem_malloc32((int32u)size));
    }

    /* ================================================== */
    cr_inline void_t* mem_calloc64 (int64u num, size_t size)
    {
        if (num > CR_ULL(0xFFFFFFFF))
            return (NULL);
        return (mem_calloc32((int32u)num, size));
    }
#endif  /* !_CR_SYS32_ */
#endif  /* !ASY_NO_CRHACK */

#include "crhack.h"

/* Include */
#if defined(_CR_CC_MSC_)
    #include <intrin.h>
    typedef dist_t  ssize_t;
#endif
#if defined(_CR_OS_MSWIN_)
    #include <process.h>
    #include <windows.h>
#else
    #include <time.h>
    #include <errno.h>
    #include <sched.h>
    #include <pthread.h>
#endif

/* BASIC STUFF */
#include "basic/basic.hpp"
#include "basic/defer.hpp"
#include "basic/safer.hpp"

/* CPU STUFF */
#include "cpu/thread.hpp"
#include "cpu/atomic.hpp"
#include "cpu/crisec.hpp"
#include "cpu/events.hpp"
#include "cpu/exlock.hpp"
#include "cpu/mtlock.hpp"
#include "cpu/nolock.hpp"
#include "cpu/rwlock.hpp"
#include "cpu/splock.hpp"
#include "cpu/doonce.hpp"
#include "cpu/mtpool.hpp"

/* CrHack C++ Wrapper */
#include "crhack/ascall.hpp"
#include "crhack/iports.hpp"
#if defined(ASY_USE_GDI)
    #include "gfx2/gdiwin.h"
    #include "crhack/gfx2_gdi.hpp"
#endif
#if defined(ASY_USE_DX8)
    #include "gfx2/dx8win.h"
    #include "crhack/gfx2_dx8.hpp"
#endif
#if defined(ASY_USE_DX9)
    #include "gfx2/dx9win.h"
    #include "crhack/gfx2_dx9.hpp"
#endif

/* Yet Another Wheel */
#include "yaw/array.hpp"
#include "yaw/bring.hpp"
#include "yaw/list2.hpp"
#include "yaw/map2d.hpp"
#include "yaw/map_a.hpp"
#include "yaw/map_l.hpp"
#include "yaw/oring.hpp"
#include "yaw/table.hpp"
#include "yaw/tree_a.hpp"
#include "yaw/tree_l.hpp"
#include "yaw/map_acs.hpp"

/* Misaka Network */

/* Asylum3D */
#include "draw3d/asylum3d.hpp"
#if defined(ASY_USE_DX9)
    #include "draw3d/crh3d9_main.hpp"
    #include "draw3d/crh3d9_shader.hpp"
    #include "draw3d/crh3d9_texture.hpp"
    #include "draw3d/crh3d9_mtl_wf.hpp"
#endif

#endif  /* __ASYLUM_HPP__ */
<commit_msg>Asylum: 补上缺失的库引用<commit_after>/*
***************************************
*   Asylum Project @ 2013-12-09
***************************************
*/

#ifndef __ASYLUM_HPP__
#define __ASYLUM_HPP__

#include "defs.h"

/* System Filter */
#if !defined(_CR_SYS32_) && \
    !defined(_CR_SYS64_)
    #error "asylum.hpp: system not supported!"
#endif
#if !defined(_CR_CC_MSC_) && \
    !defined(_CR_CC_GCC_)
    #error "asylum.hpp: compiler not supported!"
#endif
#if !defined(_CR_OS_UNIX_) && \
    !defined(_CR_OS_WIN32_) && \
    !defined(_CR_OS_WIN64_)
    #error "asylum.hpp: os type not supported!"
#endif

/* Import CrHack Library */
#ifndef ASY_NO_CRHACK
    #ifndef _CR_NO_PRAGMA_LIB_
        #ifndef ASY_USE_STATIC
            #pragma comment (lib, "CrH_CORE.lib")
        #else
            #pragma comment (lib, "COREs.lib")
        #endif
    #endif
#else
    #include <stdlib.h>
    #include <string.h>
    /* ======================================= */
    cr_inline void_t mem_free (const void_t* ptr)
    {
        ::free((void*)ptr);
    }

    #if defined(_CR_NO_STDC_)
        #define mem_set     ::memset
        #define mem_cpy     ::memcpy
        #define mem_cmp     ::memcmp
        #define mem_mov     ::memmove
    #endif
    #define mem_malloc      ::malloc
    #define mem_calloc      ::calloc
    #define mem_malloc32    ::malloc
    #define mem_calloc32    ::calloc
    #define mem_realloc     ::realloc

#ifndef _CR_SYS32_
    #define mem_malloc64    ::malloc
    #define mem_calloc64    ::calloc
#else
    /* ====================================== */
    cr_inline void_t* mem_malloc64 (int64u size)
    {
        if (size > CR_ULL(0xFFFFFFFF))
            return (NULL);
        return (mem_malloc32((int32u)size));
    }

    /* ================================================== */
    cr_inline void_t* mem_calloc64 (int64u num, size_t size)
    {
        if (num > CR_ULL(0xFFFFFFFF))
            return (NULL);
        return (mem_calloc32((int32u)num, size));
    }
#endif  /* !_CR_SYS32_ */
#endif  /* !ASY_NO_CRHACK */

#include "crhack.h"

/* Include */
#if defined(_CR_CC_MSC_)
    #include <intrin.h>
    typedef dist_t  ssize_t;
#endif
#if defined(_CR_OS_MSWIN_)
    #include <process.h>
    #include <windows.h>
#else
    #include <time.h>
    #include <errno.h>
    #include <sched.h>
    #include <pthread.h>
#endif

/* BASIC STUFF */
#include "basic/basic.hpp"
#include "basic/defer.hpp"
#include "basic/safer.hpp"

/* CPU STUFF */
#include "cpu/thread.hpp"
#include "cpu/atomic.hpp"
#include "cpu/crisec.hpp"
#include "cpu/events.hpp"
#include "cpu/exlock.hpp"
#include "cpu/mtlock.hpp"
#include "cpu/nolock.hpp"
#include "cpu/rwlock.hpp"
#include "cpu/splock.hpp"
#include "cpu/doonce.hpp"
#include "cpu/mtpool.hpp"

/* CrHack C++ Wrapper */
#include "crhack/ascall.hpp"
#include "crhack/iports.hpp"
#if defined(ASY_USE_GDI)
    #include "gfx2/gdiwin.h"
    #include "crhack/gfx2_gdi.hpp"
#endif
#if defined(ASY_USE_DX8)
    #include "gfx2/dx8win.h"
    #include "crhack/gfx2_dx8.hpp"
#endif
#if defined(ASY_USE_DX9)
    #include "gfx2/dx9win.h"
    #include "crhack/gfx2_dx9.hpp"
#endif

/* Yet Another Wheel */
#include "yaw/array.hpp"
#include "yaw/bring.hpp"
#include "yaw/list2.hpp"
#include "yaw/map2d.hpp"
#include "yaw/map_a.hpp"
#include "yaw/map_l.hpp"
#include "yaw/oring.hpp"
#include "yaw/table.hpp"
#include "yaw/tree_a.hpp"
#include "yaw/tree_l.hpp"
#include "yaw/map_acs.hpp"

/* Misaka Network */

/* Asylum3D */
#include "draw3d/asylum3d.hpp"
#if defined(ASY_USE_DX9)
    #include "draw3d/crh3d9_main.hpp"
    #include "draw3d/crh3d9_shader.hpp"
    #include "draw3d/crh3d9_texture.hpp"
    #include "draw3d/crh3d9_mtl_wf.hpp"
    #ifndef ASY_USE_STATIC
        #pragma comment (lib, "CrH_GFX3.lib")
    #else
        #pragma comment (lib, "GFX3s.lib")
    #endif
#endif

#endif  /* __ASYLUM_HPP__ */
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008-2010 Digital Bazaar, Inc. All rights reserved.
 */
#include "bitmunk/test/Tester.h"

// FIXME: bitmunk-unit-tests.h should be split between the bmtest library
//        and the tests.
#include "bitmunk/tests/bitmunk-unit-tests.h"
#include "bitmunk/common/Logging.h"
#include "monarch/config/ConfigManager.h"
#include "monarch/io/File.h"
#include "monarch/test/Test.h"

using namespace std;
using namespace bitmunk::common;
using namespace bitmunk::node;
using namespace bitmunk::test;
using namespace monarch::app;
using namespace monarch::config;
using namespace monarch::io;
using namespace monarch::kernel;
using namespace monarch::rt;

Tester::Tester()
{
}

Tester::~Tester()
{
}

bool Tester::addNodeConfig(monarch::test::TestRunner& tr, Config* extraMerge)
{
   bool rval;

   //monarch::test::Tester::setup(tr);
   Config config;
   {
      Config meta = tr.getApp()->getMetaConfig();
      const char* gid = meta["groups"]["boot"]->getString();
      config[ConfigManager::VERSION] = BITMUNK_CONFIG_VERSION;
      config[ConfigManager::ID] = "bitmunk.test.Tester.config.base";
      config[ConfigManager::GROUP] = gid;
      config[ConfigManager::PARENT] = meta["parents"][gid]->getString();
   }
   Config& cfg = config[ConfigManager::MERGE];

   cfg["node"]["host"] = "localhost";
   cfg["node"]["port"] = 19101;
   cfg["node"]["bitmunkUrl"] = "http://localhost:19101";
   cfg["node"]["secureBitmunkUrl"] = "https://localhost:19101";
   cfg["node"]["modulePath"] = MODULES_DIRECTORY;
   cfg["node"]["bitmunkHomePath"] = "/tmp/test";
   cfg["node"]["profilePath"] = PROFILES_DIRECTORY;
   cfg["node"]["usersPath"] = "users";
   cfg["node"]["sslGenerate"] = true;
   cfg["node"]["sslCertificate"] = SSL_CERTIFICATE_FILE;
   cfg["node"]["sslPrivateKey"] = SSL_PRIVATE_KEY_FILE;
   cfg["node"]["sslCAFile"] = SSL_CA_FILE;
   cfg["node"]["maxConnectionCount"] = (uint64_t)100;
   cfg["node"]["maxThreadCount"] = (uint64_t)100;

   // cached bfp modules directory
   cfg["bitmunk.bfp.Bfp"]["cachePath"] = "bitmunk.bfp.Bfp/cache";

   // FIXME: this looks dated...
   // null webui config
   cfg["bitmunk.webui.WebUi"]["main"]->setType(String);
   cfg["bitmunk.webui.WebUi"]["plugins"]->setType(Map);
   //cfg["bitmunk.webui.WebUi"]["modules"]->setType(Array);
   //cfg["bitmunk.webui.WebUi"]["modulesPath"]->setType(Array);
   cfg["bitmunk.webui.WebUi"]["sessionDatabase"]["url"] =
      "sqlite3://bitmunk.webui.WebUi/sessiondb.db";
   cfg["bitmunk.webui.WebUi"]["sessionDatabase"]["connections"] = 1;

   // flash config info
   cfg["bitmunk.webui.WebUi"]["flash"]["policyServer"]["host"] = "0.0.0.0";
   cfg["bitmunk.webui.WebUi"]["flash"]["policyServer"]["port"] = 19844;

   // purchase module config
   cfg["bitmunk.purchase.Purchase"]["temporaryPath"] = "tmp";
   cfg["bitmunk.purchase.Purchase"]["downloadPath"] = "dl";
   cfg["bitmunk.purchase.Purchase"]["maxDownloadRate"] = 1024 * 1024;
   cfg["bitmunk.purchase.Purchase"]["maxExcessBandwidth"] = 1024 * 10;
   cfg["bitmunk.purchase.Purchase"]["maxPieces"] = 10;
   cfg["bitmunk.purchase.Purchase"]["database"]["url"] =
      "sqlite3://bitmunk.purchase.Purchase/purchase.db";
   cfg["bitmunk.purchase.Purchase"]["database"]["connections"] = 1;

   // media library config
   cfg["bitmunk.medialibrary.MediaLibrary"]["database"]["url"] =
      "sqlite3://bitmunk.medialibrary.MediaLibrary/medialibrary.db";
   cfg["bitmunk.medialibrary.MediaLibrary"]["database"]["connections"] = 1;

   // custom catalog config
   // Note: do updates every 10 seconds for testing
   cfg["bitmunk.catalog.CustomCatalog"]["listingSyncInterval"] = 10;
   cfg["bitmunk.catalog.CustomCatalog"]["uploadListings"] = false;

   // sell config
   cfg["bitmunk.sell.Sell"]["maxUploadRate"] = 0;

   /* OLD PEER NODE CONFIG
   DynamicObject config;
   config[ConfigManager::VERSION] = BITMUNK_CONFIG_VERSION;
   config[ConfigManager::ID] = "bitmunk.test.Tester.config.peer";
   config[ConfigManager::GROUP] =
      tr.getApp()->getMetaConfig()["groups"]["main"]->getString();
   Config merge = config[ConfigManager::MERGE];
   merge["node"]["port"] = 19200;
   merge["node"]["bitmunkUrl"] = "http://localhost:19100";
   merge["node"]["secureBitmunkUrl"] = "https://localhost:19100";
    */

   if(extraMerge)
   {
      cfg.merge(*extraMerge, false);
   }

   // only load this config once
   ConfigManager* cm = tr.getApp()->getConfigManager();
   if(!cm->hasConfig(config[ConfigManager::ID]->getString()))
   {
      rval = cm->addConfig(config);
      assertNoException();
   }

   return rval;
}

bool Tester::removeNodeConfig(monarch::test::TestRunner& tr)
{
   bool rval;

   /* CODE TO REMOVE OLD PEER NODE CONFIG
   return tr.getMicroKernel()->getConfigManager()->removeConfig(
      "bitmunk.test.Tester.config.peer");
   */

   ConfigManager::ConfigId id = "bitmunk.test.Tester.config.base";
   // only load this config once
   ConfigManager* cm = tr.getApp()->getConfigManager();
   if(cm->hasConfig(id))
   {
      rval = cm->removeConfig(id);
      assertNoException();
   }

   return rval;
}

Node* Tester::loadNode(monarch::test::TestRunner& tr)
{
   Node* rval = NULL;

   // load node module
   File file(File::join(MODULES_DIRECTORY, "libbmnode.so").c_str());
   MicroKernel* k = tr.getMicroKernel();
   MicroKernelModule* mod = k->loadMicroKernelModule(file->getAbsolutePath());
   if(mod != NULL)
   {
      rval = dynamic_cast<Node*>(mod->getApi(k));
      if(rval == NULL)
      {
         // unload bad module
         k->unloadModule(&mod->getId());
         ExceptionRef e = new Exception(
            "Invalid node module.",
            "bitmunk.test.Tester.InvalidNodeModule");
         e->getDetails()["filename"] = file->getAbsolutePath();
         Exception::set(e);
      }
   }

   return rval;
}

bool Tester::unloadNode(monarch::test::TestRunner& tr)
{
   MicroKernel* k = tr.getMicroKernel();
   return k->unloadModule("bitmunk.node.Node");
}

/*
bool Tester::setupNode(monarch::test::TestRunner& tr, Node* node)
{
   bool rval = true;
   ConfigManager* cm = getApp()->getConfigManager();
   ConfigManager* ncm = node->getConfigManager();

   // copy test config as new node's boot config
   {
      Config c;
      c[ConfigManager::ID] = "boot";
      c[ConfigManager::MERGE] = cm->getConfig("main").clone();
      rval = ncm->addConfig(c);
   }

   // add empty main
   if(rval)
   {
      Config c;
      c[ConfigManager::ID] = "__main__";
      c[ConfigManager::PARENT] = "boot";
      c[ConfigManager::GROUP] = "main";
      rval = ncm->addConfig(c);
   }

   // copy raw users config
   if(rval)
   {
      Config c;
      c[ConfigManager::ID] = "bitmunk.test.Tester users";
      c[ConfigManager::GROUP] = "users";
      c[ConfigManager::MERGE] = cm->getConfig("users");
      rval = ncm->addConfig(c);
   }

   return rval;
}
*/
<commit_msg>Changed bitmunk port to 19100 for auth server.<commit_after>/*
 * Copyright (c) 2008-2010 Digital Bazaar, Inc. All rights reserved.
 */
#include "bitmunk/test/Tester.h"

// FIXME: bitmunk-unit-tests.h should be split between the bmtest library
//        and the tests.
#include "bitmunk/tests/bitmunk-unit-tests.h"
#include "bitmunk/common/Logging.h"
#include "monarch/config/ConfigManager.h"
#include "monarch/io/File.h"
#include "monarch/test/Test.h"

using namespace std;
using namespace bitmunk::common;
using namespace bitmunk::node;
using namespace bitmunk::test;
using namespace monarch::app;
using namespace monarch::config;
using namespace monarch::io;
using namespace monarch::kernel;
using namespace monarch::rt;

Tester::Tester()
{
}

Tester::~Tester()
{
}

bool Tester::addNodeConfig(monarch::test::TestRunner& tr, Config* extraMerge)
{
   bool rval;

   //monarch::test::Tester::setup(tr);
   Config config;
   {
      Config meta = tr.getApp()->getMetaConfig();
      const char* gid = meta["groups"]["boot"]->getString();
      config[ConfigManager::VERSION] = BITMUNK_CONFIG_VERSION;
      config[ConfigManager::ID] = "bitmunk.test.Tester.config.base";
      config[ConfigManager::GROUP] = gid;
      config[ConfigManager::PARENT] = meta["parents"][gid]->getString();
   }
   Config& cfg = config[ConfigManager::MERGE];

   cfg["node"]["host"] = "localhost";
   cfg["node"]["port"] = 19101;
   cfg["node"]["bitmunkUrl"] = "http://localhost:19100";
   cfg["node"]["secureBitmunkUrl"] = "https://localhost:19100";
   cfg["node"]["modulePath"] = MODULES_DIRECTORY;
   cfg["node"]["bitmunkHomePath"] = "/tmp/test";
   cfg["node"]["profilePath"] = PROFILES_DIRECTORY;
   cfg["node"]["usersPath"] = "users";
   cfg["node"]["sslGenerate"] = true;
   cfg["node"]["sslCertificate"] = SSL_CERTIFICATE_FILE;
   cfg["node"]["sslPrivateKey"] = SSL_PRIVATE_KEY_FILE;
   cfg["node"]["sslCAFile"] = SSL_CA_FILE;
   cfg["node"]["maxConnectionCount"] = (uint64_t)100;
   cfg["node"]["maxThreadCount"] = (uint64_t)100;

   // cached bfp modules directory
   cfg["bitmunk.bfp.Bfp"]["cachePath"] = "bitmunk.bfp.Bfp/cache";

   // FIXME: this looks dated...
   // null webui config
   cfg["bitmunk.webui.WebUi"]["main"]->setType(String);
   cfg["bitmunk.webui.WebUi"]["plugins"]->setType(Map);
   //cfg["bitmunk.webui.WebUi"]["modules"]->setType(Array);
   //cfg["bitmunk.webui.WebUi"]["modulesPath"]->setType(Array);
   cfg["bitmunk.webui.WebUi"]["sessionDatabase"]["url"] =
      "sqlite3://bitmunk.webui.WebUi/sessiondb.db";
   cfg["bitmunk.webui.WebUi"]["sessionDatabase"]["connections"] = 1;

   // flash config info
   cfg["bitmunk.webui.WebUi"]["flash"]["policyServer"]["host"] = "0.0.0.0";
   cfg["bitmunk.webui.WebUi"]["flash"]["policyServer"]["port"] = 19844;

   // purchase module config
   cfg["bitmunk.purchase.Purchase"]["temporaryPath"] = "tmp";
   cfg["bitmunk.purchase.Purchase"]["downloadPath"] = "dl";
   cfg["bitmunk.purchase.Purchase"]["maxDownloadRate"] = 1024 * 1024;
   cfg["bitmunk.purchase.Purchase"]["maxExcessBandwidth"] = 1024 * 10;
   cfg["bitmunk.purchase.Purchase"]["maxPieces"] = 10;
   cfg["bitmunk.purchase.Purchase"]["database"]["url"] =
      "sqlite3://bitmunk.purchase.Purchase/purchase.db";
   cfg["bitmunk.purchase.Purchase"]["database"]["connections"] = 1;

   // media library config
   cfg["bitmunk.medialibrary.MediaLibrary"]["database"]["url"] =
      "sqlite3://bitmunk.medialibrary.MediaLibrary/medialibrary.db";
   cfg["bitmunk.medialibrary.MediaLibrary"]["database"]["connections"] = 1;

   // custom catalog config
   // Note: do updates every 10 seconds for testing
   cfg["bitmunk.catalog.CustomCatalog"]["listingSyncInterval"] = 10;
   cfg["bitmunk.catalog.CustomCatalog"]["uploadListings"] = false;

   // sell config
   cfg["bitmunk.sell.Sell"]["maxUploadRate"] = 0;

   /* OLD PEER NODE CONFIG
   DynamicObject config;
   config[ConfigManager::VERSION] = BITMUNK_CONFIG_VERSION;
   config[ConfigManager::ID] = "bitmunk.test.Tester.config.peer";
   config[ConfigManager::GROUP] =
      tr.getApp()->getMetaConfig()["groups"]["main"]->getString();
   Config merge = config[ConfigManager::MERGE];
   merge["node"]["port"] = 19200;
   merge["node"]["bitmunkUrl"] = "http://localhost:19100";
   merge["node"]["secureBitmunkUrl"] = "https://localhost:19100";
    */

   if(extraMerge)
   {
      cfg.merge(*extraMerge, false);
   }

   // only load this config once
   ConfigManager* cm = tr.getApp()->getConfigManager();
   if(!cm->hasConfig(config[ConfigManager::ID]->getString()))
   {
      rval = cm->addConfig(config);
      assertNoException();
   }

   return rval;
}

bool Tester::removeNodeConfig(monarch::test::TestRunner& tr)
{
   bool rval;

   /* CODE TO REMOVE OLD PEER NODE CONFIG
   return tr.getMicroKernel()->getConfigManager()->removeConfig(
      "bitmunk.test.Tester.config.peer");
   */

   ConfigManager::ConfigId id = "bitmunk.test.Tester.config.base";
   // only load this config once
   ConfigManager* cm = tr.getApp()->getConfigManager();
   if(cm->hasConfig(id))
   {
      rval = cm->removeConfig(id);
      assertNoException();
   }

   return rval;
}

Node* Tester::loadNode(monarch::test::TestRunner& tr)
{
   Node* rval = NULL;

   // load node module
   File file(File::join(MODULES_DIRECTORY, "libbmnode.so").c_str());
   MicroKernel* k = tr.getMicroKernel();
   MicroKernelModule* mod = k->loadMicroKernelModule(file->getAbsolutePath());
   if(mod != NULL)
   {
      rval = dynamic_cast<Node*>(mod->getApi(k));
      if(rval == NULL)
      {
         // unload bad module
         k->unloadModule(&mod->getId());
         ExceptionRef e = new Exception(
            "Invalid node module.",
            "bitmunk.test.Tester.InvalidNodeModule");
         e->getDetails()["filename"] = file->getAbsolutePath();
         Exception::set(e);
      }
   }

   return rval;
}

bool Tester::unloadNode(monarch::test::TestRunner& tr)
{
   MicroKernel* k = tr.getMicroKernel();
   return k->unloadModule("bitmunk.node.Node");
}

/*
bool Tester::setupNode(monarch::test::TestRunner& tr, Node* node)
{
   bool rval = true;
   ConfigManager* cm = getApp()->getConfigManager();
   ConfigManager* ncm = node->getConfigManager();

   // copy test config as new node's boot config
   {
      Config c;
      c[ConfigManager::ID] = "boot";
      c[ConfigManager::MERGE] = cm->getConfig("main").clone();
      rval = ncm->addConfig(c);
   }

   // add empty main
   if(rval)
   {
      Config c;
      c[ConfigManager::ID] = "__main__";
      c[ConfigManager::PARENT] = "boot";
      c[ConfigManager::GROUP] = "main";
      rval = ncm->addConfig(c);
   }

   // copy raw users config
   if(rval)
   {
      Config c;
      c[ConfigManager::ID] = "bitmunk.test.Tester users";
      c[ConfigManager::GROUP] = "users";
      c[ConfigManager::MERGE] = cm->getConfig("users");
      rval = ncm->addConfig(c);
   }

   return rval;
}
*/
<|endoftext|>


<commit_before>/************************************************************************
	filename: 	CEGUIEventSet.cpp
	created:	21/2/2004
	author:		Paul D Turner

	purpose:	Implements the EventSet class
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "CEGUIEventSet.h"
#include "CEGUIExceptions.h"
#include "CEGUIGlobalEventSet.h"
#include "CEGUIScriptModule.h"
#include "CEGUISystem.h"

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Constructor
*************************************************************************/
EventSet::EventSet() :
	d_muted(false)
{
}

/*************************************************************************
	Destructor
*************************************************************************/
EventSet::~EventSet(void)
{
	removeAllEvents();
}

/*************************************************************************
	Add a new event to the EventSet
*************************************************************************/
void EventSet::addEvent(const String& name)
{
	if (isEventPresent(name))
	{
		throw AlreadyExistsException("An event named '" + name + "' already exists in the EventSet.");
	}

	d_events[name] = new Event(name);
}

/*************************************************************************
	Remove an event from the EventSet
*************************************************************************/
void EventSet::removeEvent(const String& name)
{
	EventMap::iterator pos = d_events.find(name);

	if (pos != d_events.end())
	{
		delete pos->second;
		d_events.erase(pos);
	}

}

/*************************************************************************
	Remove all events from the EventSet
*************************************************************************/
void EventSet::removeAllEvents(void)
{
	EventMap::iterator pos = d_events.begin();
	EventMap::iterator end = d_events.end()	;

	for (; pos != end; ++pos)
	{
		delete pos->second;
	}

	d_events.clear();
}

/*************************************************************************
	Check to see if an event is available
*************************************************************************/
bool EventSet::isEventPresent(const String& name)
{
	return (d_events.find(name) != d_events.end());
}

/*************************************************************************
	Subscribe to a scripted event (no group)
*************************************************************************/
Event::Connection EventSet::subscribeScriptedEvent(const String& name, const String& subscriber_name)
{
	//return subscribeEvent(name, Event::Subscriber(ScriptFunctor(subscriber_name)));
	ScriptModule* sm = System::getSingletonPtr()->getScriptingModule();
	if (!sm)
	{
	   throw InvalidRequestException("[EventSet::subscribeScriptedEvent] No scripting module is available");
	}
	return sm->subscribeEvent(this, name, subscriber_name);
}

/*************************************************************************
	Subscribe to a scripted event
*************************************************************************/
Event::Connection EventSet::subscribeScriptedEvent(const String& name, Event::Group group, const String& subscriber_name)
{
        //return subscribeEvent(name, group, Event::Subscriber(ScriptFunctor(subscriber_name)));
        ScriptModule* sm = System::getSingletonPtr()->getScriptingModule();
	if (!sm)
	{
	   throw InvalidRequestException("[EventSet::subscribeScriptedEvent] No scripting module is available");
	}
	return sm->subscribeEvent(this, name, group, subscriber_name);
}

/*************************************************************************
	Subscribe to an event (no group)
*************************************************************************/
Event::Connection EventSet::subscribeEvent(const String& name, Event::Subscriber subscriber)
{
    // do subscription & return connection
    return getEventObject(name)->subscribe(subscriber);
}

/*************************************************************************
	Subscribe to an event group
*************************************************************************/
Event::Connection EventSet::subscribeEvent(const String& name, Event::Group group, Event::Subscriber subscriber)
{
    // do subscription with group & return connection
    return getEventObject(name)->subscribe(group, subscriber);
}

/*************************************************************************
	Fire / Trigger an event
*************************************************************************/
void EventSet::fireEvent(const String& name, EventArgs& args, const String& eventNamespace)
{
    // handle global events
    GlobalEventSet::getSingleton().fireEvent(name, args, eventNamespace);
    // handle local event
    fireEvent_impl(name, args);
}

/*************************************************************************
	Return whether the EventSet is muted or not.
*************************************************************************/
bool EventSet::isMuted(void) const
{
	return d_muted;
}

/*************************************************************************
	Set the mute state for this EventSet.
*************************************************************************/
void EventSet::setMutedState(bool setting)
{
	d_muted = setting;
}

/*************************************************************************
    Return the named Event object, optionally adding it to the set
    if needed
*************************************************************************/
Event* EventSet::getEventObject(const String& name, bool autoAdd)
{
    EventMap::iterator pos = d_events.find(name);

    // if event did not exist, add it and then find it.
    if (pos == d_events.end())
    {
        if (autoAdd)
        {
            addEvent(name);
            return d_events.find(name)->second;
        }
        else
        {
            return 0;
        }
    }

    return pos->second;
}

/*************************************************************************

*************************************************************************/
void EventSet::fireEvent_impl(const String& name, EventArgs& args)
{
    // find event object
    Event* ev = getEventObject(name);

    // fire the event if present and set is not muted
    if ((ev != 0) && !d_muted)
        (*ev)(args);
}

/*************************************************************************
	Return a EventSet::EventIterator object to iterate over the available
	events.
*************************************************************************/
EventSet::EventIterator EventSet::getIterator(void) const
{
	return EventIterator(d_events.begin(), d_events.end());
}

} // End of  CEGUI namespace section
<commit_msg>Fixed issue where dynamic EventSet did not actually create the new events (D'oh!)<commit_after>/************************************************************************
	filename: 	CEGUIEventSet.cpp
	created:	21/2/2004
	author:		Paul D Turner

	purpose:	Implements the EventSet class
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "CEGUIEventSet.h"
#include "CEGUIExceptions.h"
#include "CEGUIGlobalEventSet.h"
#include "CEGUIScriptModule.h"
#include "CEGUISystem.h"

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Constructor
*************************************************************************/
EventSet::EventSet() :
	d_muted(false)
{
}

/*************************************************************************
	Destructor
*************************************************************************/
EventSet::~EventSet(void)
{
	removeAllEvents();
}

/*************************************************************************
	Add a new event to the EventSet
*************************************************************************/
void EventSet::addEvent(const String& name)
{
	if (isEventPresent(name))
	{
		throw AlreadyExistsException("An event named '" + name + "' already exists in the EventSet.");
	}

	d_events[name] = new Event(name);
}

/*************************************************************************
	Remove an event from the EventSet
*************************************************************************/
void EventSet::removeEvent(const String& name)
{
	EventMap::iterator pos = d_events.find(name);

	if (pos != d_events.end())
	{
		delete pos->second;
		d_events.erase(pos);
	}

}

/*************************************************************************
	Remove all events from the EventSet
*************************************************************************/
void EventSet::removeAllEvents(void)
{
	EventMap::iterator pos = d_events.begin();
	EventMap::iterator end = d_events.end()	;

	for (; pos != end; ++pos)
	{
		delete pos->second;
	}

	d_events.clear();
}

/*************************************************************************
	Check to see if an event is available
*************************************************************************/
bool EventSet::isEventPresent(const String& name)
{
	return (d_events.find(name) != d_events.end());
}

/*************************************************************************
	Subscribe to a scripted event (no group)
*************************************************************************/
Event::Connection EventSet::subscribeScriptedEvent(const String& name, const String& subscriber_name)
{
	//return subscribeEvent(name, Event::Subscriber(ScriptFunctor(subscriber_name)));
	ScriptModule* sm = System::getSingletonPtr()->getScriptingModule();
	if (!sm)
	{
	   throw InvalidRequestException("[EventSet::subscribeScriptedEvent] No scripting module is available");
	}
	return sm->subscribeEvent(this, name, subscriber_name);
}

/*************************************************************************
	Subscribe to a scripted event
*************************************************************************/
Event::Connection EventSet::subscribeScriptedEvent(const String& name, Event::Group group, const String& subscriber_name)
{
        //return subscribeEvent(name, group, Event::Subscriber(ScriptFunctor(subscriber_name)));
        ScriptModule* sm = System::getSingletonPtr()->getScriptingModule();
	if (!sm)
	{
	   throw InvalidRequestException("[EventSet::subscribeScriptedEvent] No scripting module is available");
	}
	return sm->subscribeEvent(this, name, group, subscriber_name);
}

/*************************************************************************
	Subscribe to an event (no group)
*************************************************************************/
Event::Connection EventSet::subscribeEvent(const String& name, Event::Subscriber subscriber)
{
    // do subscription & return connection
    return getEventObject(name, true)->subscribe(subscriber);
}

/*************************************************************************
	Subscribe to an event group
*************************************************************************/
Event::Connection EventSet::subscribeEvent(const String& name, Event::Group group, Event::Subscriber subscriber)
{
    // do subscription with group & return connection
    return getEventObject(name, true)->subscribe(group, subscriber);
}

/*************************************************************************
	Fire / Trigger an event
*************************************************************************/
void EventSet::fireEvent(const String& name, EventArgs& args, const String& eventNamespace)
{
    // handle global events
    GlobalEventSet::getSingleton().fireEvent(name, args, eventNamespace);
    // handle local event
    fireEvent_impl(name, args);
}

/*************************************************************************
	Return whether the EventSet is muted or not.
*************************************************************************/
bool EventSet::isMuted(void) const
{
	return d_muted;
}

/*************************************************************************
	Set the mute state for this EventSet.
*************************************************************************/
void EventSet::setMutedState(bool setting)
{
	d_muted = setting;
}

/*************************************************************************
    Return the named Event object, optionally adding it to the set
    if needed
*************************************************************************/
Event* EventSet::getEventObject(const String& name, bool autoAdd)
{
    EventMap::iterator pos = d_events.find(name);

    // if event did not exist, add it and then find it.
    if (pos == d_events.end())
    {
        if (autoAdd)
        {
            addEvent(name);
            return d_events.find(name)->second;
        }
        else
        {
            return 0;
        }
    }

    return pos->second;
}

/*************************************************************************

*************************************************************************/
void EventSet::fireEvent_impl(const String& name, EventArgs& args)
{
    // find event object
    Event* ev = getEventObject(name);

    // fire the event if present and set is not muted
    if ((ev != 0) && !d_muted)
        (*ev)(args);
}

/*************************************************************************
	Return a EventSet::EventIterator object to iterate over the available
	events.
*************************************************************************/
EventSet::EventIterator EventSet::getIterator(void) const
{
	return EventIterator(d_events.begin(), d_events.end());
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#include "CatBlockerApp.h"

#include <cinder/gl/gl.h>

using ci::Color;
using ci::gl::clear;

void CatBlockerApp::prepareSettings(Settings *settings)
{
  settings->setWindowSize(0, 0);
  settings->setBorderless(true);
}

void CatBlockerApp::setup()
{

}

void CatBlockerApp::update()
{
  input_.update();
  if (input_.isSpaceDown() && input_.isLControlDown() && input_.isTabDown()) {
    setFullScreen(false);
  }
  else if (input_.countKeysDown() >= 4) {
    setFullScreen(true);
  }
}

void CatBlockerApp::draw()
{
  clear(Color(255, 0, 0), true);
}
<commit_msg>Fix for #2, making app's window always on top.<commit_after>#include "CatBlockerApp.h"

#include <cinder/gl/gl.h>

using ci::Color;
using ci::gl::clear;

void CatBlockerApp::prepareSettings(Settings *settings)
{
  settings->setWindowSize(0, 0);
  settings->setBorderless(true);
  settings->setAlwaysOnTop(true);
}

void CatBlockerApp::setup()
{

}

void CatBlockerApp::update()
{
  input_.update();
  if (input_.isSpaceDown() && input_.isLControlDown() && input_.isTabDown()) {
    setFullScreen(false);
  }
  else if (input_.countKeysDown() >= 4) {
    setFullScreen(true);
  }
}

void CatBlockerApp::draw()
{
  clear(Color(255, 0, 0), true);
}
<|endoftext|>