<commit_before>#include "tilesetController.hpp"

#include "tilesetManager.hpp"

#include <SFML/Graphics/Image.hpp>
#include <SFML/Graphics/Sprite.hpp>

#include <SFGUI/Adjustment.hpp>
#include <SFGUI/Box.hpp>
#include <SFGUI/Button.hpp>
#include <SFGUI/Desktop.hpp>
#include <SFGUI/Frame.hpp>
#include <SFGUI/Image.hpp>
#include <SFGUI/Label.hpp>
#include <SFGUI/Scale.hpp>

TilesetController::TilesetController(TilesetManager &tilesetManager, sfg::Desktop &desktop) :
  mTilesetManager(tilesetManager),
  mDesktop(desktop)
{
  initGui();
}

void TilesetController::update()
{
  //Offset
  static auto lastOffset = mCurrentOffset;
  if (lastOffset != mCurrentOffset)
  {
    lastOffset = mCurrentOffset;
    redrawCanvas();
  }
  //Zoom
  static auto lastZoom = mCurrentZoom;
  mCurrentZoom = mGui.zoomScale->GetValue();
  if (lastZoom != mCurrentZoom)
  {
    auto cursorPos = mGui.zoomEntry->GetCursorPosition();
    mGui.zoomEntry->SetText(std::to_string(static_cast<int>(mCurrentZoom * 100)) + "%");
    mGui.zoomEntry->SetCursorPosition(cursorPos);
    redrawCanvas();
    lastZoom = mCurrentZoom;
  }
  //Size
  static auto lastSize = mGui.notebook->GetAllocation();
  auto currentSize = mGui.notebook->GetAllocation();
  if (lastSize.width != currentSize.width || lastSize.height != currentSize.height)
  {
    lastSize = currentSize;
    redrawCanvas();
  }
}

void TilesetController::redrawCanvas()
{
  if (mGui.tilesetPages.size() != 0)
  {
    std::cout << "Redraw, canvas: " << mGui.activePage->texName << std::endl;
    const sf::Texture &tex = mTilesetManager.getTileset(mGui.activePage->canvas->GetId());
    if (mRenderTex.getSize() != sf::Vector2u(mGui.activePage->canvas->GetAllocation().width, mGui.activePage->canvas->GetAllocation().height))
    {
      std::cout << "Recreated texture" << std::endl;
      mRenderTex.create(static_cast<unsigned>(mGui.activePage->canvas->GetAllocation().width),
        static_cast<unsigned>(mGui.activePage->canvas->GetAllocation().height));
    }

    sf::Sprite sprite(tex);
    sprite.scale({ mCurrentZoom, mCurrentZoom });
    auto view = mRenderTex.getDefaultView();
    view.setCenter({ mCurrentOffset.x + sprite.getGlobalBounds().width / 2.f, mCurrentOffset.y + sprite.getGlobalBounds().height / 2.f });
    mRenderTex.setView(view);
    mRenderTex.clear();
    mRenderTex.draw(sprite);
    mRenderTex.display();
    sf::Sprite sprite2(mRenderTex.getTexture());
    std::cout << "Draw" << std::endl;
    mGui.activePage->canvas->Clear();
    mGui.activePage->canvas->Draw(sprite2);
    mGui.activePage->canvas->Display();
    std::cout << "Offset: " << mCurrentOffset.x << " | " << mCurrentOffset.y << std::endl;
    auto difference_x = sprite.getGlobalBounds().width - mRenderTex.getSize().x;
    if (difference_x > 0)
    {
      mGui.activePage->hScrollbar->Show(true);
      auto adj = mGui.activePage->hScrollbar->GetAdjustment();
      adj->Configure(mCurrentOffset.x, -difference_x / 2.f, difference_x / 2.f, difference_x / 100.f, difference_x / 5.f, 1);
    }
    else
    {
      mGui.activePage->hScrollbar->Show(false);
      mGui.activePage->hScrollbar->SetValue(0);
    }
    auto difference_y = sprite.getGlobalBounds().height - mRenderTex.getSize().y;
    if (difference_y > 0)
    {
      mGui.activePage->vScrollbar->Show(true);
      auto adj = mGui.activePage->vScrollbar->GetAdjustment();
      adj->Configure(mCurrentOffset.y, -difference_y / 2.f, difference_y / 2.f, difference_y / 100.f, difference_y / 5.f, 1.f);
    }
    else
    {
      mGui.activePage->vScrollbar->Show(false);
      mGui.activePage->vScrollbar->SetValue(0);
    }
  }
}

void TilesetController::openLoadTilesetDialog()
{
  mGui.loadTilesetName->SetText("tileset.png");

  mGui.loadTilesetDialog->Show(true);
  mGui.loadTilesetDialog->GrabFocus();
}

void TilesetController::loadNewTileset()
{
  auto name = mGui.loadTilesetName->GetText();
  if (mTilesetManager.loadTileset(name))
  {
    addTilesetToView(name);
    mGui.loadTilesetDialog->Show(false);
    mGui.notebook->SetCurrentPage(mGui.notebook->GetPageCount() - 1);
    updateActiveCanvas();
  }
  else
  {
    mGui.loadTilesetName->SetText("Could not load the file");
  }
}

void TilesetController::updateActiveCanvas()
{
  auto activePage = mGui.notebook->GetCurrentPage();
  if (mGui.tilesetPages.size() != 0)
  {
    auto ptr = &mGui.tilesetPages[activePage];
    if (ptr != mGui.activePage)
    {
      mGui.activePage = ptr;
      redrawCanvas();
    }
  }
}

void TilesetController::updateZoom()
{
  std::string text = mGui.zoomEntry->GetText();
  if (text.size() > 0)
  {
    if (text.back() == '%')
      text.pop_back();
    mCurrentZoom = static_cast<float>(std::atof(text.c_str()));
    if (mCurrentZoom <= 0)
      mCurrentZoom = 1;
    else
      mCurrentZoom /= 100;

    mGui.zoomScale->SetValue(mCurrentZoom);
  }
}

void TilesetController::updateOffset()
{
  mCurrentOffset.x = mGui.activePage->hScrollbar->GetValue();
  mCurrentOffset.y = mGui.activePage->vScrollbar->GetValue();
}

void TilesetController::addTilesetToView(const std::string &name)
{
  auto label = sfg::Label::Create(name);
  auto box = sfg::Box::Create(sfg::Box::Orientation::VERTICAL);
  auto subBox = sfg::Box::Create();
  auto canvas = sfg::Canvas::Create();
  canvas->SetId(name);
  canvas->SetRequisition({ 200, 200 });
  subBox->Pack(canvas);
  auto vScrollbar = sfg::Scrollbar::Create(sfg::Scrollbar::Orientation::VERTICAL);
  vScrollbar->SetRequisition({ 18, 0 });
  vScrollbar->SetRange(0, 100);
  vScrollbar->SetIncrements(1, 5);
  vScrollbar->GetAdjustment()->GetSignal(sfg::Adjustment::OnChange).Connect(std::bind(&TilesetController::updateOffset, this));
  subBox->Pack(vScrollbar, false);
  auto hScrollbar = sfg::Scrollbar::Create();
  hScrollbar->SetRequisition({ 0, 18 });
  hScrollbar->SetIncrements(1, 5);
  hScrollbar->SetRange(0, 100);
  hScrollbar->GetAdjustment()->GetSignal(sfg::Adjustment::OnChange).Connect(std::bind(&TilesetController::updateOffset, this));
  box->Pack(subBox);
  box->Pack(hScrollbar, false);
  mGui.notebook->AppendPage(box, label);
  mGui.tilesetPages.push_back({ canvas, hScrollbar, vScrollbar, name });

  //Check if the preview page is still there, delete if so
  if (mGui.notebook->GetNthPage(0)->GetId() == "preview")
  {
    mGui.notebook->RemovePage(0);
  }
}

void TilesetController::initGui()
{
  initTilesetWindow();
  initLoadTilesetDialog();
}

void TilesetController::initTilesetWindow()
{
  auto box = sfg::Box::Create(sfg::Box::Orientation::VERTICAL);

  //TILESET view
  mGui.notebook = sfg::Notebook::Create();
  mGui.notebook->GetSignal(sfg::Notebook::OnLeftClick).Connect(std::bind(&TilesetController::updateActiveCanvas, this));
 // mGui.notebook->GetSignal(sfg::Notebook::OnSizeAllocate).Connect(std::bind(&TilesetController::redrawCanvas, this));

  auto label = sfg::Label::Create("No tileset loaded");
  auto canvas = sfg::Canvas::Create();
  canvas->SetRequisition({ 50.f, 50.f });
  canvas->SetId("preview");
  mGui.notebook->AppendPage(canvas, label);

  box->Pack(mGui.notebook);

  //CONTROLS
  auto subBox = sfg::Box::Create();
  box->Pack(subBox, false);

  auto bt = sfg::Button::Create("Add");
  bt->GetSignal(sfg::Button::OnLeftClick).Connect(std::bind(&TilesetController::openLoadTilesetDialog, this));
  subBox->Pack(bt, false);
  bt = sfg::Button::Create("Remove");
  subBox->Pack(bt, false);
  mGui.zoomEntry = sfg::Entry::Create("100%");
  mGui.zoomEntry->SetRequisition({ 50.f, 0.f });
  mGui.zoomEntry->GetSignal(sfg::Entry::OnTextChanged).Connect(std::bind(&TilesetController::updateZoom, this));
  subBox->Pack(mGui.zoomEntry, false);
  mGui.zoomScale = sfg::Scale::Create(0, 5, 0.1f);
  mGui.zoomScale->SetValue(1.f);
  mGui.zoomScale->SetRequisition({ 0, 10 });
  subBox->Pack(mGui.zoomScale);

  auto window = sfg::Window::Create(sfg::Window::Style::TOPLEVEL | sfg::Window::Style::SHADOW);
  window->SetTitle("Tilemaps");
  window->Add(box);
  mDesktop.Add(window);
}

void TilesetController::initLoadTilesetDialog()
{
  mGui.loadTilesetDialog = sfg::Window::Create(sfg::Window::Style::BACKGROUND |
    sfg::Window::Style::TITLEBAR);
  mGui.loadTilesetDialog->SetTitle("Load new Tileset");

  auto box = sfg::Box::Create(sfg::Box::Orientation::VERTICAL, 5.f);

  auto frame = sfg::Frame::Create("Enter tileset name with extension");
  mGui.loadTilesetName = sfg::Entry::Create("tileset.png");
  frame->Add(mGui.loadTilesetName);
  box->Pack(frame);

  auto subBox = sfg::Box::Create(sfg::Box::Orientation::HORIZONTAL, 5.f);
  auto bt = sfg::Button::Create("Load");
  bt->GetSignal(sfg::Button::OnLeftClick).Connect(std::bind(&TilesetController::loadNewTileset, this));
  subBox->Pack(bt);
  bt = sfg::Button::Create("Cancel");
  bt->GetSignal(sfg::Button::OnLeftClick).Connect([this](){mGui.loadTilesetDialog->Show(false); });
  subBox->Pack(bt);

  box->Pack(subBox);

  mGui.loadTilesetDialog->Add(box);
  mGui.loadTilesetDialog->Show(false);
  //mLoadTilesetDialog.window->SetZOrder(5);
  mDesktop.Add(mGui.loadTilesetDialog);
}<commit_msg>Fixed compiler warnings<commit_after>#include "tilesetController.hpp"

#include "tilesetManager.hpp"

#include <SFML/Graphics/Image.hpp>
#include <SFML/Graphics/Sprite.hpp>

#include <SFGUI/Adjustment.hpp>
#include <SFGUI/Box.hpp>
#include <SFGUI/Button.hpp>
#include <SFGUI/Desktop.hpp>
#include <SFGUI/Frame.hpp>
#include <SFGUI/Image.hpp>
#include <SFGUI/Label.hpp>
#include <SFGUI/Scale.hpp>

TilesetController::TilesetController(TilesetManager &tilesetManager, sfg::Desktop &desktop) :
  mTilesetManager(tilesetManager),
  mDesktop(desktop)
{
  initGui();
}

void TilesetController::update()
{
  //Offset
  static auto lastOffset = mCurrentOffset;
  if (lastOffset != mCurrentOffset)
  {
    lastOffset = mCurrentOffset;
    redrawCanvas();
  }
  //Zoom
  static auto lastZoom = mCurrentZoom;
  mCurrentZoom = mGui.zoomScale->GetValue();
  if (lastZoom != mCurrentZoom)
  {
    auto cursorPos = mGui.zoomEntry->GetCursorPosition();
    mGui.zoomEntry->SetText(std::to_string(static_cast<int>(mCurrentZoom * 100)) + "%");
    mGui.zoomEntry->SetCursorPosition(cursorPos);
    redrawCanvas();
    lastZoom = mCurrentZoom;
  }
  //Size
  static auto lastSize = mGui.notebook->GetAllocation();
  auto currentSize = mGui.notebook->GetAllocation();
  if (lastSize.width != currentSize.width || lastSize.height != currentSize.height)
  {
    lastSize = currentSize;
    redrawCanvas();
  }
}

void TilesetController::redrawCanvas()
{
  if (mGui.tilesetPages.size() != 0)
  {
    std::cout << "Redraw, canvas: " << mGui.activePage->texName << std::endl;
    const sf::Texture &tex = mTilesetManager.getTileset(mGui.activePage->canvas->GetId());
    if (mRenderTex.getSize() != sf::Vector2u(static_cast<unsigned>(mGui.activePage->canvas->GetAllocation().width),
      static_cast<unsigned>(mGui.activePage->canvas->GetAllocation().height)))
    {
      std::cout << "Recreated texture" << std::endl;
      mRenderTex.create(static_cast<unsigned>(mGui.activePage->canvas->GetAllocation().width),
        static_cast<unsigned>(mGui.activePage->canvas->GetAllocation().height));
    }

    sf::Sprite sprite(tex);
    sprite.scale({ mCurrentZoom, mCurrentZoom });
    auto view = mRenderTex.getDefaultView();
    view.setCenter({ mCurrentOffset.x + sprite.getGlobalBounds().width / 2.f, mCurrentOffset.y + sprite.getGlobalBounds().height / 2.f });
    mRenderTex.setView(view);
    mRenderTex.clear();
    mRenderTex.draw(sprite);
    mRenderTex.display();
    sf::Sprite sprite2(mRenderTex.getTexture());
    std::cout << "Draw" << std::endl;
    mGui.activePage->canvas->Clear();
    mGui.activePage->canvas->Draw(sprite2);
    mGui.activePage->canvas->Display();
    std::cout << "Offset: " << mCurrentOffset.x << " | " << mCurrentOffset.y << std::endl;
    auto difference_x = sprite.getGlobalBounds().width - mRenderTex.getSize().x;
    if (difference_x > 0)
    {
      mGui.activePage->hScrollbar->Show(true);
      auto adj = mGui.activePage->hScrollbar->GetAdjustment();
      adj->Configure(mCurrentOffset.x, -difference_x / 2.f, difference_x / 2.f, difference_x / 100.f, difference_x / 5.f, 1);
    }
    else
    {
      mGui.activePage->hScrollbar->Show(false);
      mGui.activePage->hScrollbar->SetValue(0);
    }
    auto difference_y = sprite.getGlobalBounds().height - mRenderTex.getSize().y;
    if (difference_y > 0)
    {
      mGui.activePage->vScrollbar->Show(true);
      auto adj = mGui.activePage->vScrollbar->GetAdjustment();
      adj->Configure(mCurrentOffset.y, -difference_y / 2.f, difference_y / 2.f, difference_y / 100.f, difference_y / 5.f, 1.f);
    }
    else
    {
      mGui.activePage->vScrollbar->Show(false);
      mGui.activePage->vScrollbar->SetValue(0);
    }
  }
}

void TilesetController::openLoadTilesetDialog()
{
  mGui.loadTilesetName->SetText("tileset.png");

  mGui.loadTilesetDialog->Show(true);
  mGui.loadTilesetDialog->GrabFocus();
}

void TilesetController::loadNewTileset()
{
  auto name = mGui.loadTilesetName->GetText();
  if (mTilesetManager.loadTileset(name))
  {
    addTilesetToView(name);
    mGui.loadTilesetDialog->Show(false);
    mGui.notebook->SetCurrentPage(mGui.notebook->GetPageCount() - 1);
    updateActiveCanvas();
  }
  else
  {
    mGui.loadTilesetName->SetText("Could not load the file");
  }
}

void TilesetController::updateActiveCanvas()
{
  auto activePage = mGui.notebook->GetCurrentPage();
  if (mGui.tilesetPages.size() != 0)
  {
    auto ptr = &mGui.tilesetPages[activePage];
    if (ptr != mGui.activePage)
    {
      mGui.activePage = ptr;
      redrawCanvas();
    }
  }
}

void TilesetController::updateZoom()
{
  std::string text = mGui.zoomEntry->GetText();
  if (text.size() > 0)
  {
    if (text.back() == '%')
      text.pop_back();
    mCurrentZoom = static_cast<float>(std::atof(text.c_str()));
    if (mCurrentZoom <= 0)
      mCurrentZoom = 1;
    else
      mCurrentZoom /= 100;

    mGui.zoomScale->SetValue(mCurrentZoom);
  }
}

void TilesetController::updateOffset()
{
  mCurrentOffset.x = mGui.activePage->hScrollbar->GetValue();
  mCurrentOffset.y = mGui.activePage->vScrollbar->GetValue();
}

void TilesetController::addTilesetToView(const std::string &name)
{
  auto label = sfg::Label::Create(name);
  auto box = sfg::Box::Create(sfg::Box::Orientation::VERTICAL);
  auto subBox = sfg::Box::Create();
  auto canvas = sfg::Canvas::Create();
  canvas->SetId(name);
  canvas->SetRequisition({ 200, 200 });
  subBox->Pack(canvas);
  auto vScrollbar = sfg::Scrollbar::Create(sfg::Scrollbar::Orientation::VERTICAL);
  vScrollbar->SetRequisition({ 18, 0 });
  vScrollbar->SetRange(0, 100);
  vScrollbar->SetIncrements(1, 5);
  vScrollbar->GetAdjustment()->GetSignal(sfg::Adjustment::OnChange).Connect(std::bind(&TilesetController::updateOffset, this));
  subBox->Pack(vScrollbar, false);
  auto hScrollbar = sfg::Scrollbar::Create();
  hScrollbar->SetRequisition({ 0, 18 });
  hScrollbar->SetIncrements(1, 5);
  hScrollbar->SetRange(0, 100);
  hScrollbar->GetAdjustment()->GetSignal(sfg::Adjustment::OnChange).Connect(std::bind(&TilesetController::updateOffset, this));
  box->Pack(subBox);
  box->Pack(hScrollbar, false);
  mGui.notebook->AppendPage(box, label);
  mGui.tilesetPages.push_back({ canvas, hScrollbar, vScrollbar, name });

  //Check if the preview page is still there, delete if so
  if (mGui.notebook->GetNthPage(0)->GetId() == "preview")
  {
    mGui.notebook->RemovePage(0);
  }
}

void TilesetController::initGui()
{
  initTilesetWindow();
  initLoadTilesetDialog();
}

void TilesetController::initTilesetWindow()
{
  auto box = sfg::Box::Create(sfg::Box::Orientation::VERTICAL);

  //TILESET view
  mGui.notebook = sfg::Notebook::Create();
  mGui.notebook->GetSignal(sfg::Notebook::OnLeftClick).Connect(std::bind(&TilesetController::updateActiveCanvas, this));
 // mGui.notebook->GetSignal(sfg::Notebook::OnSizeAllocate).Connect(std::bind(&TilesetController::redrawCanvas, this));

  auto label = sfg::Label::Create("No tileset loaded");
  auto canvas = sfg::Canvas::Create();
  canvas->SetRequisition({ 50.f, 50.f });
  canvas->SetId("preview");
  mGui.notebook->AppendPage(canvas, label);

  box->Pack(mGui.notebook);

  //CONTROLS
  auto subBox = sfg::Box::Create();
  box->Pack(subBox, false);

  auto bt = sfg::Button::Create("Add");
  bt->GetSignal(sfg::Button::OnLeftClick).Connect(std::bind(&TilesetController::openLoadTilesetDialog, this));
  subBox->Pack(bt, false);
  bt = sfg::Button::Create("Remove");
  subBox->Pack(bt, false);
  mGui.zoomEntry = sfg::Entry::Create("100%");
  mGui.zoomEntry->SetRequisition({ 50.f, 0.f });
  mGui.zoomEntry->GetSignal(sfg::Entry::OnTextChanged).Connect(std::bind(&TilesetController::updateZoom, this));
  subBox->Pack(mGui.zoomEntry, false);
  mGui.zoomScale = sfg::Scale::Create(0, 5, 0.1f);
  mGui.zoomScale->SetValue(1.f);
  mGui.zoomScale->SetRequisition({ 0, 10 });
  subBox->Pack(mGui.zoomScale);

  auto window = sfg::Window::Create(sfg::Window::Style::TOPLEVEL | sfg::Window::Style::SHADOW);
  window->SetTitle("Tilemaps");
  window->Add(box);
  mDesktop.Add(window);
}

void TilesetController::initLoadTilesetDialog()
{
  mGui.loadTilesetDialog = sfg::Window::Create(sfg::Window::Style::BACKGROUND |
    sfg::Window::Style::TITLEBAR);
  mGui.loadTilesetDialog->SetTitle("Load new Tileset");

  auto box = sfg::Box::Create(sfg::Box::Orientation::VERTICAL, 5.f);

  auto frame = sfg::Frame::Create("Enter tileset name with extension");
  mGui.loadTilesetName = sfg::Entry::Create("tileset.png");
  frame->Add(mGui.loadTilesetName);
  box->Pack(frame);

  auto subBox = sfg::Box::Create(sfg::Box::Orientation::HORIZONTAL, 5.f);
  auto bt = sfg::Button::Create("Load");
  bt->GetSignal(sfg::Button::OnLeftClick).Connect(std::bind(&TilesetController::loadNewTileset, this));
  subBox->Pack(bt);
  bt = sfg::Button::Create("Cancel");
  bt->GetSignal(sfg::Button::OnLeftClick).Connect([this](){mGui.loadTilesetDialog->Show(false); });
  subBox->Pack(bt);

  box->Pack(subBox);

  mGui.loadTilesetDialog->Add(box);
  mGui.loadTilesetDialog->Show(false);
  //mLoadTilesetDialog.window->SetZOrder(5);
  mDesktop.Add(mGui.loadTilesetDialog);
}<|endoftext|>


<commit_before>// Stolen from libLAS' endian.hpp
/******************************************************************************
 * $Id$
 *
 * Project:  libLAS - http://liblas.org - A BSD library for LAS format data.
 * Purpose:  Endian macros
 * Author:   Mateusz Loskot, mateusz@loskot.net
 *
 * This file has been stolen from <boost/endian.hpp> and
 * modified for libLAS purposes.
 *
 * (C) Copyright Mateusz Loskot 2007, mateusz@loskot.net
 * (C) Copyright Caleb Epstein 2005
 * (C) Copyright John Maddock 2006
 * Distributed under the Boost  Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * Revision History
 * 06 Feb 2006 - Initial Revision
 * 09 Nov 2006 - fixed variant and version bits for v4 guids
 * 13 Nov 2006 - added serialization
 * 17 Nov 2006 - added name-based guid creation
 * 20 Nov 2006 - add fixes for gcc (from Tim Blechmann)
 * 07 Mar 2007 - converted to header only
 * 20 Jan 2008 - removed dependency of Boost and modified for libLAS (by Mateusz Loskot)
 ******************************************************************************
 *
 * Copyright (c) 1997
 * Silicon Graphics Computer Systems, Inc.
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Silicon Graphics makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 *
 *
 * Copyright notice reproduced from <boost/detail/limits.hpp>, from
 * which this code was originally taken.
 *
 * Modified by Caleb Epstein to use <endian.h> with GNU libc and to
 * defined the BOOST_ENDIAN macro.
 ****************************************************************************/
#ifndef INCLUDED_DRIVER_OCI_ENDIAN_HPP
#define INCLUDED_DRIVER_OCI_ENDIAN_HPP

# define SWAP_BE_TO_LE(p) \
    do { \
        char* first = static_cast<char*>(static_cast<void*>(&p)); \
        char* last = first + sizeof(p) - 1; \
        for(; first < last; ++first, --last) { \
            char const x = *last; \
            *last = *first; \
            *first = x; \
        }} while(false)

# define SWAP_LE_TO_BE(p) \
    do { \
        char* first = static_cast<char*>(static_cast<void*>(&p)); \
        char* last = first + sizeof(p) - 1; \
        for(; first < last; ++first, --last) { \
            char const x = *last; \
            *last = *first; \
            *first = x; \
        }} while(false)

# define SWAP_BE_TO_LE_N(p, n) \
    do { \
        char* first = static_cast<char*>(static_cast<void*>(&p)); \
        char* last = first + n - 1; \
        for(; first < last; ++first, --last) { \
            char const x = *last; \
            *last = *first; \
            *first = x; \
        }} while(false)

#endif
<commit_msg>add SWAP_LE_TO_BE_N method<commit_after>// Stolen from libLAS' endian.hpp
/******************************************************************************
 * $Id$
 *
 * Project:  libLAS - http://liblas.org - A BSD library for LAS format data.
 * Purpose:  Endian macros
 * Author:   Mateusz Loskot, mateusz@loskot.net
 *
 * This file has been stolen from <boost/endian.hpp> and
 * modified for libLAS purposes.
 *
 * (C) Copyright Mateusz Loskot 2007, mateusz@loskot.net
 * (C) Copyright Caleb Epstein 2005
 * (C) Copyright John Maddock 2006
 * Distributed under the Boost  Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * Revision History
 * 06 Feb 2006 - Initial Revision
 * 09 Nov 2006 - fixed variant and version bits for v4 guids
 * 13 Nov 2006 - added serialization
 * 17 Nov 2006 - added name-based guid creation
 * 20 Nov 2006 - add fixes for gcc (from Tim Blechmann)
 * 07 Mar 2007 - converted to header only
 * 20 Jan 2008 - removed dependency of Boost and modified for libLAS (by Mateusz Loskot)
 ******************************************************************************
 *
 * Copyright (c) 1997
 * Silicon Graphics Computer Systems, Inc.
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Silicon Graphics makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 *
 *
 * Copyright notice reproduced from <boost/detail/limits.hpp>, from
 * which this code was originally taken.
 *
 * Modified by Caleb Epstein to use <endian.h> with GNU libc and to
 * defined the BOOST_ENDIAN macro.
 ****************************************************************************/
#ifndef INCLUDED_DRIVER_OCI_ENDIAN_HPP
#define INCLUDED_DRIVER_OCI_ENDIAN_HPP

# define SWAP_BE_TO_LE(p) \
    do { \
        char* first = static_cast<char*>(static_cast<void*>(&p)); \
        char* last = first + sizeof(p) - 1; \
        for(; first < last; ++first, --last) { \
            char const x = *last; \
            *last = *first; \
            *first = x; \
        }} while(false)

# define SWAP_LE_TO_BE(p) \
    do { \
        char* first = static_cast<char*>(static_cast<void*>(&p)); \
        char* last = first + sizeof(p) - 1; \
        for(; first < last; ++first, --last) { \
            char const x = *last; \
            *last = *first; \
            *first = x; \
        }} while(false)

# define SWAP_BE_TO_LE_N(p, n) \
    do { \
        char* first = static_cast<char*>(static_cast<void*>(&p)); \
        char* last = first + n - 1; \
        for(; first < last; ++first, --last) { \
            char const x = *last; \
            *last = *first; \
            *first = x; \
        }} while(false)

# define SWAP_LE_TO_BE_N(p, n) \
    do { \
        char* first = static_cast<char*>(static_cast<void*>(&p)); \
        char* last = first + n - 1; \
        for(; first < last; ++first, --last) { \
            char const x = *last; \
            *last = *first; \
            *first = x; \
        }} while(false)

#endif
<|endoftext|>


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

#include <cassert>
#include <unistd.h>

#include "zorbaerrors/Assert.h"

#ifdef ZORBA_HAVE_PTHREAD_H
#    include <pthread.h>
#    define ZORBA_THREAD_RETURN void *
#else
#    include <Windows.h>
#    define ZORBA_THREAD_RETURN DWORD WINAPI
#endif

zorba::Runnable::~Runnable()
{
}

zorba::Runnable::Runnable()
  : theStatus(IDLE),
    theFinishCalled(false),
    theMutex(),
    theCondition(theMutex),
    theDeleteAfterRun(false),
    theJoining(false)
#ifdef ZORBA_HAVE_PTHREAD_H
    ,theCalledTerminate(false)
#endif
{
}

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

********************************************************************************/
void zorba::Runnable::reset()
{
  theFinishCalled = false;
  theStatus = IDLE;
}

/*******************************************************************************
  This method is invoked by the parent thread and starts a child thread.
********************************************************************************/
void zorba::Runnable::start()
{
  theStatus = RUNNING;
#ifdef WIN32
  theThread = CreateThread(NULL, 0, &startImpl, (void *) this, 0, &theThreadId);
#else
  if (pthread_create(&theThread, NULL, &startImpl, (void *) this))
    assert(false);
#endif

  // std::cout << "Created child thread " << theThread << std::endl << std::endl;
}

/*******************************************************************************
  This method is invoked by the parent thread
********************************************************************************/
void zorba::Runnable::terminate()
{
  // std::cout << "Terminating child thread " << theThread << std::endl << std::endl;

retry:

  theMutex.lock();

#ifdef ZORBA_HAVE_PTHREAD_H
  theCalledTerminate = true;
#endif

  if (theStatus == SUSPENDED)
  {
#ifdef WIN32
    TerminateThread(theThread, 0);
#else

    pthread_cancel(theThread);

    theCondition.signal();

#endif
  }
  else if (theStatus == TERMINATED)
  {
    theMutex.unlock();
    return;
  }
  else if (theStatus == RUNNING)
  {
    // busy wait until the child thread terminates or suspends itself.
    theMutex.unlock();
    usleep(1000);
    goto retry;
  }
  else
  {
    assert(theStatus == IDLE);
  }

  theMutex.unlock();

  join();

  finishImpl();
}

/*******************************************************************************
  This method is invoked by the parent thread
********************************************************************************/
void zorba::Runnable::join()
{
  theMutex.lock();

  if (theStatus == TERMINATED || theStatus == IDLE)
  {
    theMutex.unlock();
    return;
  }

  theJoining = true;

  theMutex.unlock();

#ifdef WIN32
  WaitForSingleObject( theThread, INFINITE );
#else
  if (pthread_join( theThread, 0 ))
    assert(false);
#endif

  theStatus = TERMINATED;
}

/*******************************************************************************
  This method is called by the child thread to suspend itself for a given
  amount of time.
********************************************************************************/
void zorba::Runnable::suspend(unsigned long aTimeInMs /*= 0*/)
{
#ifdef WIN32
  theStatus = SUSPENDED;
  if (aTimeInMs != 0)
  {
    DWORD lTime = aTimeInMs;
    WaitForSingleObject(theThread, lTime);
  }
  else
  {
    SuspendThread(theThread);
  }
#else

  // std::cout << "Suspending child thread " << theThread << std::endl << std::endl;

  theMutex.lock();

  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  pthread_cleanup_push(mutexCleanupHandler, &theMutex);

  theStatus = SUSPENDED;

  if (aTimeInMs != 0)
    theCondition.timedWait(aTimeInMs);
  else
    theCondition.wait();

  std::cout << "Resuming child thread " << theThread << std::endl << std::endl;

  theStatus = RUNNING;

  pthread_testcancel();
  pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  pthread_cleanup_pop(1);
#endif
}

#ifdef ZORBA_HAVE_PTHREAD_H
void zorba::Runnable::mutexCleanupHandler(void* param)
{
  Mutex* lMutex = static_cast<Mutex*>(param);
  lMutex->unlock();
}
#endif

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

********************************************************************************/
void zorba::Runnable::resume()
{
  theMutex.lock();

#ifdef WIN32
  ResumeThread(theThread);
#else

  assert (theStatus == SUSPENDED);

  theCondition.signal();

#endif
  theStatus = RUNNING;

  theMutex.unlock();
}

/*******************************************************************************
  This method is the "main" method of the child thread.
********************************************************************************/
ZORBA_THREAD_RETURN
zorba::Runnable::startImpl( void* params )
{
  // run the users function in the thread
  Runnable* r = static_cast<Runnable*>(params);
  r->run();

  // finish if the thread reaches the end
  // of the control flow
  r->finishImpl();
  return NULL;
}

/*******************************************************************************
  Called if the child thread reaches the end of the control flow or terminate
  is requested
********************************************************************************/
void zorba::Runnable::finishImpl()
{
  theMutex.lock();

#ifndef NDEBUG
  assert (!theFinishCalled);
#endif

  finish();

  theFinishCalled = true;

  theStatus = TERMINATED;

  theMutex.unlock();

#ifdef ZORBA_HAVE_PTHREAD_H
  if (!theCalledTerminate && !theJoining)
  {
    pthread_detach(theThread);
  }
#endif

  if (theDeleteAfterRun)
  {
    delete this;
  }
}

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

********************************************************************************/
void zorba::Runnable::setDeleteAfterRun( bool aDeleteAfterRun )
{
  theDeleteAfterRun = aDeleteAfterRun;

  // Check postconditions
  ZORBA_ASSERT(theDeleteAfterRun == aDeleteAfterRun);
}
<commit_msg>Fix Windows build.<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "runnable.h"

#include <cassert>

#include "zorbaerrors/Assert.h"

#ifdef ZORBA_HAVE_PTHREAD_H
#include <unistd.h>
#    include <pthread.h>
#    define ZORBA_THREAD_RETURN void *
#else
#    include <Windows.h>
#    define ZORBA_THREAD_RETURN DWORD WINAPI
#endif

zorba::Runnable::~Runnable()
{
}

zorba::Runnable::Runnable()
  : theStatus(IDLE),
    theFinishCalled(false),
    theMutex(),
    theCondition(theMutex),
    theDeleteAfterRun(false),
    theJoining(false)
#ifdef ZORBA_HAVE_PTHREAD_H
    ,theCalledTerminate(false)
#endif
{
}

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

********************************************************************************/
void zorba::Runnable::reset()
{
  theFinishCalled = false;
  theStatus = IDLE;
}

/*******************************************************************************
  This method is invoked by the parent thread and starts a child thread.
********************************************************************************/
void zorba::Runnable::start()
{
  theStatus = RUNNING;
#ifdef WIN32
  theThread = CreateThread(NULL, 0, &startImpl, (void *) this, 0, &theThreadId);
#else
  if (pthread_create(&theThread, NULL, &startImpl, (void *) this))
    assert(false);
#endif

  // std::cout << "Created child thread " << theThread << std::endl << std::endl;
}

/*******************************************************************************
  This method is invoked by the parent thread
********************************************************************************/
void zorba::Runnable::terminate()
{
  // std::cout << "Terminating child thread " << theThread << std::endl << std::endl;

retry:

  theMutex.lock();

#ifdef ZORBA_HAVE_PTHREAD_H
  theCalledTerminate = true;
#endif

  if (theStatus == SUSPENDED)
  {
#ifdef WIN32
    TerminateThread(theThread, 0);
#else

    pthread_cancel(theThread);

    theCondition.signal();

#endif
  }
  else if (theStatus == TERMINATED)
  {
    theMutex.unlock();
    return;
  }
  else if (theStatus == RUNNING)
  {
    // busy wait until the child thread terminates or suspends itself.
    theMutex.unlock();
#ifndef WIN32
    usleep(1000);
#else
    Sleep(1);
#endif
    goto retry;
  }
  else
  {
    assert(theStatus == IDLE);
  }

  theMutex.unlock();

  join();

  finishImpl();
}

/*******************************************************************************
  This method is invoked by the parent thread
********************************************************************************/
void zorba::Runnable::join()
{
  theMutex.lock();

  if (theStatus == TERMINATED || theStatus == IDLE)
  {
    theMutex.unlock();
    return;
  }

  theJoining = true;

  theMutex.unlock();

#ifdef WIN32
  WaitForSingleObject( theThread, INFINITE );
#else
  if (pthread_join( theThread, 0 ))
    assert(false);
#endif

  theStatus = TERMINATED;
}

/*******************************************************************************
  This method is called by the child thread to suspend itself for a given
  amount of time.
********************************************************************************/
void zorba::Runnable::suspend(unsigned long aTimeInMs /*= 0*/)
{
#ifdef WIN32
  theStatus = SUSPENDED;
  if (aTimeInMs != 0)
  {
    DWORD lTime = aTimeInMs;
    WaitForSingleObject(theThread, lTime);
  }
  else
  {
    SuspendThread(theThread);
  }
#else

  // std::cout << "Suspending child thread " << theThread << std::endl << std::endl;

  theMutex.lock();

  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  pthread_cleanup_push(mutexCleanupHandler, &theMutex);

  theStatus = SUSPENDED;

  if (aTimeInMs != 0)
    theCondition.timedWait(aTimeInMs);
  else
    theCondition.wait();

  std::cout << "Resuming child thread " << theThread << std::endl << std::endl;

  theStatus = RUNNING;

  pthread_testcancel();
  pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  pthread_cleanup_pop(1);
#endif
}

#ifdef ZORBA_HAVE_PTHREAD_H
void zorba::Runnable::mutexCleanupHandler(void* param)
{
  Mutex* lMutex = static_cast<Mutex*>(param);
  lMutex->unlock();
}
#endif

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

********************************************************************************/
void zorba::Runnable::resume()
{
  theMutex.lock();

#ifdef WIN32
  ResumeThread(theThread);
#else

  assert (theStatus == SUSPENDED);

  theCondition.signal();

#endif
  theStatus = RUNNING;

  theMutex.unlock();
}

/*******************************************************************************
  This method is the "main" method of the child thread.
********************************************************************************/
ZORBA_THREAD_RETURN
zorba::Runnable::startImpl( void* params )
{
  // run the users function in the thread
  Runnable* r = static_cast<Runnable*>(params);
  r->run();

  // finish if the thread reaches the end
  // of the control flow
  r->finishImpl();
  return NULL;
}

/*******************************************************************************
  Called if the child thread reaches the end of the control flow or terminate
  is requested
********************************************************************************/
void zorba::Runnable::finishImpl()
{
  theMutex.lock();

#ifndef NDEBUG
  assert (!theFinishCalled);
#endif

  finish();

  theFinishCalled = true;

  theStatus = TERMINATED;

  theMutex.unlock();

#ifdef ZORBA_HAVE_PTHREAD_H
  if (!theCalledTerminate && !theJoining)
  {
    pthread_detach(theThread);
  }
#endif

  if (theDeleteAfterRun)
  {
    delete this;
  }
}

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

********************************************************************************/
void zorba::Runnable::setDeleteAfterRun( bool aDeleteAfterRun )
{
  theDeleteAfterRun = aDeleteAfterRun;

  // Check postconditions
  ZORBA_ASSERT(theDeleteAfterRun == aDeleteAfterRun);
}
<|endoftext|>


<commit_before>#include "Library.h"
#include "ui_Library.h"

#include <QFileDialog>
#include <QInputDialog>
#include <QProcess>
#include <QMessageBox>
#include <QDebug>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>

#include <cctype>

#if defined(_WIN32) || defined(_WIN64)
#include <QSettings>
#endif

namespace pt = boost::property_tree;

Library::Library(Database db)
    : QWidget(0),
      db(db),
      ui(new Ui::Library),
      runningProcess(new QProcess(this))
{
    ui->setupUi(this);
    this->setObjectName("libraryUI");
    connect(runningProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(finished(int, QProcess::ExitStatus)));
    connect(runningProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onLaunchError(QProcess::ProcessError)));

    QList<Game> games = db.getGames();
    for (auto game : games)
    {
        qDebug() << game.id << game.gameName << game.gameDirectory << game.executablePath;
    }

    refreshGames();
    findSteamGames();
}

Library::~Library()
{
    delete ui;
    delete runningProcess;
}

void Library::on_testLaunch_clicked()
{
    if (!isProcessRunning())
    {
        auto selection = ui->gameListWidget->currentItem();
        if (selection != nullptr)
        {
            Game* game = db.getGameByName(selection->text());
            runProcess(game->executablePath, game->gameDirectory);
        }
    }
    else
    {
        QMessageBox messageBox;
        messageBox.setText("Error: an application is already running.");
        messageBox.exec();
    }
}

void Library::on_addGame_clicked()
{
    QString name = QInputDialog::getText(0, "Game Name", "Game Name:");

    if (name.trimmed() == "")
    {
        QMessageBox::critical(0, "Error", "You must specify a game name!");
        return;
    }

    QFileDialog exeDialog;
    exeDialog.setWindowTitle("Select Executable");
    exeDialog.setFileMode(QFileDialog::ExistingFile);
    #if defined(__unix__)
        exeDialog.setDirectory(QDir::home());
    #elif defined(_WIN32) || defined(_WIN64)
        exeDialog.setDirectory("C:");
    #endif

    if (exeDialog.exec())
    {
        QStringList files = exeDialog.selectedFiles();
        QString exe = files.at(0);
        #ifdef Q_WS_MACX
            //Get the binary from the app bundle
            QDir dir(file + "/Contents/MacOS");
            // TODO: Change to dir.entryList(QDir::NoDotAndDotDot) to be safe
            QStringList fileList = dir.entryList();
            file = dir.absoluteFilePath(fileList.at(2));// USUALLY this is the executable (after ., ..)
        #endif

        QFileDialog wdDialog; // Working Directory
        wdDialog.setWindowTitle("Select Working Directory");
        wdDialog.setFileMode(QFileDialog::DirectoryOnly);
        wdDialog.setDirectory(exeDialog.directory().absolutePath());

        if (wdDialog.exec())
        {
            QStringList dirs = wdDialog.selectedFiles();
            QString dir = dirs.at(0);

            qDebug() << "Adding game:" << name << exe << dir;
            db.addGame(name, dir, exe);

            refreshGames();
        }
    }
}

void Library::on_removeGame_clicked()
{
    auto selection = ui->gameListWidget->currentItem();
    if (selection != nullptr)
    {
        db.removeGameByName(selection->text());
        refreshGames();
    }
}

void Library::runProcess(QString file, QString workingDirectory)
{
    // TODO: Implement some threading
    if (!isProcessRunning())
    {
        qDebug() << "Launching:" << file << ", at" << workingDirectory;
        runningProcess->setWorkingDirectory(workingDirectory);
        runningProcess->setStandardErrorFile("error.txt");
        runningProcess->setStandardOutputFile("log.txt");
        runningProcess->start(file, QStringList());
        runningProcess->waitForStarted();
    }
}

void Library::refreshGames()
{
    ui->gameListWidget->clear();
    QList<Game> gameList = db.getGames();
    for (auto game : gameList)
    {
        ui->gameListWidget->addItem(game.gameName);
    }
}

void Library::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
    if (exitCode != 0)
    {
        QMessageBox(QMessageBox::Warning, "Warning", "The game finished, but it claims to have encountered an error").exec();
    }
}

void Library::onLaunchError(QProcess::ProcessError error)
{
    switch (error)
    {
        case QProcess::FailedToStart:
            QMessageBox(QMessageBox::Critical, "Error", "Could not start the game. Please double check that you are using the correct file to launch it.").exec();
            break;
        case QProcess::Crashed:
            QMessageBox(QMessageBox::Warning, "Crash!", "The launched game has crashed").exec();
            break;
        default:
            // Other cases are errors unrelated to startup, so let's not handle them
            break;
    }
}

bool Library::isProcessRunning() const
{
    // We shall consider "Starting" to be running here too
    return runningProcess->state() != QProcess::NotRunning;
}

void Library::findSteamGames()
{
    #if defined(_WIN32) || defined(_WIN64)
        QSettings settings("HKEY_CURRENT_USER\\Software\\Valve\\Steam", QSettings::NativeFormat);
        QDir steamRoot(settings.value("SteamPath").toString());
    #elif defined(__apple__)
        // TODO: however OS X handles steam
    #elif defined(__linux__)
        QDir steamRoot(QDir::home().filePath(".steam/steam"));
    #else
        QMessageBox(QMessageBox::Critical, "Error", "Platform doesn't support steam.");
    #endif

    if (steamRoot.exists())
    {
        pt::ptree libraryFolders;
        pt::read_info(steamRoot.filePath("steamapps/libraryfolders.vdf").toLocal8Bit().constData(), libraryFolders);
        steamDirectoryList.append(steamRoot.filePath(""));
        QString pathString = "" + steamDirectoryList.at(0) + "\n";

        for (auto kv : libraryFolders.get_child("LibraryFolders"))
        {
            if (std::isdigit(static_cast<int>(*kv.first.data())))
            {
                std::string path = kv.second.data();
                QDir dir(QString::fromStdString(path));
                if (dir.exists())
                {
                    steamDirectoryList.append(dir.filePath(""));
                    pathString += dir.filePath("");
                    pathString += "\n";
                }
            }
        }

        // TODO: Make this prompting better/less obtrusive
        bool directoryPlural = (steamDirectoryList.size() > 1);
        int ret = QMessageBox(QMessageBox::Question, "Found " + QString::number(steamDirectoryList.size()) + " director" + (directoryPlural ? "ies" : "y"), QString::number(steamDirectoryList.size()) + " directories have been found.\n\n" + pathString + "Proceed?", QMessageBox::Yes | QMessageBox::No).exec();
        switch(ret)
        {
            case QMessageBox::Yes:
                parseAcf();
                break;
            case QMessageBox::No:
                break;
            default:
                break;
        }
    }
}

void Library::parseAcf()
{
    // TODO: This stuff needs its own thread
    for(QString iter : steamDirectoryList)
    {
        QDir steamAppsDir(iter);
        steamAppsDir = steamAppsDir.filePath("steamapps");
        QStringList fileList = steamAppsDir.entryList(QStringList("*.acf"), QDir::Files | QDir::NoSymLinks);

        for (auto fileIter : fileList)
        {
            pt::ptree fileTree;
            std::string acfDir = steamAppsDir.filePath(fileIter).toLocal8Bit().constData();
            pt::read_info(acfDir, fileTree);

            QString name = QString::fromStdString(fileTree.get<std::string>("AppState.name"));
            // TODO: Either add SteamID to db, or add getGameByPath
            if (db.getGameByName(name) == nullptr)
            {
                QString path = steamAppsDir.filePath("common/" + QString::fromStdString(fileTree.get<std::string>("AppState.installdir")));
                QString exe;
                QStringList exeList = QDir(path).entryList(QDir::Files | QDir::NoSymLinks | QDir::Executable);

                QFileDialog exeDialog;
                exeDialog.setWindowTitle("Select Executable");
                exeDialog.setFileMode(QFileDialog::ExistingFile);
                exeDialog.setDirectory(path);
                if (exeDialog.exec())
                {
                    exe = exeDialog.selectedFiles().at(0);
                }
                db.addGame(name, path, exe);
                refreshGames();
            }
            else
            {
                QMessageBox(QMessageBox::Critical, name + " exists", name + " already exists in the database.").exec();
                refreshGames();
            }
        }
    }
}
<commit_msg>Fix bug when Steam is not installed on Windows<commit_after>#include "Library.h"
#include "ui_Library.h"

#include <QFileDialog>
#include <QInputDialog>
#include <QProcess>
#include <QMessageBox>
#include <QDebug>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>

#include <cctype>

#if defined(_WIN32) || defined(_WIN64)
#include <QSettings>
#endif

namespace pt = boost::property_tree;

Library::Library(Database db)
    : QWidget(0),
      db(db),
      ui(new Ui::Library),
      runningProcess(new QProcess(this))
{
    ui->setupUi(this);
    this->setObjectName("libraryUI");
    connect(runningProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(finished(int, QProcess::ExitStatus)));
    connect(runningProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onLaunchError(QProcess::ProcessError)));

    QList<Game> games = db.getGames();
    for (auto game : games)
    {
        qDebug() << game.id << game.gameName << game.gameDirectory << game.executablePath;
    }

    refreshGames();
    findSteamGames();
}

Library::~Library()
{
    delete ui;
    delete runningProcess;
}

void Library::on_testLaunch_clicked()
{
    if (!isProcessRunning())
    {
        auto selection = ui->gameListWidget->currentItem();
        if (selection != nullptr)
        {
            Game* game = db.getGameByName(selection->text());
            runProcess(game->executablePath, game->gameDirectory);
        }
    }
    else
    {
        QMessageBox messageBox;
        messageBox.setText("Error: an application is already running.");
        messageBox.exec();
    }
}

void Library::on_addGame_clicked()
{
    QString name = QInputDialog::getText(0, "Game Name", "Game Name:");

    if (name.trimmed() == "")
    {
        QMessageBox::critical(0, "Error", "You must specify a game name!");
        return;
    }

    QFileDialog exeDialog;
    exeDialog.setWindowTitle("Select Executable");
    exeDialog.setFileMode(QFileDialog::ExistingFile);
    #if defined(__unix__)
        exeDialog.setDirectory(QDir::home());
    #elif defined(_WIN32) || defined(_WIN64)
        exeDialog.setDirectory("C:");
    #endif

    if (exeDialog.exec())
    {
        QStringList files = exeDialog.selectedFiles();
        QString exe = files.at(0);
        #ifdef Q_WS_MACX
            //Get the binary from the app bundle
            QDir dir(file + "/Contents/MacOS");
            // TODO: Change to dir.entryList(QDir::NoDotAndDotDot) to be safe
            QStringList fileList = dir.entryList();
            file = dir.absoluteFilePath(fileList.at(2));// USUALLY this is the executable (after ., ..)
        #endif

        QFileDialog wdDialog; // Working Directory
        wdDialog.setWindowTitle("Select Working Directory");
        wdDialog.setFileMode(QFileDialog::DirectoryOnly);
        wdDialog.setDirectory(exeDialog.directory().absolutePath());

        if (wdDialog.exec())
        {
            QStringList dirs = wdDialog.selectedFiles();
            QString dir = dirs.at(0);

            qDebug() << "Adding game:" << name << exe << dir;
            db.addGame(name, dir, exe);

            refreshGames();
        }
    }
}

void Library::on_removeGame_clicked()
{
    auto selection = ui->gameListWidget->currentItem();
    if (selection != nullptr)
    {
        db.removeGameByName(selection->text());
        refreshGames();
    }
}

void Library::runProcess(QString file, QString workingDirectory)
{
    // TODO: Implement some threading
    if (!isProcessRunning())
    {
        qDebug() << "Launching:" << file << ", at" << workingDirectory;
        runningProcess->setWorkingDirectory(workingDirectory);
        runningProcess->setStandardErrorFile("error.txt");
        runningProcess->setStandardOutputFile("log.txt");
        runningProcess->start(file, QStringList());
        runningProcess->waitForStarted();
    }
}

void Library::refreshGames()
{
    ui->gameListWidget->clear();
    QList<Game> gameList = db.getGames();
    for (auto game : gameList)
    {
        ui->gameListWidget->addItem(game.gameName);
    }
}

void Library::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
    if (exitCode != 0)
    {
        QMessageBox(QMessageBox::Warning, "Warning", "The game finished, but it claims to have encountered an error").exec();
    }
}

void Library::onLaunchError(QProcess::ProcessError error)
{
    switch (error)
    {
        case QProcess::FailedToStart:
            QMessageBox(QMessageBox::Critical, "Error", "Could not start the game. Please double check that you are using the correct file to launch it.").exec();
            break;
        case QProcess::Crashed:
            QMessageBox(QMessageBox::Warning, "Crash!", "The launched game has crashed").exec();
            break;
        default:
            // Other cases are errors unrelated to startup, so let's not handle them
            break;
    }
}

bool Library::isProcessRunning() const
{
    // We shall consider "Starting" to be running here too
    return runningProcess->state() != QProcess::NotRunning;
}

void Library::findSteamGames()
{
	bool steamFound = true;
    #if defined(_WIN32) || defined(_WIN64)
        QSettings settings("HKEY_CURRENT_USER\\Software\\Valve\\Steam", QSettings::NativeFormat);
        QString steamPath = settings.value("SteamPath").toString();
        if (steamPath.trimmed() == "")
        {
            qDebug("Steam was not found, probably not installed.");
            steamFound = false;
        }
        QDir steamRoot(steamPath);
    #elif defined(__apple__)
        // TODO: however OS X handles steam
    #elif defined(__linux__)
        QDir steamRoot(QDir::home().filePath(".steam/steam"));
    #else
        QMessageBox(QMessageBox::Critical, "Error", "Platform doesn't support steam.");
    #endif

    if (steamRoot.exists() && steamFound)
    {
        pt::ptree libraryFolders;
        pt::read_info(steamRoot.filePath("steamapps/libraryfolders.vdf").toLocal8Bit().constData(), libraryFolders);
        steamDirectoryList.append(steamRoot.filePath(""));
        QString pathString = "" + steamDirectoryList.at(0) + "\n";

        for (auto kv : libraryFolders.get_child("LibraryFolders"))
        {
            if (std::isdigit(static_cast<int>(*kv.first.data())))
            {
                std::string path = kv.second.data();
                QDir dir(QString::fromStdString(path));
                if (dir.exists())
                {
                    steamDirectoryList.append(dir.filePath(""));
                    pathString += dir.filePath("");
                    pathString += "\n";
                }
            }
        }

        // TODO: Make this prompting better/less obtrusive
        bool directoryPlural = (steamDirectoryList.size() > 1);
        int ret = QMessageBox(QMessageBox::Question, "Found " + QString::number(steamDirectoryList.size()) + " director" + (directoryPlural ? "ies" : "y"), QString::number(steamDirectoryList.size()) + " directories have been found.\n\n" + pathString + "Proceed?", QMessageBox::Yes | QMessageBox::No).exec();
        switch(ret)
        {
            case QMessageBox::Yes:
                parseAcf();
                break;
            case QMessageBox::No:
                break;
            default:
                break;
        }
    }
}

void Library::parseAcf()
{
    // TODO: This stuff needs its own thread
    for(QString iter : steamDirectoryList)
    {
        QDir steamAppsDir(iter);
        steamAppsDir = steamAppsDir.filePath("steamapps");
        QStringList fileList = steamAppsDir.entryList(QStringList("*.acf"), QDir::Files | QDir::NoSymLinks);

        for (auto fileIter : fileList)
        {
            pt::ptree fileTree;
            std::string acfDir = steamAppsDir.filePath(fileIter).toLocal8Bit().constData();
            pt::read_info(acfDir, fileTree);

            QString name = QString::fromStdString(fileTree.get<std::string>("AppState.name"));
            // TODO: Either add SteamID to db, or add getGameByPath
            if (db.getGameByName(name) == nullptr)
            {
                QString path = steamAppsDir.filePath("common/" + QString::fromStdString(fileTree.get<std::string>("AppState.installdir")));
                QString exe;
                QStringList exeList = QDir(path).entryList(QDir::Files | QDir::NoSymLinks | QDir::Executable);

                QFileDialog exeDialog;
                exeDialog.setWindowTitle("Select Executable");
                exeDialog.setFileMode(QFileDialog::ExistingFile);
                exeDialog.setDirectory(path);
                if (exeDialog.exec())
                {
                    exe = exeDialog.selectedFiles().at(0);
                }
                db.addGame(name, path, exe);
                refreshGames();
            }
            else
            {
                QMessageBox(QMessageBox::Critical, name + " exists", name + " already exists in the database.").exec();
                refreshGames();
            }
        }
    }
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_ESCAPE_STRING_HPP_INCLUDED
#define TORRENT_ESCAPE_STRING_HPP_INCLUDED

#include <string>
#include <boost/limits.hpp>
#include <boost/array.hpp>
#include "libtorrent/config.hpp"
#include "libtorrent/size_type.hpp"
#include "libtorrent/error_code.hpp"

namespace libtorrent
{
	TORRENT_EXTRA_EXPORT boost::array<char, 3 + std::numeric_limits<size_type>::digits10> to_string(size_type n);
	TORRENT_EXTRA_EXPORT bool is_alpha(char c);
	TORRENT_EXTRA_EXPORT bool is_digit(char c);
	TORRENT_EXTRA_EXPORT bool is_print(char c);
	TORRENT_EXTRA_EXPORT bool is_space(char c);
	TORRENT_EXTRA_EXPORT char to_lower(char c);

	TORRENT_EXTRA_EXPORT int split_string(char const** tags, int buf_size, char* in);
	TORRENT_EXTRA_EXPORT bool string_begins_no_case(char const* s1, char const* s2);
	TORRENT_EXTRA_EXPORT bool string_equal_no_case(char const* s1, char const* s2);

	TORRENT_EXTRA_EXPORT void url_random(char* begin, char* end);

	TORRENT_EXTRA_EXPORT std::string unescape_string(std::string const& s, error_code& ec);
	// replaces all disallowed URL characters by their %-encoding
	TORRENT_EXTRA_EXPORT std::string escape_string(const char* str, int len);
	// same as escape_string but does not encode '/'
	TORRENT_EXTRA_EXPORT std::string escape_path(const char* str, int len);
	// if the url does not appear to be encoded, and it contains illegal url characters
	// it will be encoded
	TORRENT_EXTRA_EXPORT std::string maybe_url_encode(std::string const& url);

	TORRENT_EXTRA_EXPORT bool need_encoding(char const* str, int len);

	// encodes a string using the base64 scheme
	TORRENT_EXTRA_EXPORT std::string base64encode(std::string const& s);
	TORRENT_EXTRA_EXPORT std::string base64decode(std::string const& s);
	// encodes a string using the base32 scheme
	TORRENT_EXTRA_EXPORT std::string base32encode(std::string const& s);
	TORRENT_EXTRA_EXPORT std::string base32decode(std::string const& s);

	TORRENT_EXTRA_EXPORT std::string url_has_argument(
		std::string const& url, std::string argument, std::string::size_type* out_pos = 0);

	// replaces \ with /
	TORRENT_EXTRA_EXPORT void convert_path_to_posix(std::string& path);

	TORRENT_EXTRA_EXPORT std::string read_until(char const*& str, char delim, char const* end);
	TORRENT_EXTRA_EXPORT std::string to_hex(std::string const& s);
	TORRENT_EXTRA_EXPORT bool is_hex(char const *in, int len);
	TORRENT_EXTRA_EXPORT void to_hex(char const *in, int len, char* out);
	TORRENT_EXTRA_EXPORT bool from_hex(char const *in, int len, char* out);

#if defined TORRENT_WINDOWS && TORRENT_USE_WSTRING
	TORRENT_EXTRA_EXPORT std::wstring convert_to_wstring(std::string const& s);
	TORRENT_EXTRA_EXPORT std::string convert_from_wstring(std::wstring const& s);
#endif

#if TORRENT_USE_ICONV || TORRENT_USE_LOCALE
	TORRENT_EXTRA_EXPORT std::string convert_to_native(std::string const& s);
	TORRENT_EXTRA_EXPORT std::string convert_from_native(std::string const& s);
#else
	inline std::string const& convert_to_native(std::string const& s) { return s; }
	inline std::string const& convert_from_native(std::string const& s) { return s; }
#endif
}

#endif // TORRENT_ESCAPE_STRING_HPP_INCLUDED

<commit_msg>fix dynamic link build<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_ESCAPE_STRING_HPP_INCLUDED
#define TORRENT_ESCAPE_STRING_HPP_INCLUDED

#include <string>
#include <boost/limits.hpp>
#include <boost/array.hpp>
#include "libtorrent/config.hpp"
#include "libtorrent/size_type.hpp"
#include "libtorrent/error_code.hpp"

namespace libtorrent
{
	TORRENT_EXTRA_EXPORT boost::array<char, 3 + std::numeric_limits<size_type>::digits10> to_string(size_type n);
	TORRENT_EXTRA_EXPORT bool is_alpha(char c);
	TORRENT_EXPORT bool is_digit(char c);
	TORRENT_EXTRA_EXPORT bool is_print(char c);
	TORRENT_EXTRA_EXPORT bool is_space(char c);
	TORRENT_EXTRA_EXPORT char to_lower(char c);

	TORRENT_EXTRA_EXPORT int split_string(char const** tags, int buf_size, char* in);
	TORRENT_EXTRA_EXPORT bool string_begins_no_case(char const* s1, char const* s2);
	TORRENT_EXTRA_EXPORT bool string_equal_no_case(char const* s1, char const* s2);

	TORRENT_EXTRA_EXPORT void url_random(char* begin, char* end);

	TORRENT_EXTRA_EXPORT std::string unescape_string(std::string const& s, error_code& ec);
	// replaces all disallowed URL characters by their %-encoding
	TORRENT_EXTRA_EXPORT std::string escape_string(const char* str, int len);
	// same as escape_string but does not encode '/'
	TORRENT_EXTRA_EXPORT std::string escape_path(const char* str, int len);
	// if the url does not appear to be encoded, and it contains illegal url characters
	// it will be encoded
	TORRENT_EXTRA_EXPORT std::string maybe_url_encode(std::string const& url);

	TORRENT_EXTRA_EXPORT bool need_encoding(char const* str, int len);

	// encodes a string using the base64 scheme
	TORRENT_EXTRA_EXPORT std::string base64encode(std::string const& s);
	TORRENT_EXTRA_EXPORT std::string base64decode(std::string const& s);
	// encodes a string using the base32 scheme
	TORRENT_EXTRA_EXPORT std::string base32encode(std::string const& s);
	TORRENT_EXTRA_EXPORT std::string base32decode(std::string const& s);

	TORRENT_EXTRA_EXPORT std::string url_has_argument(
		std::string const& url, std::string argument, std::string::size_type* out_pos = 0);

	// replaces \ with /
	TORRENT_EXTRA_EXPORT void convert_path_to_posix(std::string& path);

	TORRENT_EXTRA_EXPORT std::string read_until(char const*& str, char delim, char const* end);
	TORRENT_EXTRA_EXPORT std::string to_hex(std::string const& s);
	TORRENT_EXTRA_EXPORT bool is_hex(char const *in, int len);
	TORRENT_EXTRA_EXPORT void to_hex(char const *in, int len, char* out);
	TORRENT_EXTRA_EXPORT bool from_hex(char const *in, int len, char* out);

#if defined TORRENT_WINDOWS && TORRENT_USE_WSTRING
	TORRENT_EXTRA_EXPORT std::wstring convert_to_wstring(std::string const& s);
	TORRENT_EXTRA_EXPORT std::string convert_from_wstring(std::wstring const& s);
#endif

#if TORRENT_USE_ICONV || TORRENT_USE_LOCALE
	TORRENT_EXTRA_EXPORT std::string convert_to_native(std::string const& s);
	TORRENT_EXTRA_EXPORT std::string convert_from_native(std::string const& s);
#else
	inline std::string const& convert_to_native(std::string const& s) { return s; }
	inline std::string const& convert_from_native(std::string const& s) { return s; }
#endif
}

#endif // TORRENT_ESCAPE_STRING_HPP_INCLUDED

<|endoftext|>


<commit_before>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef NODE_HPP
#define NODE_HPP

#include <algorithm>
#include <map>
#include <set>

#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/msg.hpp>

#include <libtorrent/io.hpp>
#include <libtorrent/session_settings.hpp>
#include <libtorrent/assert.hpp>

#include <boost/cstdint.hpp>
#include <boost/optional.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/ref.hpp>

#include "libtorrent/socket.hpp"

namespace libtorrent { namespace dht
{

using asio::ip::udp;

#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DECLARE_LOG(node);
#endif

// this is the entry for every peer
// the timestamp is there to make it possible
// to remove stale peers
struct peer_entry
{
	tcp::endpoint addr;
	ptime added;
};

// this is a group. It contains a set of group members
struct torrent_entry
{
	std::set<peer_entry> peers;
};

inline bool operator<(peer_entry const& lhs, peer_entry const& rhs)
{
	return lhs.addr.address() == rhs.addr.address()
		? lhs.addr.port() < rhs.addr.port()
		: lhs.addr.address() < rhs.addr.address();
}

struct null_type {};

class announce_observer : public observer
{
public:
	announce_observer(boost::pool<>& allocator
		, sha1_hash const& info_hash
		, int listen_port
		, entry const& write_token)
		: observer(allocator)
		, m_info_hash(info_hash)
		, m_listen_port(listen_port)
		, m_token(write_token)
	{}

	void send(msg& m)
	{
		m.port = m_listen_port;
		m.info_hash = m_info_hash;
		m.write_token = m_token;
	}

	void timeout() {}
	void reply(msg const&) {}
	void abort() {}

private:
	sha1_hash m_info_hash;
	int m_listen_port;
	entry m_token;
};

class get_peers_observer : public observer
{
public:
	get_peers_observer(sha1_hash const& info_hash
		, int listen_port
		, rpc_manager& rpc
		, boost::function<void(std::vector<tcp::endpoint> const&, sha1_hash const&)> f)
		: observer(rpc.allocator())
		, m_info_hash(info_hash)
		, m_listen_port(listen_port)
		, m_rpc(rpc)
		, m_fun(f)
	{}

	void send(msg& m)
	{
		m.port = m_listen_port;
		m.info_hash = m_info_hash;
	}

	void timeout() {}
	void reply(msg const& r)
	{
		m_rpc.invoke(messages::announce_peer, r.addr
			, observer_ptr(new (m_rpc.allocator().malloc()) announce_observer(
				m_rpc.allocator(), m_info_hash, m_listen_port, r.write_token)));
		m_fun(r.peers, m_info_hash);
	}
	void abort() {}

private:
	sha1_hash m_info_hash;
	int m_listen_port;
	rpc_manager& m_rpc;
	boost::function<void(std::vector<tcp::endpoint> const&, sha1_hash const&)> m_fun;
};

class node_impl : boost::noncopyable
{
typedef std::map<node_id, torrent_entry> table_t;
public:
	node_impl(boost::function<void(msg const&)> const& f
		, dht_settings const& settings, boost::optional<node_id> node_id);

	virtual ~node_impl() {}

	void refresh(node_id const& id, boost::function0<void> f);
	void bootstrap(std::vector<udp::endpoint> const& nodes
		, boost::function0<void> f);
	void find_node(node_id const& id, boost::function<
	void(std::vector<node_entry> const&)> f);
	void add_router_node(udp::endpoint router);

	void incoming(msg const& m);

	void refresh();
	void refresh_bucket(int bucket);
	int bucket_size(int bucket);

	typedef routing_table::iterator iterator;

	iterator begin() const { return m_table.begin(); }
	iterator end() const { return m_table.end(); }

	typedef table_t::iterator data_iterator;

	node_id const& nid() const { return m_id; }
	boost::tuple<int, int> size() const{ return m_table.size(); }
	size_type num_global_nodes() const
	{ return m_table.num_global_nodes(); }

	data_iterator begin_data() { return m_map.begin(); }
	data_iterator end_data() { return m_map.end(); }
	int data_size() const { return int(m_map.size()); }

#ifdef TORRENT_DHT_VERBOSE_LOGGING
	void print_state(std::ostream& os) const
	{ m_table.print_state(os); }
#endif

	void announce(sha1_hash const& info_hash, int listen_port
		, boost::function<void(std::vector<tcp::endpoint> const&
			, sha1_hash const&)> f);

	bool verify_token(msg const& m);
	entry generate_token(msg const& m);

	// the returned time is the delay until connection_timeout()
	// should be called again the next time
	time_duration connection_timeout();
	time_duration refresh_timeout();

	// generates a new secret number used to generate write tokens
	void new_write_key();

	// pings the given node, and adds it to
	// the routing table if it respons and if the
	// bucket is not full.
	void add_node(udp::endpoint node);

	void replacement_cache(bucket_t& nodes) const
	{ m_table.replacement_cache(nodes); }

protected:
	// is called when a find data request is received. Should
	// return false if the data is not stored on this node. If
	// the data is stored, it should be serialized into 'data'.
	bool on_find(msg const& m, std::vector<tcp::endpoint>& peers) const;

	// this is called when a store request is received. The data
	// is store-parameters and the data to be stored.
	void on_announce(msg const& m, msg& reply);

	dht_settings const& m_settings;

	// the maximum number of peers to send in a get_peers
	// reply. Ordinary trackers usually limit this to 50.
	// 50 => 6 * 50 = 250 bytes + packet overhead
	int m_max_peers_reply;

private:
	void incoming_request(msg const& h);

	node_id m_id;
	routing_table m_table;
	rpc_manager m_rpc;
	table_t m_map;

	ptime m_last_tracker_tick;

	// secret random numbers used to create write tokens
	int m_secret[2];
};

} } // namespace libtorrent::dht

#endif // NODE_HPP

<commit_msg>fixed dht asserts<commit_after>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef NODE_HPP
#define NODE_HPP

#include <algorithm>
#include <map>
#include <set>

#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/msg.hpp>

#include <libtorrent/io.hpp>
#include <libtorrent/session_settings.hpp>
#include <libtorrent/assert.hpp>

#include <boost/cstdint.hpp>
#include <boost/optional.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/ref.hpp>

#include "libtorrent/socket.hpp"

namespace libtorrent { namespace dht
{

using asio::ip::udp;

#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DECLARE_LOG(node);
#endif

// this is the entry for every peer
// the timestamp is there to make it possible
// to remove stale peers
struct peer_entry
{
	tcp::endpoint addr;
	ptime added;
};

// this is a group. It contains a set of group members
struct torrent_entry
{
	std::set<peer_entry> peers;
};

inline bool operator<(peer_entry const& lhs, peer_entry const& rhs)
{
	return lhs.addr.address() == rhs.addr.address()
		? lhs.addr.port() < rhs.addr.port()
		: lhs.addr.address() < rhs.addr.address();
}

struct null_type {};

class announce_observer : public observer
{
public:
	announce_observer(boost::pool<>& allocator
		, sha1_hash const& info_hash
		, int listen_port
		, entry const& write_token)
		: observer(allocator)
		, m_info_hash(info_hash)
		, m_listen_port(listen_port)
		, m_token(write_token)
	{}

	void send(msg& m)
	{
		m.port = m_listen_port;
		m.info_hash = m_info_hash;
		m.write_token = m_token;
	}

	void timeout() {}
	void reply(msg const&) {}
	void abort() {}

private:
	sha1_hash m_info_hash;
	int m_listen_port;
	entry m_token;
};

class get_peers_observer : public observer
{
public:
	get_peers_observer(sha1_hash const& info_hash
		, int listen_port
		, rpc_manager& rpc
		, boost::function<void(std::vector<tcp::endpoint> const&, sha1_hash const&)> f)
		: observer(rpc.allocator())
		, m_info_hash(info_hash)
		, m_listen_port(listen_port)
		, m_rpc(rpc)
		, m_fun(f)
	{}

	void send(msg& m)
	{
		m.port = m_listen_port;
		m.info_hash = m_info_hash;
	}

	void timeout() {}
	void reply(msg const& r)
	{
		observer_ptr o(new (m_rpc.allocator().malloc()) announce_observer(
			m_rpc.allocator(), m_info_hash, m_listen_port, r.write_token));
#ifndef NDEBUG
		o->m_in_constructor = false;
#endif
		m_rpc.invoke(messages::announce_peer, r.addr, o);
		m_fun(r.peers, m_info_hash);
	}
	void abort() {}

private:
	sha1_hash m_info_hash;
	int m_listen_port;
	rpc_manager& m_rpc;
	boost::function<void(std::vector<tcp::endpoint> const&, sha1_hash const&)> m_fun;
};

class node_impl : boost::noncopyable
{
typedef std::map<node_id, torrent_entry> table_t;
public:
	node_impl(boost::function<void(msg const&)> const& f
		, dht_settings const& settings, boost::optional<node_id> node_id);

	virtual ~node_impl() {}

	void refresh(node_id const& id, boost::function0<void> f);
	void bootstrap(std::vector<udp::endpoint> const& nodes
		, boost::function0<void> f);
	void find_node(node_id const& id, boost::function<
	void(std::vector<node_entry> const&)> f);
	void add_router_node(udp::endpoint router);

	void incoming(msg const& m);

	void refresh();
	void refresh_bucket(int bucket);
	int bucket_size(int bucket);

	typedef routing_table::iterator iterator;

	iterator begin() const { return m_table.begin(); }
	iterator end() const { return m_table.end(); }

	typedef table_t::iterator data_iterator;

	node_id const& nid() const { return m_id; }
	boost::tuple<int, int> size() const{ return m_table.size(); }
	size_type num_global_nodes() const
	{ return m_table.num_global_nodes(); }

	data_iterator begin_data() { return m_map.begin(); }
	data_iterator end_data() { return m_map.end(); }
	int data_size() const { return int(m_map.size()); }

#ifdef TORRENT_DHT_VERBOSE_LOGGING
	void print_state(std::ostream& os) const
	{ m_table.print_state(os); }
#endif

	void announce(sha1_hash const& info_hash, int listen_port
		, boost::function<void(std::vector<tcp::endpoint> const&
			, sha1_hash const&)> f);

	bool verify_token(msg const& m);
	entry generate_token(msg const& m);

	// the returned time is the delay until connection_timeout()
	// should be called again the next time
	time_duration connection_timeout();
	time_duration refresh_timeout();

	// generates a new secret number used to generate write tokens
	void new_write_key();

	// pings the given node, and adds it to
	// the routing table if it respons and if the
	// bucket is not full.
	void add_node(udp::endpoint node);

	void replacement_cache(bucket_t& nodes) const
	{ m_table.replacement_cache(nodes); }

protected:
	// is called when a find data request is received. Should
	// return false if the data is not stored on this node. If
	// the data is stored, it should be serialized into 'data'.
	bool on_find(msg const& m, std::vector<tcp::endpoint>& peers) const;

	// this is called when a store request is received. The data
	// is store-parameters and the data to be stored.
	void on_announce(msg const& m, msg& reply);

	dht_settings const& m_settings;

	// the maximum number of peers to send in a get_peers
	// reply. Ordinary trackers usually limit this to 50.
	// 50 => 6 * 50 = 250 bytes + packet overhead
	int m_max_peers_reply;

private:
	void incoming_request(msg const& h);

	node_id m_id;
	routing_table m_table;
	rpc_manager m_rpc;
	table_t m_map;

	ptime m_last_tracker_tick;

	// secret random numbers used to create write tokens
	int m_secret[2];
};

} } // namespace libtorrent::dht

#endif // NODE_HPP

<|endoftext|>


<commit_before>
#include "luiText.h"

LUIText::LUIText(float x, float y) : LUIObject(x, y) {
  _text = "";
  _font_size = 100.0;
  set_font("default");
}

LUIText::LUIText(LUIObject *parent, float x, float y) : LUIObject(parent, x, y) {
  _text = "";
  _font_size = 100.0;
  set_font("default");
}

LUIText::LUIText(LUIObject *parent, const string &text, const string &font_name, float x, float y)
  : LUIObject(parent, x, y)  {
  _text = text;
  _font_size = 100.0;
  set_font(font_name);
}

LUIText::~LUIText() {

}

void LUIText::update_text() {
  int len = _text.size();

  nassertv(_font != NULL);

  if (lui_cat.is_spam()) {
    cout << "Current text is '" << _text.c_str() << "'" << endl;
  }

  // Remove all sprites which aren't required
  while (_sprites.size() > len) {
    if (lui_cat.is_spam()) {
      cout << "Removing sprite .. " << endl;
    }
    remove_sprite(*_sprites.begin());
  }

  // Allocate as many sprites as required
  int to_allocate  = len - _sprites.size();
  //cout << "Allocating " << to_allocate << " Sprites" << endl;
  for (int i = 0; i < to_allocate; i++) {
    attach_sprite((Texture*)NULL);
  }

  // Pixels per unit, used to convert betweeen coordinate spaces
  float ppu = _font_size;

  for (int i = 0; i < _glyphs.size(); i++) {
    _glyphs[i]->_geom_count --;
  }
  _glyphs.clear();

  float effective_line_height = ppu * _font->get_line_height();

  // Now iterate over the sprites
  pset<PT(LUISprite)>::iterator it;
  int i = 0;
  float current_x_pos = 0.0;

  for (it = _sprites.begin(); it != _sprites.end(); ++it, i++)
  {
    //cout << "Iteration #" << i << " .." << endl;
    LUISprite* sprite = *it;
    int char_code = (int)_text.at(i);

    const TextGlyph *const_glyph;
    if (!_font->get_glyph(char_code, const_glyph)) {
      sprite->set_texture((Texture*)NULL);
      lui_cat.error() << "Could not render character, skipping." << endl;
      continue;
    }

    TextGlyph *glyph = (TextGlyph*) const_glyph;

    PT(DynamicTextGlyph) dynamic_glyph = DCAST(DynamicTextGlyph, glyph);

    // If this gets executed, a non-dynamic font got loaded.
    nassertv(dynamic_glyph != NULL);

    _glyphs.push_back(dynamic_glyph);
    dynamic_glyph->_geom_count ++;

    //cout << "Render character " << char_code << ", top = " << dynamic_glyph->get_top() << ", bottom = " << dynamic_glyph->get_bottom() << ", l_h = " << _font->get_line_height() << endl;

    sprite->set_texture(dynamic_glyph->get_page());
    sprite->set_pos(
      current_x_pos + dynamic_glyph->get_left() * ppu,
      (-dynamic_glyph->get_top()) * ppu + _font->get_line_height() * ppu * 0.8);
    sprite->set_uv_range(
      dynamic_glyph->get_uv_left(),
      1-dynamic_glyph->get_uv_top(),
      dynamic_glyph->get_uv_right(),
      1-dynamic_glyph->get_uv_bottom());
    sprite->set_size(
       (dynamic_glyph->get_right() - dynamic_glyph->get_left()) * ppu,
       (dynamic_glyph->get_top() - dynamic_glyph->get_bottom()) * ppu);

    current_x_pos += dynamic_glyph->get_advance() * ppu;
  }

  set_size(current_x_pos, effective_line_height);

}<commit_msg>Smaller fixes<commit_after>
#include "luiText.h"

LUIText::LUIText(float x, float y) : LUIObject(x, y) {
  _text = "";
  _font_size = 100.0;
  set_font("default");
}

LUIText::LUIText(LUIObject *parent, float x, float y) : LUIObject(parent, x, y) {
  _text = "";
  _font_size = 100.0;
  set_font("default");
}

LUIText::LUIText(LUIObject *parent, const string &text, const string &font_name, float x, float y)
  : LUIObject(parent, x, y)  {
  _text = text;
  _font_size = 100.0;
  set_font(font_name);
}

LUIText::~LUIText() {

}

void LUIText::update_text() {
  int len = _text.size();

  nassertv(_font != NULL);

  if (lui_cat.is_spam()) {
    cout << "Current text is '" << _text.c_str() << "'" << endl;
  }

  // Remove all sprites which aren't required
  while (_sprites.size() > len) {
    if (lui_cat.is_spam()) {
      cout << "Removing sprite .. " << endl;
    }
    remove_sprite(*_sprites.begin());
  }

  // Allocate as many sprites as required
  int to_allocate  = len - _sprites.size();
  //cout << "Allocating " << to_allocate << " Sprites" << endl;
  for (int i = 0; i < to_allocate; i++) {
    attach_sprite((Texture*)NULL);
  }

  // Pixels per unit, used to convert betweeen coordinate spaces
  float ppu = _font_size;

  // Unreference all current glyphs
  for (int i = 0; i < _glyphs.size(); i++) {
    _glyphs[i]->_geom_count --;
  }
  _glyphs.clear();

  // Iterate over the sprites
  pset<PT(LUISprite)>::iterator it;
  int i = 0;
  float current_x_pos = 0.0;

  for (it = _sprites.begin(); it != _sprites.end(); ++it, i++)
  {
    LUISprite* sprite = *it;
    int char_code = (int)_text.at(i);

    const TextGlyph *const_glyph;
    if (!_font->get_glyph(char_code, const_glyph)) {
      sprite->set_texture((Texture*)NULL);
      lui_cat.error() << "Could not render character, skipping." << endl;
      continue;
    }

    TextGlyph *glyph = (TextGlyph*) const_glyph;

    PT(DynamicTextGlyph) dynamic_glyph = DCAST(DynamicTextGlyph, glyph);

    // If this gets executed, a non-dynamic font got loaded.
    nassertv(dynamic_glyph != NULL);

    _glyphs.push_back(dynamic_glyph);
    dynamic_glyph->_geom_count ++;

    // LUISprite has a check if the texture is the same, so if the atlas didn't
    // change, this is quite efficient.
    sprite->set_texture(dynamic_glyph->get_page());

    // Position the glyph.
    sprite->set_pos(
      current_x_pos + dynamic_glyph->get_left() * ppu,
      (_font->get_line_height() * 0.8 - dynamic_glyph->get_top()) * ppu);

    // The V coordinate is inverted, as panda stores the textures flipped
    sprite->set_uv_range(
      dynamic_glyph->get_uv_left(),
      1-dynamic_glyph->get_uv_top(),
      dynamic_glyph->get_uv_right(),
      1-dynamic_glyph->get_uv_bottom());

    // Determine size frm coordinates
    sprite->set_size(
       (dynamic_glyph->get_right() - dynamic_glyph->get_left()) * ppu,
       (dynamic_glyph->get_top() - dynamic_glyph->get_bottom()) * ppu);

    // Move *cursor* by glyph length
    current_x_pos += dynamic_glyph->get_advance() * ppu;
  }

  // Finally, set the size
  set_size(current_x_pos, _font_size);

}<|endoftext|>