<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#ifndef DO_KDTREE_KDTREE_HPP
#define DO_KDTREE_KDTREE_HPP

// DISCLAIMER REGARDING FLANN 1.8.4:
//
// I have disabled compiler warnings for MSVC in the CMakeLists.txt of FLANN.
//
// There is still a disturbing compiler warning with MSVC:
// FLANN 1.8.4 will issue compiler warning because of a reimplemented
// operator new*(...) and the corresponding operator delete [] is not implemented.
// I seriously hope there won't be memory-leak as argued in the changelog...
// serialization functions in FLANN 1.8.4 do not compile as well...

#include <DO/Core.hpp>
#include <flann/flann.hpp>

// The data structure will likely evolve again in order to be fully "templated".
// Still, it is enough as it does what I need to do.
// See if the compile time of template instantiation is not a burden for a quick
// prototyping in practice.

namespace DO {

  /*! VERY IMPORTANT TECHNICAL DETAIL: MatrixXd uses a *** COLUMN-MAJOR ***
   *  storage in the core library.
   *  The matrix must be transposed before.
   *  I say this because it seems common to stack data in a row major fashion.
   *
   *  Therefore, data points are column vectors in MatrixXd !!
   *  However FLANN uses a row major storage.
   *  So, please listen to Michael Jackson:
   *    DO THINK TWICE ! (... She told my baby that we danced 'til three...)
   *  And have a look on the DOKDTree.cpp, which tests the KDTree data-structure
   */
  class KDTree
  {
  public:
    KDTree(const MatrixXd& colMajorColStackedDataMatrix,
           const flann::KDTreeIndexParams& indexParams = flann::KDTreeIndexParams(1),
           const flann::SearchParams& searchParams = flann::SearchParams(-1));
    ~KDTree();

    //! Basic k-NN search wrapped function.
    template <int N, int Options, int MaxRows, int MaxCols>
    void knnSearch(const Matrix<double, N, 1, Options, MaxRows, MaxCols>& query,
                   size_t k,
                   std::vector<int>& indices, std::vector<double>& sqDists,
                   bool remove1NN = false)
    {
      if (data_.cols != query.size())
        throw std::runtime_error("Dimension of query vector do not match \
                                 dimension of input feature space!");
      if (remove1NN)
      {
        knnSearch(query.data(), k+1, indices, sqDists);
        indices.erase(indices.begin());
        sqDists.erase(sqDists.begin());
      }
      else
        knnSearch(query.data(), k, indices, sqDists);
    }
    //! Basic k-NN search wrapped function.
    template <int N, int Options, int MaxRows, int MaxCols>
    void knnSearch(const Matrix<double, N, 1, Options, MaxRows, MaxCols>& query,
                   size_t k, std::vector<int>& indices,
                   bool remove1NN = false)
    {
      if (data_.cols != query.size())
        throw std::runtime_error("Dimension of query vector do not match \
                                 dimension of input feature space!");
      std::vector<double> sqDists;
      if (remove1NN)
      {
        knnSearch(query.data(), k+1, indices, sqDists);
        indices.erase(indices.begin());
        sqDists.erase(sqDists.begin());
      }
      else
        knnSearch(query.data(), k, indices, sqDists);
    }
    //! Basic k-NN search  wrapped function.
    void knnSearch(const MatrixXd& queries, size_t k,
                   std::vector<std::vector<int> >& indices,
                   std::vector<std::vector<double> >& sqDists,
                   bool remove1NN = false);
    //! Basic k-NN search wrapped function.
    void knnSearch(const MatrixXd& queries, size_t k,
                   std::vector<std::vector<int> >& indices,
                   bool remove1NN = false);
    //! In case the point query is a point in data, call this method preferably.
    void knnSearch(size_t i, size_t k,
                   std::vector<int>& indices, std::vector<double>& sqDists);
    //! In case the point query is a point in data, call this method preferably.
    void knnSearch(size_t i, size_t k, std::vector<int>& indices);
    //! In case the point query is a point in data, call this method preferably.
    void knnSearch(const std::vector<size_t>& queries, size_t k,
                   std::vector<std::vector<int> >& indices,
                   std::vector<std::vector<double> >& sqDists);
    //! In case the point query is a point in data, call this method preferably.
    void knnSearch(const std::vector<size_t>& queries, size_t k,
                   std::vector<std::vector<int> >& indices);

    //! Basic radius search wrapped function.
    template <int N, int Options, int MaxRows, int MaxCols>
    size_t radiusSearch(const Matrix<double, N, 1, Options, MaxRows, MaxCols>& query,
                        double sqSearchRadius,
                        std::vector<int>& indices, std::vector<double>& sqDists,
                        bool remove1NN = false)
    {
      if (data_.cols != query.size())
          throw std::runtime_error("Dimension of query vector do not match \
                                   dimension of input feature space!");
      radiusSearch(query.data(), sqSearchRadius, indices, sqDists);
      if (remove1NN)
      {
        indices.erase(indices.begin());
        sqDists.erase(sqDists.begin());
      }
      return indices.size();
    }
    //! Basic radius search wrapped function.
    template <int N, int Options, int MaxRows, int MaxCols>
    size_t radiusSearch(const Matrix<double, N, 1, Options, MaxRows, MaxCols>& query,
                        double sqSearchRadius, std::vector<int>& indices,
                        bool remove1NN = false)
    {
      if (data_.cols != query.size())
          throw std::runtime_error("Dimension of query vector do not match \
                                   dimension of input feature space!");
      std::vector<double> sqDists;
      radiusSearch(query.data(), sqSearchRadius, indices, sqDists);
      if (remove1NN)
      {
        indices.erase(indices.begin());
        sqDists.erase(sqDists.begin());
      }
      return indices.size();
    }
    //! Basic radius search wrapped function.
    void radiusSearch(const MatrixXd& queries, double sqSearchRadius,
                      std::vector<std::vector<int> >& indices,
                      std::vector<std::vector<double> >& sqDists,
                      bool remove1NN = false);
    //! Basic radius search wrapped function.
    void radiusSearch(const MatrixXd& queries, double sqSearchRadius,
                      std::vector<std::vector<int> >& indices,
                      bool remove1NN);
    //! In case the point query is a point in data, call this method preferably.
    int radiusSearch(size_t i, double sqSearchRadius,
                      std::vector<int>& indices, std::vector<double>& sqDists);
    //! In case the point query is a point in data, call this method preferably.
    int radiusSearch(size_t i, double sqSearchRadius, std::vector<int>& indices);
    //! In case the point query is a point in data, call this method preferably.
    void radiusSearch(const std::vector<size_t>& queries, double sqSearchRadius,
                      std::vector<std::vector<int> >& indices,
                      std::vector<std::vector<double> >& sqDists);
    //! In case the point query is a point in data, call this method preferably.
    void radiusSearch(const std::vector<size_t>& queries, double sqSearchRadius,
                      std::vector<std::vector<int> >& indices);

  private:
    void knnSearch(const double *query, size_t k,
                  std::vector<int>& indices, std::vector<double>& sqDists);

    int radiusSearch(const double *query, double sqSearchRadius,
                      std::vector<int>& indices, std::vector<double>& sqDists);

  private:
    bool wrapped_data_;
    flann::Matrix<double> data_;
    flann::Index<flann::L2<double> > index_;
    flann::KDTreeIndexParams index_params_;
    flann::SearchParams search_params_;
  };

}

#endif /* DO_KDTREE_KDTREE_HPP */<commit_msg>Clean up code.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#ifndef DO_KDTREE_KDTREE_HPP
#define DO_KDTREE_KDTREE_HPP

#include <DO/Core.hpp>
#include <flann/flann.hpp>

namespace DO {

  /*!
   *  N.B.: MatrixXd uses a *** COLUMN-MAJOR *** storage in the core library.
   *  The matrix must be transposed before.
   *
   *  Therefore, data points are column vectors in MatrixXd !!
   */
  class KDTree
  {
  public:
    //! Constructor.
    KDTree(const MatrixXd& colMajorColStackedDataMatrix,
           const flann::KDTreeIndexParams& indexParams
             = flann::KDTreeIndexParams(1),
           const flann::SearchParams& searchParams
             = flann::SearchParams(-1));

    //! \brief Destructor
    ~KDTree();

    //! Basic k-NN search wrapped function.
    template <int N>
    void knn_search(const Matrix<double, N, 1>& query,
                    size_t k,
                    std::vector<int>& indices,
                    std::vector<double>& sqDists,
                    bool remove1NN = false)
    {
      if (data_.cols != query.size())
        throw std::runtime_error("Dimension of query vector do not match \
                                 dimension of input feature space!");
      if (remove1NN)
      {
        knn_search(query.data(), k+1, indices, sqDists);
        indices.erase(indices.begin());
        sqDists.erase(sqDists.begin());
      }
      else
        knn_search(query.data(), k, indices, sqDists);
    }

    //! Basic k-NN search wrapped function.
    template <int N, int Options, int MaxRows, int MaxCols>
    void knn_search(const Matrix<double, N, 1, Options, MaxRows, MaxCols>& query,
                    size_t k, std::vector<int>& indices,
                    bool remove1NN = false)
    {
      if (data_.cols != query.size())
        throw std::runtime_error("Dimension of query vector do not match \
                                 dimension of input feature space!");
      std::vector<double> sqDists;
      if (remove1NN)
      {
        knn_search(query.data(), k+1, indices, sqDists);
        indices.erase(indices.begin());
        sqDists.erase(sqDists.begin());
      }
      else
        knn_search(query.data(), k, indices, sqDists);
    }

    //! Basic k-NN search  wrapped function.
    void knn_search(const MatrixXd& queries, size_t k,
                   std::vector<std::vector<int> >& indices,
                   std::vector<std::vector<double> >& sqDists,
                   bool remove1NN = false);

    //! Basic k-NN search wrapped function.
    void knn_search(const MatrixXd& queries, size_t k,
                   std::vector<std::vector<int> >& indices,
                   bool remove1NN = false);

    //! In case the point query is a point in data, call this method preferably.
    void knn_search(size_t i, size_t k,
                    std::vector<int>& indices, std::vector<double>& sqDists);

    //! In case the point query is a point in data, call this method preferably.
    void knn_search(size_t i, size_t k, std::vector<int>& indices);

    //! In case the point query is a point in data, call this method preferably.
    void knn_search(const std::vector<size_t>& queries, size_t k,
                    std::vector<std::vector<int> >& indices,
                    std::vector<std::vector<double> >& sqDists);

    //! In case the point query is a point in data, call this method preferably.
    void knn_search(const std::vector<size_t>& queries, size_t k,
                    std::vector<std::vector<int> >& indices);

    //! Basic radius search wrapped function.
    template <int N>
    size_t radius_search(const Matrix<double, N, 1>& query,
                         double sqSearchRadius,
                         std::vector<int>& indices,
                         std::vector<double>& sqDists,
                         bool remove1NN = false)
    {
      if (data_.cols != query.size())
          throw std::runtime_error("Dimension of query vector do not match \
                                   dimension of input feature space!");
      radius_search(query.data(), sqSearchRadius, indices, sqDists);
      if (remove1NN)
      {
        indices.erase(indices.begin());
        sqDists.erase(sqDists.begin());
      }
      return indices.size();
    }

    //! Basic radius search wrapped function.
    template <int N, int Options, int MaxRows, int MaxCols>
    size_t radius_search(const Matrix<double, N, 1>& query,
                         double sqSearchRadius,
                         std::vector<int>& indices,
                         bool remove1NN = false)
    {
      if (data_.cols != query.size())
          throw std::runtime_error("Dimension of query vector do not match \
                                   dimension of input feature space!");
      std::vector<double> sqDists;
      radius_search(query.data(), sqSearchRadius, indices, sqDists);
      if (remove1NN)
      {
        indices.erase(indices.begin());
        sqDists.erase(sqDists.begin());
      }
      return indices.size();
    }

    //! Basic radius search wrapped function.
    void radius_search(const MatrixXd& queries, double sqSearchRadius,
                       std::vector<std::vector<int> >& indices,
                       std::vector<std::vector<double> >& sqDists,
                       bool remove1NN = false);

    //! Basic radius search wrapped function.
    void radius_search(const MatrixXd& queries, double sqSearchRadius,
                       std::vector<std::vector<int> >& indices,
                       bool remove1NN);

    //! In case the point query is a point in data, call this method preferably.
    int radius_search(size_t i, double sqSearchRadius,
                      std::vector<int>& indices, std::vector<double>& sqDists);

    //! In case the point query is a point in data, call this method preferably.
    int radius_search(size_t i, double sqSearchRadius,
                      std::vector<int>& indices);

    //! In case the point query is a point in data, call this method preferably.
    void radius_search(const std::vector<size_t>& queries, double sqSearchRadius,
                       std::vector<std::vector<int> >& indices,
                       std::vector<std::vector<double> >& sqDists);

    //! In case the point query is a point in data, call this method preferably.
    void radius_search(const std::vector<size_t>& queries,
                       double sqSearchRadius,
                       std::vector<std::vector<int> >& indices);

  private:
    void knn_search(const double *query, size_t k,
                    std::vector<int>& indices, std::vector<double>& sqDists);

    int radius_search(const double *query, double sqSearchRadius,
                      std::vector<int>& indices, std::vector<double>& sqDists);

  private:
    bool wrapped_data_;
    flann::Matrix<double> data_;
    flann::Index<flann::L2<double> > index_;
    flann::KDTreeIndexParams index_params_;
    flann::SearchParams search_params_;
  };

}

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


<commit_before>//
// Created by admarkov on 25.04.17.
//

#include "ast.h"
#include "tokens.h"

Node* buildAST(TokenStream stream, Node* root = nullptr, Node* p = nullptr) {
    if (stream.findInflection()!=-1) {
        TokenStream left, right;
        Token inflection;
        stream.split(inflection,left,right);
        Node* n = new Node(p, inflection.data, nullptr, nullptr);
        if (root==nullptr) root=n;
        n->left=buildAST(left, root, n);
        n->right=buildAST(right, root, n);
        return n;
    }
    else {
        Token t = stream.get(1);
        if (t.data!="(") {
            if (t.type=="function") {
                Node *n = new Node(p, t.data, nullptr, nullptr);
                if (root == nullptr) root = n;
                stream.breakBrackets();
                n->left=buildAST(stream, root, n);
                return n;
            }
            if (t.type=="constant") {
                Node *n = new Node(p, t.data, nullptr, nullptr);
                if (root == nullptr) root = n;
                return n;
            }
            if (t.type=="variable") {
                var *n = new var(t.data, root, p);
                if (n->root==nullptr) n->root=n;
                return (Node*)n;
            }
        }
        else {
            stream.breakBrackets();
            return buildAST(stream, root, p);
        }
    }
}<commit_msg>Abandoned of "var" subclass<commit_after>//
// Created by admarkov on 25.04.17.
//

#include "ast.h"
#include "tokens.h"

Node* buildAST(TokenStream stream, Node* root = nullptr, Node* p = nullptr) {
    if (stream.findInflection()!=-1) {
        TokenStream left, right;
        Token inflection;
        stream.split(inflection,left,right);
        Node* n = new Node(p, root, "operator", inflection.data, nullptr, nullptr);
        if (root==nullptr) root=n;
        n->left=buildAST(left, root, n);
        n->right=buildAST(right, root, n);
        return n;
    }
    else {
        Token t = stream.get(1);
        if (t.data!="(") {
            if (t.type=="function") {
                Node *n = new Node(p, root, t.type, t.data, nullptr, nullptr);
                if (root == nullptr) root = n;
                stream.breakBrackets();
                n->left=buildAST(stream, root, n);
                return n;
            }
            if (t.type=="constant") {
                Node *n = new Node(p, root, t.type, t.data, nullptr, nullptr);
                if (root == nullptr) root = n;
                return n;
            }
            if (t.type=="variable") {
                Node *n = new Node(p, root, t.type, t.data, nullptr, nullptr);
                if (n->root==nullptr) n->root=n;
                return (Node*)n;
            }
        }
        else {
            stream.breakBrackets();
            return buildAST(stream, root, p);
        }
    }
}<|endoftext|>


<commit_before>#include "window.h"
#include "map_window.h"
#include "inspection_window.h"
#include "equipment_window.h"
#include "gameengine.h"
#include "event.h"

void MapWindow::gainFocus ()
{
    getEngine()->loadMap(50, 50);

    setTitle ("Map");

    m_mapXOffset = 1;
    m_mapYOffset = 9;
    m_mapStartX = 0;
    m_mapStartY = 0;
    m_mapWidth  = 0;
    m_mapHeight = 0;
    m_sidebarWidth = 20;
    m_sidebarXOffset = getWidth() - m_sidebarWidth;

    m_action = 'm';
    m_lastDraw = clock();
}

void MapWindow::redraw() {

    //clock_t l_clock = clock() - m_lastDraw;
    //double l_diff = static_cast<double> (l_clock/CLOCKS_PER_SEC);
    //if (l_diff < 0.01f) return;

    drawSeparators();
    drawMap();
    drawMessages();
    drawSidebar();
}

void MapWindow::resize() {
    setDimensions (0, 0, getEngine()->getGraphics()->getScreenWidth(), getEngine()->getGraphics()->getScreenHeight());
    m_sidebarXOffset = getWidth() - m_sidebarWidth - 1;
    m_mapWidth  = getWidth() - m_mapXOffset - m_sidebarWidth - 1;
    m_mapHeight = getHeight() - m_mapYOffset - 1;
}

void MapWindow::keyDown (unsigned char key) {
    Window::keyDown (key);

    if (key == 'w' || key == 'a' || key == 's' || key == 'd') {
        DIRECTION l_dir = Direction::None;
        switch (key) {
            case 'w': l_dir = Direction::North; break;
            case 'a': l_dir = Direction::West;  break;
            case 's': l_dir = Direction::South; break;
            case 'd': l_dir = Direction::East;  break;
        }

        if (m_action == 'm') {
            MoveEntityEvent* l_event = new MoveEntityEvent;
            l_event->entity = getEngine()->getEntities()->getPlayer();
            l_event->direction = l_dir;
            getEngine()->raiseEvent (l_event);
        }
        if (m_action == 'k') {
            AttackEntityEvent* l_event = new AttackEntityEvent;
            l_event->entity = getEngine()->getEntities()->getPlayer();
            l_event->direction = l_dir;
            getEngine()->raiseEvent (l_event);
        }
        if (m_action == 'i') {
            EntityHolder l_entities = getEngine()->getEntities()->findEntitiesToThe(l_dir, getEngine()->getEntities()->getPlayer());
            if (l_entities.size() > 0) {
                EntityId* l_target = new EntityId(*l_entities.begin());

                InspectionWindow* l_win = new InspectionWindow();
                l_win->initialise(getEngine(), l_target);
                getEngine()->getWindows()->pushWindow (l_win);
            }
        }
        if (m_action != 'i') getEngine()->swapTurn();
        m_action = 'm';
    }
    if (key == 27) {
        getEngine()->quit();
    }
    if (key == 'm' ||
        key == 'k' ||
        key == 'i') {
        m_action = key;
    }
    if (key == '.') {
        getEngine()->swapTurn();
    }
    if (key == 'p') {
        Location l_playerLoc = getEngine()->getEntities()->getLocation(getEngine()->getEntities()->getPlayer());
        EntityHolder l_entities = getEngine()->getEntities()->findEntitiesAt (l_playerLoc.x, l_playerLoc.y);
        bool foundSomethingAlready = false;
        for (EntityId l_entity : l_entities) {
            DroppableComponent* droppable = getEngine()->getEntities()->getDroppables()->get(l_entity);
            if (droppable) {
                if (!foundSomethingAlready) {
                    PickupEquipmentEvent* event = new PickupEquipmentEvent();
                    event->entity = getEngine()->getEntities()->getPlayer();
                    event->item = l_entity;
                    getEngine()->raiseEvent (event);
                    foundSomethingAlready = true;
                } else {
                    getEngine()->addMessage(INFO, "There's something else here...");
                    break;
                }
            }
        }
        if (!foundSomethingAlready) {
            getEngine()->addMessage(INFO, "There's nothing here...");
        }
    }
    if (key == 'E') {
        EquipmentWindow* l_win = new EquipmentWindow();
        l_win->initialise(getEngine());
        getEngine()->getWindows()->pushWindow (l_win);
    }
}

void MapWindow::drawSeparators() {
    getEngine()->getGraphics()->drawBorder (m_mapYOffset-1, m_mapXOffset-1, m_mapHeight, m_mapWidth);
    getEngine()->getGraphics()->drawBorder (0, m_sidebarXOffset, getHeight()-2, m_sidebarWidth-1);
}

void MapWindow::drawMap() {
    Location l_player = getEngine()->getEntities()->getLocation(getEngine()->getEntities()->getPlayer());
    m_mapStartX = l_player.x - (m_mapWidth/2);
    m_mapStartY = l_player.y - (m_mapHeight/2);

    int xWidth = m_mapStartX + m_mapWidth;
    int yWidth = m_mapStartY + m_mapHeight;

    for (int yy = m_mapStartY; yy < yWidth; yy++) {
        for (int xx = m_mapStartX; xx < xWidth; xx++) {
            if (!getEngine()->isValidTile (xx, yy, getEngine()->getLevel())) continue;
            Tile& l_tile = getEngine()->getTile (xx, yy, getEngine()->getLevel());
            for (EntityId entity : l_tile.entities) {
                SpriteComponent* l_sprite= getEngine()->getEntities()->getSprites()->get (entity);
                if (!l_sprite) continue;
                drawTile (  yy + m_mapYOffset - m_mapStartY,
                            xx + m_mapXOffset - m_mapStartX,
                            l_sprite->sprite,
                            l_sprite->fgColor,
                            l_sprite->bgColor);

            }
        }
    }

    return;
}

void MapWindow::drawMessages()
{
    std::vector<Message>& l_messages = getEngine()->getMessages();
    size_t ii = l_messages.size();
    size_t hh = m_mapYOffset-2;

    for (; ii > 0 && hh > 0; hh--, ii--) {
        Color fg;
        switch (l_messages[ii-1].severity) {
            case INFO: fg = Color (WHITE); break;
            case WARN: fg = Color (RED); break;
            case GOOD: fg = Color (GREEN); break;
            case CRIT: fg = Color (BLUE); break;
        }
        drawString (hh, 1, l_messages[ii-1].message.c_str(), fg);
    }
}

void MapWindow::drawSidebar ()
{
    // Current health
    drawString (2, m_sidebarXOffset+2, "Health:");
    EntityId player = getEngine()->getEntities()->getPlayer();
    HealthComponent* l_health = getEngine()->getEntities()->getHealths()->get(player);
    if (l_health) {
        drawProgressBar (m_sidebarXOffset+10, 2, l_health->health);

    }

    // Actions to take
    drawString (getHeight()-8, m_sidebarXOffset+2, "pickup Items");
    drawString (getHeight()-8, m_sidebarXOffset+2, "p", Color (GREEN));

    drawString (getHeight()-7, m_sidebarXOffset+2, "move (wasd)");
    drawString (getHeight()-7, m_sidebarXOffset+2, "m", Color (GREEN));
    if (m_action == 'm') drawString (getHeight()-7, m_sidebarXOffset+1, ">", Color (RED));

    drawString (getHeight()-6, m_sidebarXOffset+2, "attack (wasd)");
    drawString (getHeight()-6, m_sidebarXOffset+7, "k", Color (GREEN));
    if (m_action == 'k') drawString (getHeight()-6, m_sidebarXOffset+1, ">", Color (RED));

    drawString (getHeight()-5, m_sidebarXOffset+2, "inspect (wasd)");
    drawString (getHeight()-5, m_sidebarXOffset+2, "i", Color (GREEN));
    if (m_action == 'i') drawString (getHeight()-5, m_sidebarXOffset+1, ">", Color (RED));

    drawString (getHeight()-4, m_sidebarXOffset+2, "skip turn (.)");
    drawString (getHeight()-4, m_sidebarXOffset+13, ".", Color (GREEN));

    drawString (getHeight()-2, m_sidebarXOffset+2, "View Equipment");
    drawString (getHeight()-2, m_sidebarXOffset+7, "E", Color (GREEN));
}

void MapWindow::drawProgressBar (int x, int y, int value)
{
    float l_value = (float) value;
    Color l_color ((1.0f-(l_value/10.0f)), l_value/10.0f, 0);

    for (int xx = 0; xx < value; xx++) {
        drawTile (y, x+xx, 178, l_color, Color(BLACK));
    }
}
<commit_msg>Dim all tiles not in the viscinity of the player<commit_after>#include "window.h"
#include "map_window.h"
#include "inspection_window.h"
#include "equipment_window.h"
#include "gameengine.h"
#include "event.h"

void MapWindow::gainFocus ()
{
    getEngine()->loadMap(50, 50);

    setTitle ("Map");

    m_mapXOffset = 1;
    m_mapYOffset = 9;
    m_mapStartX = 0;
    m_mapStartY = 0;
    m_mapWidth  = 0;
    m_mapHeight = 0;
    m_sidebarWidth = 20;
    m_sidebarXOffset = getWidth() - m_sidebarWidth;

    m_action = 'm';
    m_lastDraw = clock();
}

void MapWindow::redraw() {

    //clock_t l_clock = clock() - m_lastDraw;
    //double l_diff = static_cast<double> (l_clock/CLOCKS_PER_SEC);
    //if (l_diff < 0.01f) return;

    drawSeparators();
    drawMap();
    drawMessages();
    drawSidebar();
}

void MapWindow::resize() {
    setDimensions (0, 0, getEngine()->getGraphics()->getScreenWidth(), getEngine()->getGraphics()->getScreenHeight());
    m_sidebarXOffset = getWidth() - m_sidebarWidth - 1;
    m_mapWidth  = getWidth() - m_mapXOffset - m_sidebarWidth - 1;
    m_mapHeight = getHeight() - m_mapYOffset - 1;
}

void MapWindow::keyDown (unsigned char key) {
    Window::keyDown (key);

    if (key == 'w' || key == 'a' || key == 's' || key == 'd') {
        DIRECTION l_dir = Direction::None;
        switch (key) {
            case 'w': l_dir = Direction::North; break;
            case 'a': l_dir = Direction::West;  break;
            case 's': l_dir = Direction::South; break;
            case 'd': l_dir = Direction::East;  break;
        }

        if (m_action == 'm') {
            MoveEntityEvent* l_event = new MoveEntityEvent;
            l_event->entity = getEngine()->getEntities()->getPlayer();
            l_event->direction = l_dir;
            getEngine()->raiseEvent (l_event);
        }
        if (m_action == 'k') {
            AttackEntityEvent* l_event = new AttackEntityEvent;
            l_event->entity = getEngine()->getEntities()->getPlayer();
            l_event->direction = l_dir;
            getEngine()->raiseEvent (l_event);
        }
        if (m_action == 'i') {
            EntityHolder l_entities = getEngine()->getEntities()->findEntitiesToThe(l_dir, getEngine()->getEntities()->getPlayer());
            if (l_entities.size() > 0) {
                EntityId* l_target = new EntityId(*l_entities.begin());

                InspectionWindow* l_win = new InspectionWindow();
                l_win->initialise(getEngine(), l_target);
                getEngine()->getWindows()->pushWindow (l_win);
            }
        }
        if (m_action != 'i') getEngine()->swapTurn();
        m_action = 'm';
    }
    if (key == 27) {
        getEngine()->quit();
    }
    if (key == 'm' ||
        key == 'k' ||
        key == 'i') {
        m_action = key;
    }
    if (key == '.') {
        getEngine()->swapTurn();
    }
    if (key == 'p') {
        Location l_playerLoc = getEngine()->getEntities()->getLocation(getEngine()->getEntities()->getPlayer());
        EntityHolder l_entities = getEngine()->getEntities()->findEntitiesAt (l_playerLoc.x, l_playerLoc.y);
        bool foundSomethingAlready = false;
        for (EntityId l_entity : l_entities) {
            DroppableComponent* droppable = getEngine()->getEntities()->getDroppables()->get(l_entity);
            if (droppable) {
                if (!foundSomethingAlready) {
                    PickupEquipmentEvent* event = new PickupEquipmentEvent();
                    event->entity = getEngine()->getEntities()->getPlayer();
                    event->item = l_entity;
                    getEngine()->raiseEvent (event);
                    foundSomethingAlready = true;
                } else {
                    getEngine()->addMessage(INFO, "There's something else here...");
                    break;
                }
            }
        }
        if (!foundSomethingAlready) {
            getEngine()->addMessage(INFO, "There's nothing here...");
        }
    }
    if (key == 'E') {
        EquipmentWindow* l_win = new EquipmentWindow();
        l_win->initialise(getEngine());
        getEngine()->getWindows()->pushWindow (l_win);
    }
}

void MapWindow::drawSeparators() {
    getEngine()->getGraphics()->drawBorder (m_mapYOffset-1, m_mapXOffset-1, m_mapHeight, m_mapWidth);
    getEngine()->getGraphics()->drawBorder (0, m_sidebarXOffset, getHeight()-2, m_sidebarWidth-1);
}

void MapWindow::drawMap() {
    Location l_player = getEngine()->getEntities()->getLocation(getEngine()->getEntities()->getPlayer());
    m_mapStartX = l_player.x - (m_mapWidth/2);
    m_mapStartY = l_player.y - (m_mapHeight/2);

    int xWidth = m_mapStartX + m_mapWidth;
    int yWidth = m_mapStartY + m_mapHeight;

    for (int yy = m_mapStartY; yy < yWidth; yy++) {
        for (int xx = m_mapStartX; xx < xWidth; xx++) {
            if (!getEngine()->isValidTile (xx, yy, getEngine()->getLevel())) continue;
            Tile& l_tile = getEngine()->getTile (xx, yy, getEngine()->getLevel());
            for (EntityId entity : l_tile.entities) {
                SpriteComponent* l_sprite= getEngine()->getEntities()->getSprites()->get (entity);
                if (!l_sprite) continue;
                Color fgColor = l_sprite->fgColor;
                if (    xx < (int)l_player.x - 3 || xx > (int)l_player.x + 3
                    ||  yy < (int)l_player.y - 3 || yy > (int)l_player.y + 3) {
                    fgColor.Red()   *= 0.4;
                    fgColor.Green() *= 0.4;
                    fgColor.Blue()  *= 0.4;
                }
                drawTile (  yy + m_mapYOffset - m_mapStartY,
                            xx + m_mapXOffset - m_mapStartX,
                            l_sprite->sprite,
                            fgColor,
                            l_sprite->bgColor);

            }
        }
    }

    return;
}

void MapWindow::drawMessages()
{
    std::vector<Message>& l_messages = getEngine()->getMessages();
    size_t ii = l_messages.size();
    size_t hh = m_mapYOffset-2;

    for (; ii > 0 && hh > 0; hh--, ii--) {
        Color fg;
        switch (l_messages[ii-1].severity) {
            case INFO: fg = Color (WHITE); break;
            case WARN: fg = Color (RED); break;
            case GOOD: fg = Color (GREEN); break;
            case CRIT: fg = Color (BLUE); break;
        }
        drawString (hh, 1, l_messages[ii-1].message.c_str(), fg);
    }
}

void MapWindow::drawSidebar ()
{
    // Current health
    drawString (2, m_sidebarXOffset+2, "Health:");
    EntityId player = getEngine()->getEntities()->getPlayer();
    HealthComponent* l_health = getEngine()->getEntities()->getHealths()->get(player);
    if (l_health) {
        drawProgressBar (m_sidebarXOffset+10, 2, l_health->health);

    }

    // Actions to take
    drawString (getHeight()-8, m_sidebarXOffset+2, "pickup Items");
    drawString (getHeight()-8, m_sidebarXOffset+2, "p", Color (GREEN));

    drawString (getHeight()-7, m_sidebarXOffset+2, "move (wasd)");
    drawString (getHeight()-7, m_sidebarXOffset+2, "m", Color (GREEN));
    if (m_action == 'm') drawString (getHeight()-7, m_sidebarXOffset+1, ">", Color (RED));

    drawString (getHeight()-6, m_sidebarXOffset+2, "attack (wasd)");
    drawString (getHeight()-6, m_sidebarXOffset+7, "k", Color (GREEN));
    if (m_action == 'k') drawString (getHeight()-6, m_sidebarXOffset+1, ">", Color (RED));

    drawString (getHeight()-5, m_sidebarXOffset+2, "inspect (wasd)");
    drawString (getHeight()-5, m_sidebarXOffset+2, "i", Color (GREEN));
    if (m_action == 'i') drawString (getHeight()-5, m_sidebarXOffset+1, ">", Color (RED));

    drawString (getHeight()-4, m_sidebarXOffset+2, "skip turn (.)");
    drawString (getHeight()-4, m_sidebarXOffset+13, ".", Color (GREEN));

    drawString (getHeight()-2, m_sidebarXOffset+2, "View Equipment");
    drawString (getHeight()-2, m_sidebarXOffset+7, "E", Color (GREEN));
}

void MapWindow::drawProgressBar (int x, int y, int value)
{
    float l_value = (float) value;
    Color l_color ((1.0f-(l_value/10.0f)), l_value/10.0f, 0);

    for (int xx = 0; xx < value; xx++) {
        drawTile (y, x+xx, 178, l_color, Color(BLACK));
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL
 */

#include "QActiveResource.h"
#include <QXmlStreamReader>
#include <QStringList>
#include <QDateTime>
#include <QDebug>
#include <curl/curl.h>

using namespace QActiveResource;

static size_t writer(void *ptr, size_t size, size_t nmemb, void *stream)
{
    reinterpret_cast<QByteArray *>(stream)->append(QByteArray((const char *)(ptr), size * nmemb));
    return size * nmemb;
}

namespace HTTP
{
    QByteArray get(const QUrl &url, bool followRedirects = false)
    {
        QByteArray data;
        CURL *curl = curl_easy_init();

        static const int maxRetry = 1;
        int retry = 0;

        if(curl)
        {
            do
            {
                curl_easy_setopt(curl, CURLOPT_URL, url.toEncoded().data());
                curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
                curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &data);
                curl_easy_setopt(curl, CURLOPT_TIMEOUT, 25);
                curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

                if(followRedirects)
                {
                    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
                    curl_easy_setopt(curl, CURLOPT_UNRESTRICTED_AUTH, 1);
                    curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 2);
                }
            }
            while(curl_easy_perform(curl) != 0 && ++retry <= maxRetry);
            curl_easy_cleanup(curl);
        }

        return data;
    }
}

static QVariant::Type lookupType(const QString &name)
{
    static QHash<QString, QVariant::Type> types;

    if(types.isEmpty())
    {
        types["integer"] = QVariant::Int;
        types["decimal"] = QVariant::Double;
        types["datetime"] = QVariant::DateTime;
        types["boolean"] = QVariant::Bool;
    }

    return types.contains(name) ? types[name] : QVariant::String;
}

static void assign(Record *record, QString name, const QVariant &value)
{
    (*record)[name.replace('-', '_')] = value;
}

static QDateTime toDateTime(const QString &s)
{
    QDateTime time = QDateTime::fromString(s.left(s.length() - 6), Qt::ISODate);

    time.setTimeSpec(Qt::UTC);

    int zoneHours = s.mid(s.length() - 6, 3).toInt();
    int zoneMinutes = s.right(2).toInt();

    return time.addSecs(-1 * (60 * zoneHours + zoneMinutes) * 60);
}

static QVariant reader(QXmlStreamReader &xml, bool advance = true)
{
    Record record;
    QString firstElement;

    while(!xml.atEnd())
    {
        if(advance)
        {
            xml.readNext();
        }
        if(xml.tokenType() == QXmlStreamReader::StartElement)
        {
            if(firstElement.isNull())
            {
                firstElement = xml.name().toString();
            }

            QString type = xml.attributes().value("type").toString();

            if(type == "array")
            {
                QString name = xml.name().toString();
                QList<QVariant> array;

                while(xml.readNext() == QXmlStreamReader::StartElement ||
                      (xml.tokenType() == QXmlStreamReader::Characters && xml.isWhitespace()))
                {
                    if(!xml.isWhitespace())
                    {
                        array.append(reader(xml, false));
                    }
                }

                assign(&record, name, array);
            }
            else if(xml.attributes().value("nil") == "true")
            {
                assign(&record, xml.name().toString(), QVariant());
            }
            else if(advance && xml.name() != firstElement)
            {
                QVariant value;
                QString text = xml.readElementText();

                switch(lookupType(type))
                {
                case QVariant::Int:
                    value = text.toInt();
                    break;
                case QVariant::Double:
                    value = text.toDouble();
                    break;
                case QVariant::DateTime:
                    value = toDateTime(text);
                    break;
                case QVariant::Bool:
                    value = bool(text == "true");
                    break;
                default:
                    value = text;
                }

                assign(&record, xml.name().toString(), value);
            }
        }
        if(xml.tokenType() == QXmlStreamReader::EndElement &&
           !firstElement.isNull() && firstElement == xml.name())
        {
            return record;
        }

        advance = true;
    }

    return QVariant();
}

static RecordList fetch(QUrl url, bool followRedirects = false)
{
    if(!url.path().endsWith(".xml"))
    {
        url.setPath(url.path() + ".xml");
    }

    QByteArray data = HTTP::get(url, followRedirects);

    QXmlStreamReader xml(data);

    QVariant value = reader(xml);
    RecordList records;

    if(value.type() == QVariant::List)
    {
        foreach(QVariant v, value.toList())
        {
            records.append(v.toHash());
        }
    }
    else if(value.type() == QVariant::Hash && value.toHash().size() == 1)
    {
        foreach(QVariant v, value.toHash().begin()->toList())
        {
            records.append(v.toHash());
        }
    }
    else
    {
        records.append(value.toHash());
    }

    return records;
}

/*
 * Param::Data
 */

Param::Data::Data(const QString &k, const QString &v) :
    key(k),
    value(v)
{

}

/*
 * Param
 */

Param::Param() :
    d(0)
{

}

Param::Param(const QString &key, const QString &value) :
    d(new Data(key, value))
{

}

bool Param::isNull() const
{
    return d == 0;
}

QString Param::key() const
{
    return isNull() ? QString() : d->key;
}

QString Param::value() const
{
    return isNull() ? QString() : d->value;
}

/*
 * Resource::Data
 */

Resource::Data::Data(const QUrl &b, const QString &r) :
    base(b),
    resource(r),
    url(base),
    followRedirects(false)
{
    setUrl();
}

void Resource::Data::setUrl()
{
    url = base;
    url.setPath(base.path() + "/" + resource);
}

/*
 * Resource
 */

Resource::Resource(const QUrl &base, const QString &resource) :
    d(new Data(base, resource))
{

}

void Resource::setBase(const QUrl &base)
{
    d->base = base;
    d->setUrl();
}

void Resource::setResource(const QString &resource)
{
    d->resource = resource;
    d->setUrl();
}

Record Resource::find(const QVariant &id) const
{
    return find(FindOne, id.toString());
}

RecordList Resource::find(FindMulti style, const QString &from, const ParamList &params) const
{
    Q_UNUSED(style);

    QUrl url = d->url;

    foreach(Param param, params)
    {
        if(!param.isNull())
        {
            url.addQueryItem(param.key(), param.value());
        }
    }

    if(!from.isEmpty())
    {
        url.setPath(url.path() + "/" + from);
    }

    return fetch(url, d->followRedirects);
}

Record Resource::find(FindSingle style, const QString &from, const ParamList &params) const
{
    QUrl url = d->url;

    foreach(Param param, params)
    {
        if(!param.isNull())
        {
            url.addQueryItem(param.key(), param.value());
        }
    }

    if(!from.isEmpty())
    {
        url.setPath(url.path() + "/" + from);
    }

    switch(style)
    {
    case FindOne:
    case FindFirst:
    {
        RecordList results = find(FindAll, from, params);
        return results.isEmpty() ? Record() : results.front();
    }
    case FindLast:
    {
        RecordList results = find(FindAll, from, params);
        return results.isEmpty() ? Record() : results.back();
    }
    }

    return Record();
}

Record Resource::find(FindSingle style, const QString &from,
                      const Param &first, const Param &second,
                      const Param &third, const Param &fourth) const
{
    return find(style, from, ParamList() << first << second << third << fourth);
}

RecordList Resource::find(FindMulti style, const QString &from,
                          const Param &first, const Param &second,
                          const Param &third, const Param &fourth) const
{
    return find(style, from, ParamList() << first << second << third << fourth);
}

void Resource::setFollowRedirects(bool followRedirects)
{
    d->followRedirects = followRedirects;
}
<commit_msg>Only convert to a hash if there's a value (now returns an empty array for empty result sets)<commit_after>/*
 * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL
 */

#include "QActiveResource.h"
#include <QXmlStreamReader>
#include <QStringList>
#include <QDateTime>
#include <QDebug>
#include <curl/curl.h>

using namespace QActiveResource;

static size_t writer(void *ptr, size_t size, size_t nmemb, void *stream)
{
    reinterpret_cast<QByteArray *>(stream)->append(QByteArray((const char *)(ptr), size * nmemb));
    return size * nmemb;
}

namespace HTTP
{
    QByteArray get(const QUrl &url, bool followRedirects = false)
    {
        QByteArray data;
        CURL *curl = curl_easy_init();

        static const int maxRetry = 1;
        int retry = 0;

        if(curl)
        {
            do
            {
                curl_easy_setopt(curl, CURLOPT_URL, url.toEncoded().data());
                curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
                curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &data);
                curl_easy_setopt(curl, CURLOPT_TIMEOUT, 25);
                curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

                if(followRedirects)
                {
                    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
                    curl_easy_setopt(curl, CURLOPT_UNRESTRICTED_AUTH, 1);
                    curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 2);
                }
            }
            while(curl_easy_perform(curl) != 0 && ++retry <= maxRetry);
            curl_easy_cleanup(curl);
        }

        return data;
    }
}

static QVariant::Type lookupType(const QString &name)
{
    static QHash<QString, QVariant::Type> types;

    if(types.isEmpty())
    {
        types["integer"] = QVariant::Int;
        types["decimal"] = QVariant::Double;
        types["datetime"] = QVariant::DateTime;
        types["boolean"] = QVariant::Bool;
    }

    return types.contains(name) ? types[name] : QVariant::String;
}

static void assign(Record *record, QString name, const QVariant &value)
{
    (*record)[name.replace('-', '_')] = value;
}

static QDateTime toDateTime(const QString &s)
{
    QDateTime time = QDateTime::fromString(s.left(s.length() - 6), Qt::ISODate);

    time.setTimeSpec(Qt::UTC);

    int zoneHours = s.mid(s.length() - 6, 3).toInt();
    int zoneMinutes = s.right(2).toInt();

    return time.addSecs(-1 * (60 * zoneHours + zoneMinutes) * 60);
}

static QVariant reader(QXmlStreamReader &xml, bool advance = true)
{
    Record record;
    QString firstElement;

    while(!xml.atEnd())
    {
        if(advance)
        {
            xml.readNext();
        }
        if(xml.tokenType() == QXmlStreamReader::StartElement)
        {
            if(firstElement.isNull())
            {
                firstElement = xml.name().toString();
            }

            QString type = xml.attributes().value("type").toString();

            if(type == "array")
            {
                QString name = xml.name().toString();
                QList<QVariant> array;

                while(xml.readNext() == QXmlStreamReader::StartElement ||
                      (xml.tokenType() == QXmlStreamReader::Characters && xml.isWhitespace()))
                {
                    if(!xml.isWhitespace())
                    {
                        array.append(reader(xml, false));
                    }
                }

                assign(&record, name, array);
            }
            else if(xml.attributes().value("nil") == "true")
            {
                assign(&record, xml.name().toString(), QVariant());
            }
            else if(advance && xml.name() != firstElement)
            {
                QVariant value;
                QString text = xml.readElementText();

                switch(lookupType(type))
                {
                case QVariant::Int:
                    value = text.toInt();
                    break;
                case QVariant::Double:
                    value = text.toDouble();
                    break;
                case QVariant::DateTime:
                    value = toDateTime(text);
                    break;
                case QVariant::Bool:
                    value = bool(text == "true");
                    break;
                default:
                    value = text;
                }

                assign(&record, xml.name().toString(), value);
            }
        }
        if(xml.tokenType() == QXmlStreamReader::EndElement &&
           !firstElement.isNull() && firstElement == xml.name())
        {
            return record;
        }

        advance = true;
    }

    return QVariant();
}

static RecordList fetch(QUrl url, bool followRedirects = false)
{
    if(!url.path().endsWith(".xml"))
    {
        url.setPath(url.path() + ".xml");
    }

    QByteArray data = HTTP::get(url, followRedirects);

    QXmlStreamReader xml(data);

    QVariant value = reader(xml);
    RecordList records;

    if(value.type() == QVariant::List)
    {
        foreach(QVariant v, value.toList())
        {
            records.append(v.toHash());
        }
    }
    else if(value.type() == QVariant::Hash && value.toHash().size() == 1)
    {
        foreach(QVariant v, value.toHash().begin()->toList())
        {
            records.append(v.toHash());
        }
    }
    else if(value.isValid())
    {
        records.append(value.toHash());
    }

    return records;
}

/*
 * Param::Data
 */

Param::Data::Data(const QString &k, const QString &v) :
    key(k),
    value(v)
{

}

/*
 * Param
 */

Param::Param() :
    d(0)
{

}

Param::Param(const QString &key, const QString &value) :
    d(new Data(key, value))
{

}

bool Param::isNull() const
{
    return d == 0;
}

QString Param::key() const
{
    return isNull() ? QString() : d->key;
}

QString Param::value() const
{
    return isNull() ? QString() : d->value;
}

/*
 * Resource::Data
 */

Resource::Data::Data(const QUrl &b, const QString &r) :
    base(b),
    resource(r),
    url(base),
    followRedirects(false)
{
    setUrl();
}

void Resource::Data::setUrl()
{
    url = base;
    url.setPath(base.path() + "/" + resource);
}

/*
 * Resource
 */

Resource::Resource(const QUrl &base, const QString &resource) :
    d(new Data(base, resource))
{

}

void Resource::setBase(const QUrl &base)
{
    d->base = base;
    d->setUrl();
}

void Resource::setResource(const QString &resource)
{
    d->resource = resource;
    d->setUrl();
}

Record Resource::find(const QVariant &id) const
{
    return find(FindOne, id.toString());
}

RecordList Resource::find(FindMulti style, const QString &from, const ParamList &params) const
{
    Q_UNUSED(style);

    QUrl url = d->url;

    foreach(Param param, params)
    {
        if(!param.isNull())
        {
            url.addQueryItem(param.key(), param.value());
        }
    }

    if(!from.isEmpty())
    {
        url.setPath(url.path() + "/" + from);
    }

    return fetch(url, d->followRedirects);
}

Record Resource::find(FindSingle style, const QString &from, const ParamList &params) const
{
    QUrl url = d->url;

    foreach(Param param, params)
    {
        if(!param.isNull())
        {
            url.addQueryItem(param.key(), param.value());
        }
    }

    if(!from.isEmpty())
    {
        url.setPath(url.path() + "/" + from);
    }

    switch(style)
    {
    case FindOne:
    case FindFirst:
    {
        RecordList results = find(FindAll, from, params);
        return results.isEmpty() ? Record() : results.front();
    }
    case FindLast:
    {
        RecordList results = find(FindAll, from, params);
        return results.isEmpty() ? Record() : results.back();
    }
    }

    return Record();
}

Record Resource::find(FindSingle style, const QString &from,
                      const Param &first, const Param &second,
                      const Param &third, const Param &fourth) const
{
    return find(style, from, ParamList() << first << second << third << fourth);
}

RecordList Resource::find(FindMulti style, const QString &from,
                          const Param &first, const Param &second,
                          const Param &third, const Param &fourth) const
{
    return find(style, from, ParamList() << first << second << third << fourth);
}

void Resource::setFollowRedirects(bool followRedirects)
{
    d->followRedirects = followRedirects;
}
<|endoftext|>


<commit_before>/*
    msnauthsocket.cpp - Socket that does the initial handshake as used by
                         both MSNAuthSocket and MSNNotifySocket

    Copyright (c) 2002 by Martijn Klingens       <klingens@kde.org>
    Kopete    (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

    Portions of this code are taken from KMerlin,
              (c) 2001 by Olaf Lueg              <olueg@olsd.de>

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

#include "msnauthsocket.h"

#include <qtimer.h>

#include <kdebug.h>
#include <klocale.h>
#include <kmessagebox.h>

MSNAuthSocket::MSNAuthSocket( const QString &msnId )
{
	m_msnId = msnId;
	m_msgBoxShown = false;
}

MSNAuthSocket::~MSNAuthSocket()
{
}

void MSNAuthSocket::reconnect()
{
	connect( server(),port() );
}

void MSNAuthSocket::handleError( uint code, uint id )
{
	if( code != 600 )
	{
		MSNSocket::handleError( code, id );
		return;
	}

	disconnect();
	QTimer::singleShot( 10, this, SLOT( reconnect() ) );

	if( !m_msgBoxShown )
	{
		QString msg =
			i18n( "The MSN server is busy.\n"
				"Trying to reconnect every 10 seconds. Please be patient..." );
		m_msgBoxShown = true;

		KMessageBox::information( 0, msg, i18n( "MSN Plugin - Kopete" ) );
	}
}

void MSNAuthSocket::parseCommand( const QString &cmd, uint id,
	const QString &data )
{
	if( cmd == "VER" )
	{
		kdDebug() << "MSNAuthSocket: Requesting authentication method"
			<< endl;
		sendCommand( "INF" );
	}
	else if( cmd == "INF" )
	{
		kdDebug() << "MSNAuthSocket: Requesting MD5 authentication "
			<< "for Passport " << m_msnId << endl;
		sendCommand( "USR", "MD5 I " + m_msnId);
	}
	else
	{
		kdDebug() << "MSNAuthSocket::parseCommand: Unexpected response '"
			<< cmd << " " << id << " " << data << "' from server!" << endl;
	}
}

void MSNAuthSocket::doneConnect()
{
	kdDebug() << "MSNAuthSocket: Negotiating server protocol version"
		<< endl;
	sendCommand( "VER", "MSNP7 MSNP6 MSNP5 MSNP4 CVR0" );
}

#include "msnauthsocket.moc"

/*
 * Local variables:
 * c-indentation-style: k&r
 * c-basic-offset: 8
 * indent-tabs-mode: t
 * End:
 */
// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>change text in debug output: 'unexepted' => 'unimplemented' to prevent confision<commit_after>/*
    msnauthsocket.cpp - Socket that does the initial handshake as used by
                         both MSNAuthSocket and MSNNotifySocket

    Copyright (c) 2002 by Martijn Klingens       <klingens@kde.org>
    Kopete    (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

    Portions of this code are taken from KMerlin,
              (c) 2001 by Olaf Lueg              <olueg@olsd.de>

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

#include "msnauthsocket.h"

#include <qtimer.h>

#include <kdebug.h>
#include <klocale.h>
#include <kmessagebox.h>

MSNAuthSocket::MSNAuthSocket( const QString &msnId )
{
	m_msnId = msnId;
	m_msgBoxShown = false;
}

MSNAuthSocket::~MSNAuthSocket()
{
}

void MSNAuthSocket::reconnect()
{
	connect( server(),port() );
}

void MSNAuthSocket::handleError( uint code, uint id )
{
	if( code != 600 )
	{
		MSNSocket::handleError( code, id );
		return;
	}

	disconnect();
	QTimer::singleShot( 10, this, SLOT( reconnect() ) );

	if( !m_msgBoxShown )
	{
		QString msg =
			i18n( "The MSN server is busy.\n"
				"Trying to reconnect every 10 seconds. Please be patient..." );
		m_msgBoxShown = true;

		KMessageBox::information( 0, msg, i18n( "MSN Plugin - Kopete" ) );
	}
}

void MSNAuthSocket::parseCommand( const QString &cmd, uint id,
	const QString &data )
{
	if( cmd == "VER" )
	{
		kdDebug() << "MSNAuthSocket: Requesting authentication method"
			<< endl;
		sendCommand( "INF" );
	}
	else if( cmd == "INF" )
	{
		kdDebug() << "MSNAuthSocket: Requesting MD5 authentication "
			<< "for Passport " << m_msnId << endl;
		sendCommand( "USR", "MD5 I " + m_msnId);
	}
	else
	{
		kdDebug() << "MSNAuthSocket::parseCommand: Unimplemented command '"
			<< cmd << " " << id << " " << data << "' from server!" << endl;
	}
}

void MSNAuthSocket::doneConnect()
{
	kdDebug() << "MSNAuthSocket: Negotiating server protocol version"
		<< endl;
	sendCommand( "VER", "MSNP7 MSNP6 MSNP5 MSNP4 CVR0" );
}

#include "msnauthsocket.moc"

/*
 * Local variables:
 * c-indentation-style: k&r
 * c-basic-offset: 8
 * indent-tabs-mode: t
 * End:
 */
// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>// Copyright 2015 Markus Ilmola
// 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.

#include "generator/DodecahedronMesh.hpp"
#include "generator/Iterator.hpp"

#include <array>
#include <memory>

using namespace generator;

static const double a = (1.0 + std::sqrt(5.0)) / 2.0;

static const std::array<gml::dvec3, 20> vertices {{
	{ 1.0,  1.0, -1.0},
	{-1.0,  1.0, -1.0},
	{ 1.0, -1.0, -1.0},
	{-1.0, -1.0, -1.0},
	{ 1.0,  1.0,  1.0},
	{-1.0,  1.0,  1.0},
	{ 1.0, -1.0,  1.0},
	{-1.0, -1.0,  1.0},

	{0.0,  1.0/a, -a},
	{0.0, -1.0/a, -a},
	{0.0,  1.0/a,  a},
	{0.0, -1.0/a,  a},

	{ 1.0/a,  a, 0.0},
	{-1.0/a,  a, 0.0},
	{ 1.0/a, -a, 0.0},
	{-1.0/a, -a, 0.0},

	{ a, 0.0, -1.0/a},
	{-a, 0.0, -1.0/a},
	{ a, 0.0,  1.0/a},
	{-a, 0.0,  1.0/a}
}};

static const std::array<std::array<int, 5>, 12> polygons{{
	{{ 0u, 12u,  4u, 18u, 16u}}, // 0
	{{18u,  6u, 14u,  2u, 16u}}, // 1
	{{ 4u, 10u, 11u,  6u, 18u}}, // 2
	{{11u,  7u, 15u, 14u,  6u}}, // 3
	{{ 7u, 11u, 10u,  5u, 19u}}, // 4
	{{17u,  3u, 15u,  7u, 19u}}, // 5
	{{ 9u,  2u, 14u, 15u,  3u}}, // 6
	{{ 1u,  8u,  9u,  3u, 17u}}, // 7
	{{10u,  4u, 12u, 13u,  5u}}, // 8
	{{ 5u, 13u,  1u, 17u, 19u}}, // 9
	{{ 0u,  8u,  1u, 13u, 12u}}, // 10
	{{ 0u, 16u,  2u,  9u,  8u}}  // 11
}};

static std::vector<gml::dvec3> makeVertices(int faceIndex) noexcept {
	std::vector<gml::dvec3> result(5);
	for (int i = 0; i < 5; ++i) {
		result.at(i) = gml::normalize(vertices.at(polygons.at(faceIndex)[i]));
	}
	return result;
}

DodecahedronMesh::Triangles::Triangles(const DodecahedronMesh& mesh) noexcept :
	mMesh{&mesh},
	mFaceIndex{0},
	mFaceMesh{std::make_shared<ConvexPolygonMesh>(makeVertices(0), mMesh->mSegments, mMesh->mRings)},
	mTriangles{mFaceMesh->triangles()}
{ }

bool DodecahedronMesh::Triangles::done() const noexcept {
	return mFaceIndex == ::polygons.size();
}

Triangle DodecahedronMesh::Triangles::generate() const {
	if (done()) throw std::out_of_range("Done!");

	Triangle triangle = mTriangles.generate();

	const int base = mFaceIndex * mMesh->mFaceVertexCount;

	triangle.vertices[0] += base;
	triangle.vertices[1] += base;
	triangle.vertices[2] += base;

	return triangle;
}

void DodecahedronMesh::Triangles::next() {
	if (done()) throw std::out_of_range("Done!");

	mTriangles.next();

	if (mTriangles.done()) {
		++mFaceIndex;

		if (!done()) {
			mFaceMesh = std::make_shared<ConvexPolygonMesh>(
				makeVertices(mFaceIndex),
				mMesh->mSegments
			);

			mTriangles = mFaceMesh->triangles();
		}
	}
}

DodecahedronMesh::Vertices::Vertices(const DodecahedronMesh& mesh) noexcept :
	mMesh{&mesh},
	mFaceIndex{0},
	mFaceMesh{std::make_shared<ConvexPolygonMesh>(
		makeVertices(0),
		mMesh->mSegments,
		mMesh->mRings
	)},
	mVertices{mFaceMesh->vertices()}
{

}

bool DodecahedronMesh::Vertices::done() const noexcept {
	return mFaceIndex == ::polygons.size();
}

MeshVertex DodecahedronMesh::Vertices::generate() const {

	MeshVertex vertex = mVertices.generate();

	vertex.position *= mMesh->mRadius;

	return vertex;
}

void DodecahedronMesh::Vertices::next() {
	mVertices.next();

	if (mVertices.done()) {
		++mFaceIndex;

		if (!done()) {
			mFaceMesh = std::make_shared<ConvexPolygonMesh>(
				makeVertices(mFaceIndex),
				mMesh->mSegments,
				mMesh->mRings
			);

			mVertices = mFaceMesh->vertices();
		}
	}
}

DodecahedronMesh::DodecahedronMesh(double radius, int segments, int rings) noexcept :
	mRadius{radius},
	mSegments{segments},
	mRings{rings},
	mFaceVertexCount{count(ConvexPolygonMesh{1.0, 5u, segments, rings}.vertices())}
{

}

DodecahedronMesh::Triangles DodecahedronMesh::triangles() const noexcept {
	return Triangles{*this};
}

DodecahedronMesh::Vertices DodecahedronMesh::vertices() const noexcept {
	return Vertices{*this};
}

<commit_msg>Remove unneeded u suffix.<commit_after>// Copyright 2015 Markus Ilmola
// 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.

#include "generator/DodecahedronMesh.hpp"
#include "generator/Iterator.hpp"

#include <array>
#include <memory>

using namespace generator;

static const double a = (1.0 + std::sqrt(5.0)) / 2.0;

static const std::array<gml::dvec3, 20> vertices {{
	{ 1.0,  1.0, -1.0},
	{-1.0,  1.0, -1.0},
	{ 1.0, -1.0, -1.0},
	{-1.0, -1.0, -1.0},
	{ 1.0,  1.0,  1.0},
	{-1.0,  1.0,  1.0},
	{ 1.0, -1.0,  1.0},
	{-1.0, -1.0,  1.0},

	{0.0,  1.0/a, -a},
	{0.0, -1.0/a, -a},
	{0.0,  1.0/a,  a},
	{0.0, -1.0/a,  a},

	{ 1.0/a,  a, 0.0},
	{-1.0/a,  a, 0.0},
	{ 1.0/a, -a, 0.0},
	{-1.0/a, -a, 0.0},

	{ a, 0.0, -1.0/a},
	{-a, 0.0, -1.0/a},
	{ a, 0.0,  1.0/a},
	{-a, 0.0,  1.0/a}
}};

static const std::array<std::array<int, 5>, 12> polygons{{
	{{ 0, 12,  4, 18, 16}}, // 0
	{{18,  6, 14,  2, 16}}, // 1
	{{ 4, 10, 11,  6, 18}}, // 2
	{{11,  7, 15, 14,  6}}, // 3
	{{ 7, 11, 10,  5, 19}}, // 4
	{{17,  3, 15,  7, 19}}, // 5
	{{ 9,  2, 14, 15,  3}}, // 6
	{{ 1,  8,  9,  3, 17}}, // 7
	{{10,  4, 12, 13,  5}}, // 8
	{{ 5, 13,  1, 17, 19}}, // 9
	{{ 0,  8,  1, 13, 12}}, // 10
	{{ 0, 16,  2,  9,  8}}  // 11
}};

static std::vector<gml::dvec3> makeVertices(int faceIndex) noexcept {
	std::vector<gml::dvec3> result(5);
	for (int i = 0; i < 5; ++i) {
		result.at(i) = gml::normalize(vertices.at(polygons.at(faceIndex)[i]));
	}
	return result;
}

DodecahedronMesh::Triangles::Triangles(const DodecahedronMesh& mesh) noexcept :
	mMesh{&mesh},
	mFaceIndex{0},
	mFaceMesh{std::make_shared<ConvexPolygonMesh>(makeVertices(0), mMesh->mSegments, mMesh->mRings)},
	mTriangles{mFaceMesh->triangles()}
{ }

bool DodecahedronMesh::Triangles::done() const noexcept {
	return mFaceIndex == ::polygons.size();
}

Triangle DodecahedronMesh::Triangles::generate() const {
	if (done()) throw std::out_of_range("Done!");

	Triangle triangle = mTriangles.generate();

	const int base = mFaceIndex * mMesh->mFaceVertexCount;

	triangle.vertices[0] += base;
	triangle.vertices[1] += base;
	triangle.vertices[2] += base;

	return triangle;
}

void DodecahedronMesh::Triangles::next() {
	if (done()) throw std::out_of_range("Done!");

	mTriangles.next();

	if (mTriangles.done()) {
		++mFaceIndex;

		if (!done()) {
			mFaceMesh = std::make_shared<ConvexPolygonMesh>(
				makeVertices(mFaceIndex),
				mMesh->mSegments
			);

			mTriangles = mFaceMesh->triangles();
		}
	}
}

DodecahedronMesh::Vertices::Vertices(const DodecahedronMesh& mesh) noexcept :
	mMesh{&mesh},
	mFaceIndex{0},
	mFaceMesh{std::make_shared<ConvexPolygonMesh>(
		makeVertices(0),
		mMesh->mSegments,
		mMesh->mRings
	)},
	mVertices{mFaceMesh->vertices()}
{

}

bool DodecahedronMesh::Vertices::done() const noexcept {
	return mFaceIndex == ::polygons.size();
}

MeshVertex DodecahedronMesh::Vertices::generate() const {

	MeshVertex vertex = mVertices.generate();

	vertex.position *= mMesh->mRadius;

	return vertex;
}

void DodecahedronMesh::Vertices::next() {
	mVertices.next();

	if (mVertices.done()) {
		++mFaceIndex;

		if (!done()) {
			mFaceMesh = std::make_shared<ConvexPolygonMesh>(
				makeVertices(mFaceIndex),
				mMesh->mSegments,
				mMesh->mRings
			);

			mVertices = mFaceMesh->vertices();
		}
	}
}

DodecahedronMesh::DodecahedronMesh(double radius, int segments, int rings) noexcept :
	mRadius{radius},
	mSegments{segments},
	mRings{rings},
	mFaceVertexCount{count(ConvexPolygonMesh{1.0, 5u, segments, rings}.vertices())}
{

}

DodecahedronMesh::Triangles DodecahedronMesh::triangles() const noexcept {
	return Triangles{*this};
}

DodecahedronMesh::Vertices DodecahedronMesh::vertices() const noexcept {
	return Vertices{*this};
}

<|endoftext|>


<commit_before>/*
    yahoostatus.cpp - Yahoo Plugin for Kopete

    Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Copyright (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

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

#include <qstring.h>
#include <kdebug.h>
#include "yahoostatus.h"
#include "yahooprotocol.h"
#include "kopeteonlinestatus.h"

YahooStatus::YahooStatus( Status status_ )
{
	m_status = status_;
}

YahooStatus::YahooStatus()
{
	m_status = Offline;
}

KopeteOnlineStatus YahooStatus::translate() const
{
	if(m_status == Available)
		return KopeteOnlineStatus(KopeteOnlineStatus::Online,  25, YahooProtocol::protocol(), m_status, "yahoo_protocol",  i18n(YSTAvailable), i18n(YSTAvailable));
	else if(m_status == Mobile)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,     5, YahooProtocol::protocol(), m_status, "yahoo_mobile",  i18n("On the mobile"), i18n("On the mobile"));
	else if(m_status == Invisible)
		return KopeteOnlineStatus(KopeteOnlineStatus::Offline, 0, YahooProtocol::protocol(), m_status, QString::null, i18n(YSTInvisible), i18n(YSTInvisible));
	else if(m_status == Idle)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    15, YahooProtocol::protocol(), m_status, "yahoo_idle",    i18n("Idle"), i18n("Idle"));
	else if(m_status == Custom)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status, "yahoo_away",    m_statusText, m_statusText);
	else if(m_status == CustomBusy)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status, "yahoo_busy",    m_statusText, m_statusText);
	else if(m_status == CustomMobile)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status, "yahoo_mobile",  m_statusText, m_statusText);
	else if(m_status == BeRightBack)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, "yahoo_away",    i18n(YSTBeRightBack), i18n(YSTBeRightBack));
	else if(m_status == Busy)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, "yahoo_busy",    i18n(YSTBusy), i18n(YSTBusy));
	else if(m_status == NotAtHome)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, "yahoo_away",    i18n(YSTNotAtHome), i18n(YSTNotAtHome));
	else if(m_status == NotAtMyDesk)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, "yahoo_away",    i18n(YSTNotAtMyDesk), i18n(YSTNotAtMyDesk));
	else if(m_status == NotInTheOffice)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, "yahoo_away",    i18n(YSTNotInTheOffice), i18n(YSTNotInTheOffice));
	else if(m_status == OnThePhone)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, "yahoo_mobile",  i18n(YSTOnThePhone), i18n(YSTOnThePhone));
	else if(m_status == OnVacation)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, "yahoo_away",    i18n(YSTOnVacation), i18n(YSTOnVacation));
	else if(m_status == OutToLunch)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, "yahoo_tea",    i18n(YSTOutToLunch), i18n(YSTOutToLunch));
	else if(m_status == SteppedOut)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status, "yahoo_away",    i18n(YSTSteppedOut), i18n(YSTSteppedOut));
	else	// must be offline
		return KopeteOnlineStatus(KopeteOnlineStatus::Offline,  0, YahooProtocol::protocol(), m_status, QString::null, i18n(YSTOffline), i18n(YSTOffline));
}

void YahooStatus::setStatus( Status status_, const QString &statusText_ )
{
	m_status = status_;
	m_statusText = statusText_;
}

YahooStatus::Status YahooStatus::fromLibYahoo2( int status_ )
{
	switch (status_)
	{
		case YAHOO_STATUS_AVAILABLE :
			return Available;
		case YAHOO_STATUS_BRB :
			return BeRightBack;
		case YAHOO_STATUS_BUSY :
			return Busy;
		case YAHOO_STATUS_NOTATHOME :
			return NotAtHome;
		case YAHOO_STATUS_NOTATDESK :
			return NotAtMyDesk;
		case YAHOO_STATUS_NOTINOFFICE :
			return NotInTheOffice;
		case YAHOO_STATUS_ONPHONE :
			return OnThePhone;
		case YAHOO_STATUS_ONVACATION :
			return OnVacation;
		case YAHOO_STATUS_OUTTOLUNCH :
			return OutToLunch;
		case YAHOO_STATUS_STEPPEDOUT :
			return SteppedOut;
		case YAHOO_STATUS_INVISIBLE :
			return Invisible;
		case YAHOO_STATUS_CUSTOM :
			return Custom;
		case YAHOO_STATUS_IDLE :
			return Idle;
		case YAHOO_STATUS_OFFLINE :
			return Offline;
		case YAHOO_STATUS_TYPING :
			return Typing;
	}

	return Offline;
}
<commit_msg>Hackish, shortlived fix to stop the statuses conflicting with my internal KopeteOnlineStatus.<commit_after>/*
    yahoostatus.cpp - Yahoo Plugin for Kopete

    Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Copyright (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

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

#include <qstring.h>
#include <kdebug.h>
#include "yahoostatus.h"
#include "yahooprotocol.h"
#include "kopeteonlinestatus.h"

YahooStatus::YahooStatus( Status status_ )
{
	m_status = status_;
}

YahooStatus::YahooStatus()
{
	m_status = Offline;
}

KopeteOnlineStatus YahooStatus::translate() const
{
	if(m_status == Available)
		return KopeteOnlineStatus(KopeteOnlineStatus::Online,  25, YahooProtocol::protocol(), m_status + 1, "yahoo_protocol",  i18n(YSTAvailable), i18n(YSTAvailable));
	else if(m_status == Mobile)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,     5, YahooProtocol::protocol(), m_status + 1, "yahoo_mobile",  i18n("On the mobile"), i18n("On the mobile"));
	else if(m_status == Invisible)
		return KopeteOnlineStatus(KopeteOnlineStatus::Offline, 0, YahooProtocol::protocol(), m_status + 1, QString::null, i18n(YSTInvisible), i18n(YSTInvisible));
	else if(m_status == Idle)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    15, YahooProtocol::protocol(), m_status + 1, "yahoo_idle",    i18n("Idle"), i18n("Idle"));
	else if(m_status == Custom)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status + 1, "yahoo_away",    m_statusText, m_statusText);
	else if(m_status == CustomBusy)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status + 1, "yahoo_busy",    m_statusText, m_statusText);
	else if(m_status == CustomMobile)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    20, YahooProtocol::protocol(), m_status + 1, "yahoo_mobile",  m_statusText, m_statusText);
	else if(m_status == BeRightBack)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, "yahoo_away",    i18n(YSTBeRightBack), i18n(YSTBeRightBack));
	else if(m_status == Busy)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, "yahoo_busy",    i18n(YSTBusy), i18n(YSTBusy));
	else if(m_status == NotAtHome)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, "yahoo_away",    i18n(YSTNotAtHome), i18n(YSTNotAtHome));
	else if(m_status == NotAtMyDesk)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, "yahoo_away",    i18n(YSTNotAtMyDesk), i18n(YSTNotAtMyDesk));
	else if(m_status == NotInTheOffice)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, "yahoo_away",    i18n(YSTNotInTheOffice), i18n(YSTNotInTheOffice));
	else if(m_status == OnThePhone)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, "yahoo_mobile",  i18n(YSTOnThePhone), i18n(YSTOnThePhone));
	else if(m_status == OnVacation)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, "yahoo_away",    i18n(YSTOnVacation), i18n(YSTOnVacation));
	else if(m_status == OutToLunch)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, "yahoo_tea",    i18n(YSTOutToLunch), i18n(YSTOutToLunch));
	else if(m_status == SteppedOut)
		return KopeteOnlineStatus(KopeteOnlineStatus::Away,    10, YahooProtocol::protocol(), m_status + 1, "yahoo_away",    i18n(YSTSteppedOut), i18n(YSTSteppedOut));
	else	// must be offline
		return KopeteOnlineStatus(KopeteOnlineStatus::Offline,  0, YahooProtocol::protocol(), m_status + 1, QString::null, i18n(YSTOffline), i18n(YSTOffline));
}

void YahooStatus::setStatus( Status status_, const QString &statusText_ )
{
	m_status = status_;
	m_statusText = statusText_;
}

YahooStatus::Status YahooStatus::fromLibYahoo2( int status_ )
{
	switch (status_)
	{
		case YAHOO_STATUS_AVAILABLE :
			return Available;
		case YAHOO_STATUS_BRB :
			return BeRightBack;
		case YAHOO_STATUS_BUSY :
			return Busy;
		case YAHOO_STATUS_NOTATHOME :
			return NotAtHome;
		case YAHOO_STATUS_NOTATDESK :
			return NotAtMyDesk;
		case YAHOO_STATUS_NOTINOFFICE :
			return NotInTheOffice;
		case YAHOO_STATUS_ONPHONE :
			return OnThePhone;
		case YAHOO_STATUS_ONVACATION :
			return OnVacation;
		case YAHOO_STATUS_OUTTOLUNCH :
			return OutToLunch;
		case YAHOO_STATUS_STEPPEDOUT :
			return SteppedOut;
		case YAHOO_STATUS_INVISIBLE :
			return Invisible;
		case YAHOO_STATUS_CUSTOM :
			return Custom;
		case YAHOO_STATUS_IDLE :
			return Idle;
		case YAHOO_STATUS_OFFLINE :
			return Offline;
		case YAHOO_STATUS_TYPING :
			return Typing;
	}

	return Offline;
}
<|endoftext|>


<commit_before>#pragma once

namespace despairagus {
	namespace bitnode {
		template <typename A>
		class bitnode {
			template<typename B>
			using conref = const B &;

			using byte = unsigned char;
			using bit = bool;

		public:
			inline explicit bitnode(void) : zero{nullptr}, one{nullptr}, data{nullptr} {}

			template <typename... A>
			explicit bitnode(A... a) = delete;

		private:
			bitnode* zero;
			bitnode* one;

			A* data;
		};
	}
}<commit_msg>ensure that constructor throws no exceptions<commit_after>#pragma once

namespace despairagus {
	namespace bitnode {
		template <typename A>
		class bitnode {
			template<typename B>
			using conref = const B &;

			using byte = unsigned char;
			using bit = bool;

		public:
			inline explicit bitnode(void) noexcept : zero{nullptr}, one{nullptr}, data{nullptr} {}

			template <typename... A>
			explicit bitnode(A... a) = delete;

		private:
			bitnode* zero;
			bitnode* one;

			A* data;
		};
	}
}<|endoftext|>


<commit_before><commit_msg>Added order option<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/spellcheck_host.h"

#include "base/string_split.h"
#include "chrome/browser/prefs/pref_member.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/spellcheck_host_impl.h"
#include "chrome/browser/spellchecker_platform_engine.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/spellcheck_common.h"
#include "content/common/notification_service.h"
#include "googleurl/src/gurl.h"
#include "third_party/hunspell/google/bdict.h"
#include "ui/base/l10n/l10n_util.h"

namespace {

FilePath GetFirstChoiceFilePath(const std::string& language) {
  FilePath dict_dir;
  {
    // This should not do blocking IO from the UI thread!
    // Temporarily allow it for now.
    //   http://code.google.com/p/chromium/issues/detail?id=60643
    base::ThreadRestrictions::ScopedAllowIO allow_io;
    PathService::Get(chrome::DIR_APP_DICTIONARIES, &dict_dir);
  }
  return SpellCheckCommon::GetVersionedFileName(language, dict_dir);
}

#if defined(OS_MACOSX)
// Collect metrics on how often Hunspell is used on OS X vs the native
// spellchecker.
void RecordSpellCheckStats(bool native_spellchecker_used,
                           const std::string& language) {
  static std::set<std::string> languages_seen;

  // Only count a language code once for each session..
  if (languages_seen.find(language) != languages_seen.end()) {
    return;
  }
  languages_seen.insert(language);

  enum {
    SPELLCHECK_OSX_NATIVE_SPELLCHECKER_USED = 0,
    SPELLCHECK_HUNSPELL_USED = 1
  };

  bool engine_used = native_spellchecker_used ?
                         SPELLCHECK_OSX_NATIVE_SPELLCHECKER_USED :
                         SPELLCHECK_HUNSPELL_USED;

  UMA_HISTOGRAM_COUNTS("SpellCheck.OSXEngineUsed", engine_used);
}
#endif

#if defined(OS_WIN)
FilePath GetFallbackFilePath(const FilePath& first_choice) {
  FilePath dict_dir;
  PathService::Get(chrome::DIR_USER_DATA, &dict_dir);
  return dict_dir.Append(first_choice.BaseName());
}
#endif

}  // namespace

// Constructed on UI thread.
SpellCheckHost::SpellCheckHost(SpellCheckHostObserver* observer,
                               const std::string& language,
                               URLRequestContextGetter* request_context_getter)
    : observer_(observer),
      language_(language),
      file_(base::kInvalidPlatformFileValue),
      tried_to_download_(false),
      use_platform_spellchecker_(false),
      request_context_getter_(request_context_getter) {
  DCHECK(observer_);
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  FilePath personal_file_directory;
  PathService::Get(chrome::DIR_USER_DATA, &personal_file_directory);
  custom_dictionary_file_ =
      personal_file_directory.Append(chrome::kCustomDictionaryFileName);

  bdict_file_path_ = GetFirstChoiceFilePath(language);
}

SpellCheckHost::~SpellCheckHost() {
  if (file_ != base::kInvalidPlatformFileValue)
    base::ClosePlatformFile(file_);
}

void SpellCheckHost::Initialize() {
  if (SpellCheckerPlatform::SpellCheckerAvailable() &&
      SpellCheckerPlatform::PlatformSupportsLanguage(language_)) {
#if defined(OS_MACOSX)
    RecordSpellCheckStats(true, language_);
#endif
    use_platform_spellchecker_ = true;
    SpellCheckerPlatform::SetLanguage(language_);
    MessageLoop::current()->PostTask(FROM_HERE,
        NewRunnableMethod(this,
            &SpellCheckHost::InformObserverOfInitialization));
    return;
  }
>>>>>>> Update a bunch of files to the new location of notification files.

// static
scoped_refptr<SpellCheckHost> SpellCheckHost::Create(
    SpellCheckHostObserver* observer,
    const std::string& language,
    URLRequestContextGetter* request_context_getter) {
  scoped_refptr<SpellCheckHostImpl> host =
      new SpellCheckHostImpl(observer,
                             language,
                             request_context_getter);
  if (!host)
    return NULL;

  host->Initialize();
  return host;
}

// static
int SpellCheckHost::GetSpellCheckLanguages(
    Profile* profile,
    std::vector<std::string>* languages) {
  StringPrefMember accept_languages_pref;
  StringPrefMember dictionary_language_pref;
  accept_languages_pref.Init(prefs::kAcceptLanguages, profile->GetPrefs(),
                             NULL);
  dictionary_language_pref.Init(prefs::kSpellCheckDictionary,
                                profile->GetPrefs(), NULL);
  std::string dictionary_language = dictionary_language_pref.GetValue();

  // The current dictionary language should be there.
  languages->push_back(dictionary_language);

  // Now scan through the list of accept languages, and find possible mappings
  // from this list to the existing list of spell check languages.
  std::vector<std::string> accept_languages;

  if (SpellCheckerPlatform::SpellCheckerAvailable())
    SpellCheckerPlatform::GetAvailableLanguages(&accept_languages);
  else
    base::SplitString(accept_languages_pref.GetValue(), ',', &accept_languages);

  for (std::vector<std::string>::const_iterator i = accept_languages.begin();
       i != accept_languages.end(); ++i) {
    std::string language =
        SpellCheckCommon::GetCorrespondingSpellCheckLanguage(*i);
    if (!language.empty() &&
        std::find(languages->begin(), languages->end(), language) ==
        languages->end()) {
      languages->push_back(language);
    }
  }

  for (size_t i = 0; i < languages->size(); ++i) {
    if ((*languages)[i] == dictionary_language)
      return i;
  }
  return -1;
}

<commit_msg>Fix a bad rebase conflict. This should fix the bots.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/spellcheck_host.h"

#include "base/string_split.h"
#include "chrome/browser/prefs/pref_member.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/spellcheck_host_impl.h"
#include "chrome/browser/spellchecker_platform_engine.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/spellcheck_common.h"

// static
scoped_refptr<SpellCheckHost> SpellCheckHost::Create(
    SpellCheckHostObserver* observer,
    const std::string& language,
    URLRequestContextGetter* request_context_getter) {
  scoped_refptr<SpellCheckHostImpl> host =
      new SpellCheckHostImpl(observer,
                             language,
                             request_context_getter);
  if (!host)
    return NULL;

  host->Initialize();
  return host;
}

// static
int SpellCheckHost::GetSpellCheckLanguages(
    Profile* profile,
    std::vector<std::string>* languages) {
  StringPrefMember accept_languages_pref;
  StringPrefMember dictionary_language_pref;
  accept_languages_pref.Init(prefs::kAcceptLanguages, profile->GetPrefs(),
                             NULL);
  dictionary_language_pref.Init(prefs::kSpellCheckDictionary,
                                profile->GetPrefs(), NULL);
  std::string dictionary_language = dictionary_language_pref.GetValue();

  // The current dictionary language should be there.
  languages->push_back(dictionary_language);

  // Now scan through the list of accept languages, and find possible mappings
  // from this list to the existing list of spell check languages.
  std::vector<std::string> accept_languages;

  if (SpellCheckerPlatform::SpellCheckerAvailable())
    SpellCheckerPlatform::GetAvailableLanguages(&accept_languages);
  else
    base::SplitString(accept_languages_pref.GetValue(), ',', &accept_languages);

  for (std::vector<std::string>::const_iterator i = accept_languages.begin();
       i != accept_languages.end(); ++i) {
    std::string language =
        SpellCheckCommon::GetCorrespondingSpellCheckLanguage(*i);
    if (!language.empty() &&
        std::find(languages->begin(), languages->end(), language) ==
        languages->end()) {
      languages->push_back(language);
    }
  }

  for (size_t i = 0; i < languages->size(); ++i) {
    if ((*languages)[i] == dictionary_language)
      return i;
  }
  return -1;
}
<|endoftext|>


<commit_before>#include "Resources.hpp"

#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Geometry/Model.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <Engine/Util/FileSystem.hpp>

using namespace std;

string ResourceList::Resource::GetName() const {
    switch (type) {
    case Type::SCENE:
        return scene;
    case Type::MODEL:
        return model->name;
    case Type::TEXTURE:
        return texture->name;
    case Type::SOUND:
        return sound->name;
    case Type::SCRIPT:
        return script->name;
    default:
        return "";
    }
}

ResourceList::ResourceList() {
    activeScene = "";
    resourceFolder.name = "Resources";
}

ResourceList& ResourceList::GetInstance() {
    static ResourceList resourceList;

    return resourceList;
}

void ResourceList::Save() const {
    // Save to file.
    ofstream file(GetSavePath());
    file << ToJson();
    file.close();
}

Json::Value ResourceList::ToJson() const {
    Json::Value root;

    root["activeScene"] = activeScene;
    root["resourceFolder"] = SaveFolder(resourceFolder);

    root["sceneNumber"] = sceneNumber;
    root["textureNumber"] = textureNumber;
    root["modelNumber"] = modelNumber;
    root["soundNumber"] = soundNumber;
    root["scriptNumber"] = scriptNumber;

    return root;
}

void ResourceList::Load() {
    // Load Json document from file.
    Json::Value root;
    ifstream file(GetSavePath());
    file >> root;
    file.close();

    activeScene = root["activeScene"].asString();
    resourceFolder = LoadFolder(root["resourceFolder"], "");

    sceneNumber = root["sceneNumber"].asUInt();
    textureNumber = root["textureNumber"].asUInt();
    modelNumber = root["modelNumber"].asUInt();
    soundNumber = root["soundNumber"].asUInt();
    scriptNumber = root["scriptNumber"].asUInt();
}

void ResourceList::Clear() {
    ClearFolder(resourceFolder);
    resourceFolder.name = "Resources";

    sceneNumber = 0U;
    modelNumber = 0U;
    textureNumber = 0U;
    soundNumber = 0U;
    scriptNumber = 0U;
}

Json::Value ResourceList::SaveFolder(const ResourceFolder& folder) const {
    Json::Value node;
    node["name"] = folder.name;

    // Save subfolders.
    Json::Value subfolders;
    for (const ResourceFolder& subfolder : folder.subfolders)
        subfolders.append(SaveFolder(subfolder));

    node["subfolders"] = subfolders;

    // Save resources.
    Json::Value resourcesNode;
    for (const Resource& resource : folder.resources) {
        Json::Value resourceNode;
        resourceNode["type"] = resource.type;

        switch (resource.type) {
        case Resource::SCENE:
            resourceNode["scene"] = resource.scene;
            break;
        case Resource::TEXTURE:
            resourceNode["texture"] = resource.texture->name;
            resource.texture->Save();
            break;
        case Resource::MODEL:
            resourceNode["model"] = resource.model->name;
            resource.model->Save();
            break;
        case Resource::SOUND:
            resourceNode["sound"] = resource.sound->name;
            resource.sound->Save();
            break;
        case Resource::SCRIPT:
            resourceNode["script"] = resource.script->name;
            resource.script->Save();
            break;
        }

        resourcesNode.append(resourceNode);
    }
    node["resources"] = resourcesNode;

    return node;
}

ResourceList::ResourceFolder ResourceList::LoadFolder(const Json::Value& node, std::string path) {
    ResourceFolder folder;
    folder.name = node["name"].asString();
    path += folder.name + "/";

    // Load subfolders.
    Json::Value subfoldersNode = node["subfolders"];
    for (unsigned int i = 0; i < subfoldersNode.size(); ++i)
        folder.subfolders.push_back(LoadFolder(subfoldersNode[i], path));

    // Load resources.
    Json::Value resourcesNode = node["resources"];
    for (unsigned int i = 0; i < resourcesNode.size(); ++i) {
        Json::Value resourceNode = resourcesNode[i];
        Resource resource;
        resource.type = static_cast<Resource::Type>(resourceNode["type"].asInt());

        switch (resource.type) {
        case Resource::SCENE:
            resource.scene = resourceNode["scene"].asString();
            break;
        case Resource::TEXTURE:
            resource.texture = Managers().resourceManager->CreateTextureAsset(path + resourceNode["texture"].asString());
            break;
        case Resource::MODEL:
            resource.model = Managers().resourceManager->CreateModel(path + resourceNode["model"].asString());
            break;
        case Resource::SOUND:
            resource.sound = Managers().resourceManager->CreateSound(path + resourceNode["sound"].asString());
            break;
        case Resource::SCRIPT:
            resource.script = Managers().resourceManager->CreateScriptFile(path + resourceNode["script"].asString());
            break;
        }

        folder.resources.push_back(resource);
    }

    return folder;
}

void ResourceList::ClearFolder(ResourceFolder& folder) {
    // Clear subfolders.
    for (ResourceFolder& subfolder : folder.subfolders)
        ClearFolder(subfolder);

    folder.subfolders.clear();

    // Clear resources.
    for (const Resource& resource : folder.resources) {
        switch (resource.type) {
        case Resource::Type::MODEL:
            Managers().resourceManager->FreeModel(resource.model);
            break;
        case Resource::Type::TEXTURE:
            Managers().resourceManager->FreeTextureAsset(resource.texture);
            break;
        case Resource::Type::SOUND:
            Managers().resourceManager->FreeSound(resource.sound);
            break;
        default:
            break;
        }
    }
    folder.resources.clear();
}

std::string ResourceList::GetSavePath() const{
    return Hymn().GetPath() + FileSystem::DELIMITER + "Resources.json";
}

ResourceList& Resources() {
    return ResourceList::GetInstance();
}
<commit_msg>Remove unnecessary statement<commit_after>#include "Resources.hpp"

#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Geometry/Model.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <Engine/Util/FileSystem.hpp>

using namespace std;

string ResourceList::Resource::GetName() const {
    switch (type) {
    case Type::SCENE:
        return scene;
    case Type::MODEL:
        return model->name;
    case Type::TEXTURE:
        return texture->name;
    case Type::SOUND:
        return sound->name;
    case Type::SCRIPT:
        return script->name;
    default:
        return "";
    }
}

ResourceList::ResourceList() {
    resourceFolder.name = "Resources";
}

ResourceList& ResourceList::GetInstance() {
    static ResourceList resourceList;

    return resourceList;
}

void ResourceList::Save() const {
    // Save to file.
    ofstream file(GetSavePath());
    file << ToJson();
    file.close();
}

Json::Value ResourceList::ToJson() const {
    Json::Value root;

    root["activeScene"] = activeScene;
    root["resourceFolder"] = SaveFolder(resourceFolder);

    root["sceneNumber"] = sceneNumber;
    root["textureNumber"] = textureNumber;
    root["modelNumber"] = modelNumber;
    root["soundNumber"] = soundNumber;
    root["scriptNumber"] = scriptNumber;

    return root;
}

void ResourceList::Load() {
    // Load Json document from file.
    Json::Value root;
    ifstream file(GetSavePath());
    file >> root;
    file.close();

    activeScene = root["activeScene"].asString();
    resourceFolder = LoadFolder(root["resourceFolder"], "");

    sceneNumber = root["sceneNumber"].asUInt();
    textureNumber = root["textureNumber"].asUInt();
    modelNumber = root["modelNumber"].asUInt();
    soundNumber = root["soundNumber"].asUInt();
    scriptNumber = root["scriptNumber"].asUInt();
}

void ResourceList::Clear() {
    ClearFolder(resourceFolder);
    resourceFolder.name = "Resources";

    sceneNumber = 0U;
    modelNumber = 0U;
    textureNumber = 0U;
    soundNumber = 0U;
    scriptNumber = 0U;
}

Json::Value ResourceList::SaveFolder(const ResourceFolder& folder) const {
    Json::Value node;
    node["name"] = folder.name;

    // Save subfolders.
    Json::Value subfolders;
    for (const ResourceFolder& subfolder : folder.subfolders)
        subfolders.append(SaveFolder(subfolder));

    node["subfolders"] = subfolders;

    // Save resources.
    Json::Value resourcesNode;
    for (const Resource& resource : folder.resources) {
        Json::Value resourceNode;
        resourceNode["type"] = resource.type;

        switch (resource.type) {
        case Resource::SCENE:
            resourceNode["scene"] = resource.scene;
            break;
        case Resource::TEXTURE:
            resourceNode["texture"] = resource.texture->name;
            resource.texture->Save();
            break;
        case Resource::MODEL:
            resourceNode["model"] = resource.model->name;
            resource.model->Save();
            break;
        case Resource::SOUND:
            resourceNode["sound"] = resource.sound->name;
            resource.sound->Save();
            break;
        case Resource::SCRIPT:
            resourceNode["script"] = resource.script->name;
            resource.script->Save();
            break;
        }

        resourcesNode.append(resourceNode);
    }
    node["resources"] = resourcesNode;

    return node;
}

ResourceList::ResourceFolder ResourceList::LoadFolder(const Json::Value& node, std::string path) {
    ResourceFolder folder;
    folder.name = node["name"].asString();
    path += folder.name + "/";

    // Load subfolders.
    Json::Value subfoldersNode = node["subfolders"];
    for (unsigned int i = 0; i < subfoldersNode.size(); ++i)
        folder.subfolders.push_back(LoadFolder(subfoldersNode[i], path));

    // Load resources.
    Json::Value resourcesNode = node["resources"];
    for (unsigned int i = 0; i < resourcesNode.size(); ++i) {
        Json::Value resourceNode = resourcesNode[i];
        Resource resource;
        resource.type = static_cast<Resource::Type>(resourceNode["type"].asInt());

        switch (resource.type) {
        case Resource::SCENE:
            resource.scene = resourceNode["scene"].asString();
            break;
        case Resource::TEXTURE:
            resource.texture = Managers().resourceManager->CreateTextureAsset(path + resourceNode["texture"].asString());
            break;
        case Resource::MODEL:
            resource.model = Managers().resourceManager->CreateModel(path + resourceNode["model"].asString());
            break;
        case Resource::SOUND:
            resource.sound = Managers().resourceManager->CreateSound(path + resourceNode["sound"].asString());
            break;
        case Resource::SCRIPT:
            resource.script = Managers().resourceManager->CreateScriptFile(path + resourceNode["script"].asString());
            break;
        }

        folder.resources.push_back(resource);
    }

    return folder;
}

void ResourceList::ClearFolder(ResourceFolder& folder) {
    // Clear subfolders.
    for (ResourceFolder& subfolder : folder.subfolders)
        ClearFolder(subfolder);

    folder.subfolders.clear();

    // Clear resources.
    for (const Resource& resource : folder.resources) {
        switch (resource.type) {
        case Resource::Type::MODEL:
            Managers().resourceManager->FreeModel(resource.model);
            break;
        case Resource::Type::TEXTURE:
            Managers().resourceManager->FreeTextureAsset(resource.texture);
            break;
        case Resource::Type::SOUND:
            Managers().resourceManager->FreeSound(resource.sound);
            break;
        default:
            break;
        }
    }
    folder.resources.clear();
}

std::string ResourceList::GetSavePath() const{
    return Hymn().GetPath() + FileSystem::DELIMITER + "Resources.json";
}

ResourceList& Resources() {
    return ResourceList::GetInstance();
}
<|endoftext|>


<commit_before><commit_msg>In system level install case go back to copying files instead of moving them.<commit_after><|endoftext|>