<commit_before>/*     __ __              _
 *    / // /_____ ____   (_)
 *   / // // ___// __ \ / /
 *  / // // /__ / /_/ // /
 * /_//_/ \___/ \____//_/
 * https://bitbucket.org/galaktor/llcoi
 * copyright (c) 2011, llcoi Team
 * MIT license applies - see file "LICENSE" for details.
*/
#include "root_bind.h"

#include <OgreRoot.h>
#include <OgreRenderWindow.h>
#include <OgreWindowEventUtilities.h>
#include <OgreConfigFile.h>

RootHandle root_singleton()
{
  return reinterpret_cast<RootHandle>(Ogre::Root::getSingletonPtr());
}

RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName)
{
  Ogre::Root* root = new Ogre::Root(Ogre::String(pluginFileName), Ogre::String(configFileName), Ogre::String(logFileName));
  return reinterpret_cast<RootHandle>(root);
}

void delete_root(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  delete root;
}

RenderWindowHandle root_initialise(RootHandle root_handle, int auto_create_window, const char* render_window_title)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::RenderWindow* window = root->initialise(auto_create_window, render_window_title);
  return reinterpret_cast<RenderWindowHandle>(window);
}

RenderWindowHandle create_render_window(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen, NameValuePairListHandle params)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
    Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, reinterpret_cast<Ogre::NameValuePairList>(&params));
  return reinterpret_cast<RenderWindowHandle>(window);
}

RenderWindowHandle create_render_window_hwnd(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen, unsigned long hwnd)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::NameValuePairList misc;
  misc["parentWindowHandle"] = Ogre::StringConverter::toString(hwnd);
  Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, &misc);
  window->setActive(true);
  return reinterpret_cast<RenderWindowHandle>(window);
}

// Tell Ogre to use the current GL context.  This works on Linux/GLX but
// you *will* need something different on Windows or Mac.
RenderWindowHandle create_render_window_gl_context(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::NameValuePairList misc;
  misc["currentGLContext"] = Ogre::String("True");
  Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, &misc);
  return reinterpret_cast<RenderWindowHandle>(window);
}

int root_is_initialised(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->isInitialised())
    return 1;
  return 0;
}

void save_config(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  root->saveConfig();
}

int restore_config(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->restoreConfig())
    return 1;
  return 0;
}

int show_config_dialog(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->showConfigDialog())
    return 1;
  return 0;
}

void add_render_system(RootHandle root_handle, RenderSystemHandle render_system)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
  root->addRenderSystem(rs);
}

void set_render_system(RootHandle root_handle, RenderSystemHandle render_system)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
  root->setRenderSystem(rs);
}

RenderSystemHandle get_render_system(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  return reinterpret_cast<RenderSystemHandle>(root->getRenderSystem());
}

RenderSystemHandle get_render_system_by_name(RootHandle root_handle, const char* render_system_name)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::RenderSystem* rs = root->getRenderSystemByName(render_system_name);
  return reinterpret_cast<RenderSystemHandle>(rs);
}

void load_ogre_plugin(RootHandle root_handle, const char* plugin)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
#if defined( WIN32 ) || defined( _WINDOWS )
  Ogre::String pluginString(plugin);
#ifdef _DEBUG
  root->loadPlugin(pluginString + Ogre::String("_d"));
#else
  root->loadPlugin(plugin);
#endif
#else
  root->loadPlugin( Ogre::String(plugin));
#endif
}

int render_one_frame(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->renderOneFrame())
    return 1;
  return 0;
}

int render_one_frame_ex(RootHandle root_handle, float time_since_last_frame)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->renderOneFrame(time_since_last_frame))
    return 1;
  return 0;
}

SceneManagerHandle create_scene_manager(RootHandle root_handle, const char* type_name, const char* instance_name)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::SceneManager* sm = root->createSceneManager(Ogre::String(type_name), Ogre::String(instance_name));
  return reinterpret_cast<SceneManagerHandle>(sm);
}

SceneManagerHandle get_scene_manager_by_name(RootHandle root_handle, const char* scene_manager_instance_name)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::SceneManager* sm = root->getSceneManager(scene_manager_instance_name);
  return reinterpret_cast<SceneManagerHandle>(sm);
}

// Ogre::Root::getAvailableRenderers
RenderSystemListHandle root_get_available_renderers(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  const Ogre::RenderSystemList& rslist = root->getAvailableRenderers();
  Ogre::RenderSystemList *l = new Ogre::RenderSystemList(rslist);
  return reinterpret_cast<RenderSystemListHandle>(l);
}

SceneManagerHandle root_create_scene_manager_by_mask(RootHandle root_handle, SceneTypeMask type_mask, const char* instance_name)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::SceneManager* sm = root->createSceneManager(type_mask, Ogre::String(instance_name));
  return reinterpret_cast<SceneManagerHandle>(sm);
}

TimerHandle root_get_timer(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::Timer* timer = root->getTimer();
  return reinterpret_cast<TimerHandle>(timer);
}

/*
  Ogre::Root::~Root()
  Ogre::Root::saveConfig()
  Ogre::Root::addRenderSystem(Ogre::RenderSystem*)
  Ogre::Root::getRenderSystemByName(std::string const&)
  Ogre::Root::setRenderSystem(Ogre::RenderSystem*)
  Ogre::Root::getRenderSystem()
  Ogre::Root::useCustomRenderSystemCapabilities(Ogre::RenderSystemCapabilities*)
  Ogre::Root::getRemoveRenderQueueStructuresOnClear() const
  Ogre::Root::setRemoveRenderQueueStructuresOnClear(bool)
  Ogre::Root::addSceneManagerFactory(Ogre::SceneManagerFactory*)
  Ogre::Root::removeSceneManagerFactory(Ogre::SceneManagerFactory*)
  Ogre::Root::getSceneManagerMetaData(std::string const&) const
  Ogre::Root::getSceneManagerMetaDataIterator() const
  Ogre::Root::createSceneManager(std::string const&, std::string const&)
  Ogre::Root::createSceneManager(unsigned short, std::string const&)
  Ogre::Root::destroySceneManager(Ogre::SceneManager*)
  Ogre::Root::getSceneManager(std::string const&) const
  Ogre::Root::hasSceneManager(std::string const&) const
  Ogre::Root::getSceneManagerIterator()
  Ogre::Root::getTextureManager()
  Ogre::Root::getMeshManager()
  Ogre::Root::getErrorDescription(long)
  Ogre::Root::addFrameListener(Ogre::FrameListener*)
  Ogre::Root::removeFrameListener(Ogre::FrameListener*)
  Ogre::Root::queueEndRendering()
  Ogre::Root::startRendering()
  Ogre::Root::shutdown()
  Ogre::Root::addResourceLocation(std::string const&, std::string const&, std::string const&, bool)
  Ogre::Root::removeResourceLocation(std::string const&, std::string const&)
  Ogre::Root::createFileStream(std::string const&, std::string const&, bool, std::string const&)
  Ogre::Root::openFileStream(std::string const&, std::string const&, std::string const&)
  Ogre::Root::convertColourValue(Ogre::ColourValue const&, unsigned int*)
  Ogre::Root::getAutoCreatedWindow()
  Ogre::Root::createRenderWindow(std::string const&, unsigned int, unsigned int, bool, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const*)
  Ogre::Root::createRenderWindows(std::vector<Ogre::RenderWindowDescription, Ogre::STLAllocator<Ogre::RenderWindowDescription, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&, std::vector<Ogre::RenderWindow*, Ogre::STLAllocator<Ogre::RenderWindow*, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > >&)
  Ogre::Root::detachRenderTarget(Ogre::RenderTarget*)
  Ogre::Root::detachRenderTarget(std::string const&)
  Ogre::Root::getRenderTarget(std::string const&)
  Ogre::Root::unloadPlugin(std::string const&)
  Ogre::Root::installPlugin(Ogre::Plugin*)
  Ogre::Root::uninstallPlugin(Ogre::Plugin*)
  Ogre::Root::getInstalledPlugins() const
  Ogre::Root::getTimer()
  Ogre::Root::_fireFrameStarted(Ogre::FrameEvent&)
  Ogre::Root::_fireFrameRenderingQueued(Ogre::FrameEvent&)
  Ogre::Root::_fireFrameEnded(Ogre::FrameEvent&)
  Ogre::Root::_fireFrameStarted()
  Ogre::Root::_fireFrameRenderingQueued()
  Ogre::Root::_fireFrameEnded()
  Ogre::Root::getNextFrameNumber() const
  Ogre::Root::_getCurrentSceneManager() const
  Ogre::Root::_pushCurrentSceneManager(Ogre::SceneManager*)
  Ogre::Root::_popCurrentSceneManager(Ogre::SceneManager*)
  Ogre::Root::_updateAllRenderTargets()
  Ogre::Root::_updateAllRenderTargets(Ogre::FrameEvent&)
  Ogre::Root::createRenderQueueInvocationSequence(std::string const&)
  Ogre::Root::getRenderQueueInvocationSequence(std::string const&)
  Ogre::Root::destroyRenderQueueInvocationSequence(std::string const&)
  Ogre::Root::destroyAllRenderQueueInvocationSequences()
  Ogre::Root::getSingleton()
  Ogre::Root::getSingletonPtr()
  Ogre::Root::clearEventTimes()
  Ogre::Root::setFrameSmoothingPeriod(float)
  Ogre::Root::getFrameSmoothingPeriod() const
  Ogre::Root::addMovableObjectFactory(Ogre::MovableObjectFactory*, bool)
  Ogre::Root::removeMovableObjectFactory(Ogre::MovableObjectFactory*)
  Ogre::Root::hasMovableObjectFactory(std::string const&) const
  Ogre::Root::getMovableObjectFactory(std::string const&)
  Ogre::Root::_allocateNextMovableObjectTypeFlag()
  Ogre::Root::getMovableObjectFactoryIterator() const
  Ogre::Root::getDisplayMonitorCount() const
  Ogre::Root::getWorkQueue() const
  Ogre::Root::setWorkQueue(Ogre::WorkQueue*)
  Ogre::Root::setBlendIndicesGpuRedundant(bool)
  Ogre::Root::isBlendIndicesGpuRedundant() const
  Ogre::Root::setBlendWeightsGpuRedundant(bool)
  Ogre::Root::isBlendWeightsGpuRedundant() const
*/
<commit_msg>Correct pointer location.<commit_after>/*     __ __              _
 *    / // /_____ ____   (_)
 *   / // // ___// __ \ / /
 *  / // // /__ / /_/ // /
 * /_//_/ \___/ \____//_/
 * https://bitbucket.org/galaktor/llcoi
 * copyright (c) 2011, llcoi Team
 * MIT license applies - see file "LICENSE" for details.
*/
#include "root_bind.h"

#include <OgreRoot.h>
#include <OgreRenderWindow.h>
#include <OgreWindowEventUtilities.h>
#include <OgreConfigFile.h>

RootHandle root_singleton()
{
  return reinterpret_cast<RootHandle>(Ogre::Root::getSingletonPtr());
}

RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName)
{
  Ogre::Root* root = new Ogre::Root(Ogre::String(pluginFileName), Ogre::String(configFileName), Ogre::String(logFileName));
  return reinterpret_cast<RootHandle>(root);
}

void delete_root(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  delete root;
}

RenderWindowHandle root_initialise(RootHandle root_handle, int auto_create_window, const char* render_window_title)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::RenderWindow* window = root->initialise(auto_create_window, render_window_title);
  return reinterpret_cast<RenderWindowHandle>(window);
}

RenderWindowHandle create_render_window(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen, NameValuePairListHandle params)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
    Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, reinterpret_cast<Ogre::NameValuePairList*>(params));
  return reinterpret_cast<RenderWindowHandle>(window);
}

RenderWindowHandle create_render_window_hwnd(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen, unsigned long hwnd)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::NameValuePairList misc;
  misc["parentWindowHandle"] = Ogre::StringConverter::toString(hwnd);
  Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, &misc);
  window->setActive(true);
  return reinterpret_cast<RenderWindowHandle>(window);
}

// Tell Ogre to use the current GL context.  This works on Linux/GLX but
// you *will* need something different on Windows or Mac.
RenderWindowHandle create_render_window_gl_context(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::NameValuePairList misc;
  misc["currentGLContext"] = Ogre::String("True");
  Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, &misc);
  return reinterpret_cast<RenderWindowHandle>(window);
}

int root_is_initialised(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->isInitialised())
    return 1;
  return 0;
}

void save_config(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  root->saveConfig();
}

int restore_config(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->restoreConfig())
    return 1;
  return 0;
}

int show_config_dialog(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->showConfigDialog())
    return 1;
  return 0;
}

void add_render_system(RootHandle root_handle, RenderSystemHandle render_system)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
  root->addRenderSystem(rs);
}

void set_render_system(RootHandle root_handle, RenderSystemHandle render_system)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
  root->setRenderSystem(rs);
}

RenderSystemHandle get_render_system(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  return reinterpret_cast<RenderSystemHandle>(root->getRenderSystem());
}

RenderSystemHandle get_render_system_by_name(RootHandle root_handle, const char* render_system_name)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::RenderSystem* rs = root->getRenderSystemByName(render_system_name);
  return reinterpret_cast<RenderSystemHandle>(rs);
}

void load_ogre_plugin(RootHandle root_handle, const char* plugin)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
#if defined( WIN32 ) || defined( _WINDOWS )
  Ogre::String pluginString(plugin);
#ifdef _DEBUG
  root->loadPlugin(pluginString + Ogre::String("_d"));
#else
  root->loadPlugin(plugin);
#endif
#else
  root->loadPlugin( Ogre::String(plugin));
#endif
}

int render_one_frame(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->renderOneFrame())
    return 1;
  return 0;
}

int render_one_frame_ex(RootHandle root_handle, float time_since_last_frame)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  if(root->renderOneFrame(time_since_last_frame))
    return 1;
  return 0;
}

SceneManagerHandle create_scene_manager(RootHandle root_handle, const char* type_name, const char* instance_name)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::SceneManager* sm = root->createSceneManager(Ogre::String(type_name), Ogre::String(instance_name));
  return reinterpret_cast<SceneManagerHandle>(sm);
}

SceneManagerHandle get_scene_manager_by_name(RootHandle root_handle, const char* scene_manager_instance_name)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::SceneManager* sm = root->getSceneManager(scene_manager_instance_name);
  return reinterpret_cast<SceneManagerHandle>(sm);
}

// Ogre::Root::getAvailableRenderers
RenderSystemListHandle root_get_available_renderers(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  const Ogre::RenderSystemList& rslist = root->getAvailableRenderers();
  Ogre::RenderSystemList *l = new Ogre::RenderSystemList(rslist);
  return reinterpret_cast<RenderSystemListHandle>(l);
}

SceneManagerHandle root_create_scene_manager_by_mask(RootHandle root_handle, SceneTypeMask type_mask, const char* instance_name)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::SceneManager* sm = root->createSceneManager(type_mask, Ogre::String(instance_name));
  return reinterpret_cast<SceneManagerHandle>(sm);
}

TimerHandle root_get_timer(RootHandle root_handle)
{
  Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
  Ogre::Timer* timer = root->getTimer();
  return reinterpret_cast<TimerHandle>(timer);
}

/*
  Ogre::Root::~Root()
  Ogre::Root::saveConfig()
  Ogre::Root::addRenderSystem(Ogre::RenderSystem*)
  Ogre::Root::getRenderSystemByName(std::string const&)
  Ogre::Root::setRenderSystem(Ogre::RenderSystem*)
  Ogre::Root::getRenderSystem()
  Ogre::Root::useCustomRenderSystemCapabilities(Ogre::RenderSystemCapabilities*)
  Ogre::Root::getRemoveRenderQueueStructuresOnClear() const
  Ogre::Root::setRemoveRenderQueueStructuresOnClear(bool)
  Ogre::Root::addSceneManagerFactory(Ogre::SceneManagerFactory*)
  Ogre::Root::removeSceneManagerFactory(Ogre::SceneManagerFactory*)
  Ogre::Root::getSceneManagerMetaData(std::string const&) const
  Ogre::Root::getSceneManagerMetaDataIterator() const
  Ogre::Root::createSceneManager(std::string const&, std::string const&)
  Ogre::Root::createSceneManager(unsigned short, std::string const&)
  Ogre::Root::destroySceneManager(Ogre::SceneManager*)
  Ogre::Root::getSceneManager(std::string const&) const
  Ogre::Root::hasSceneManager(std::string const&) const
  Ogre::Root::getSceneManagerIterator()
  Ogre::Root::getTextureManager()
  Ogre::Root::getMeshManager()
  Ogre::Root::getErrorDescription(long)
  Ogre::Root::addFrameListener(Ogre::FrameListener*)
  Ogre::Root::removeFrameListener(Ogre::FrameListener*)
  Ogre::Root::queueEndRendering()
  Ogre::Root::startRendering()
  Ogre::Root::shutdown()
  Ogre::Root::addResourceLocation(std::string const&, std::string const&, std::string const&, bool)
  Ogre::Root::removeResourceLocation(std::string const&, std::string const&)
  Ogre::Root::createFileStream(std::string const&, std::string const&, bool, std::string const&)
  Ogre::Root::openFileStream(std::string const&, std::string const&, std::string const&)
  Ogre::Root::convertColourValue(Ogre::ColourValue const&, unsigned int*)
  Ogre::Root::getAutoCreatedWindow()
  Ogre::Root::createRenderWindow(std::string const&, unsigned int, unsigned int, bool, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const*)
  Ogre::Root::createRenderWindows(std::vector<Ogre::RenderWindowDescription, Ogre::STLAllocator<Ogre::RenderWindowDescription, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&, std::vector<Ogre::RenderWindow*, Ogre::STLAllocator<Ogre::RenderWindow*, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > >&)
  Ogre::Root::detachRenderTarget(Ogre::RenderTarget*)
  Ogre::Root::detachRenderTarget(std::string const&)
  Ogre::Root::getRenderTarget(std::string const&)
  Ogre::Root::unloadPlugin(std::string const&)
  Ogre::Root::installPlugin(Ogre::Plugin*)
  Ogre::Root::uninstallPlugin(Ogre::Plugin*)
  Ogre::Root::getInstalledPlugins() const
  Ogre::Root::getTimer()
  Ogre::Root::_fireFrameStarted(Ogre::FrameEvent&)
  Ogre::Root::_fireFrameRenderingQueued(Ogre::FrameEvent&)
  Ogre::Root::_fireFrameEnded(Ogre::FrameEvent&)
  Ogre::Root::_fireFrameStarted()
  Ogre::Root::_fireFrameRenderingQueued()
  Ogre::Root::_fireFrameEnded()
  Ogre::Root::getNextFrameNumber() const
  Ogre::Root::_getCurrentSceneManager() const
  Ogre::Root::_pushCurrentSceneManager(Ogre::SceneManager*)
  Ogre::Root::_popCurrentSceneManager(Ogre::SceneManager*)
  Ogre::Root::_updateAllRenderTargets()
  Ogre::Root::_updateAllRenderTargets(Ogre::FrameEvent&)
  Ogre::Root::createRenderQueueInvocationSequence(std::string const&)
  Ogre::Root::getRenderQueueInvocationSequence(std::string const&)
  Ogre::Root::destroyRenderQueueInvocationSequence(std::string const&)
  Ogre::Root::destroyAllRenderQueueInvocationSequences()
  Ogre::Root::getSingleton()
  Ogre::Root::getSingletonPtr()
  Ogre::Root::clearEventTimes()
  Ogre::Root::setFrameSmoothingPeriod(float)
  Ogre::Root::getFrameSmoothingPeriod() const
  Ogre::Root::addMovableObjectFactory(Ogre::MovableObjectFactory*, bool)
  Ogre::Root::removeMovableObjectFactory(Ogre::MovableObjectFactory*)
  Ogre::Root::hasMovableObjectFactory(std::string const&) const
  Ogre::Root::getMovableObjectFactory(std::string const&)
  Ogre::Root::_allocateNextMovableObjectTypeFlag()
  Ogre::Root::getMovableObjectFactoryIterator() const
  Ogre::Root::getDisplayMonitorCount() const
  Ogre::Root::getWorkQueue() const
  Ogre::Root::setWorkQueue(Ogre::WorkQueue*)
  Ogre::Root::setBlendIndicesGpuRedundant(bool)
  Ogre::Root::isBlendIndicesGpuRedundant() const
  Ogre::Root::setBlendWeightsGpuRedundant(bool)
  Ogre::Root::isBlendWeightsGpuRedundant() const
*/
<|endoftext|>


<commit_before>/*
  LED bar library V2.0
  2010 Copyright (c) Seeed Technology Inc.  All right reserved.

  Original Author: LG

  Modify: Loovee, 2014-2-26
  User can choose which Io to be used.

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

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

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <Arduino.h>
#include "Grove_LED_Bar.h"

Grove_LED_Bar::Grove_LED_Bar(unsigned char pinClock, unsigned char pinData, bool greenToRed)
{
  __pinClock = pinClock;
  __pinData = pinData;
  __greenToRed = greenToRed;  // ascending or decending

  __state = 0x00;  // persist state so individual leds can be toggled

  pinMode(__pinClock, OUTPUT);
  pinMode(__pinData, OUTPUT);
}

// Send the latch command
void Grove_LED_Bar::latchData()
{
  digitalWrite(__pinData, LOW);
  delayMicroseconds(10);

  for (unsigned char i = 0; i < 4; i++)
  {
    digitalWrite(__pinData, HIGH);
    digitalWrite(__pinData, LOW);
  }
}

// Send 16 bits of data
void Grove_LED_Bar::sendData(unsigned int data)
{
  for (unsigned char i = 0; i < 16; i++)
  {
    unsigned int state = (data & 0x8000) ? HIGH : LOW;
    digitalWrite(__pinData, state);

    state = digitalRead(__pinClock) ? LOW : HIGH;
    digitalWrite(__pinClock, state);

    data <<= 1;
  }
}

// Change the orientation
// Green to red, or red to green
void Grove_LED_Bar::setGreenToRed(bool greenToRed)
{
  __greenToRed = greenToRed;

  setBits(__state);
}

// Set level (0-10)
// Level 0 means all leds off
// Level 10 means all leds on
void Grove_LED_Bar::setLevel(unsigned char level)
{
  level = max(0, min(10, level));

  // Set level number of bits from the left to 1
  __state = ~(~0 << level);

  setBits(__state);
}

// Set a single led
// led (1-10)
// state (0=off, 1=on)
void Grove_LED_Bar::setLed(unsigned char led, bool state)
{
  led = max(1, min(10, led));

  // Zero based index 0-9 for bitwise operations
  led--;

  // Bitwise OR or bitwise AND
  __state = state ? (__state | (0x01<<led)) : (__state & ~(0x01<<led));

  setBits(__state);
}

// Toggle a single led
// led (1-10)
void Grove_LED_Bar::toggleLed(unsigned char led)
{
  led = max(1, min(10, led));

  // Zero based index 0-9 for bitwise operations
  led--;

  // Bitwise XOR the leds current value
  __state ^= (0x01<<led);

  setBits(__state);
}

// Set the current state, one bit for each led
// 0    = 0x0   = 0b000000000000000 = all leds off
// 5    = 0x05  = 0b000000000000101 = leds 1 and 3 on, all others off
// 341  = 0x155 = 0b000000101010101 = leds 1,3,5,7,9 on, 2,4,6,8,10 off
// 1023 = 0x3ff = 0b000001111111111 = all leds on
//                       |        |
//                       10       1
void Grove_LED_Bar::setBits(unsigned int bits)
{
  sendData(CMDMODE);

  for (unsigned char i = 0; i < 10; i++)
  {
    if (__greenToRed)
    {
      // Bitwise AND the 10th bit (0x200) and left shift to cycle through all bits
      sendData((bits << i) & 0x200 ? ON : OFF);
    }
    else
    {
      // Bitwise AND the 1st bit (0x01) and right shift to cycle through all bits
      sendData((bits >> i) & 0x01 ? ON : OFF);
    }
  }

  // Two extra empty bits for padding the command to the correct length
  sendData(0x00);
  sendData(0x00);

  latchData();
}

// Return the current state
unsigned int Grove_LED_Bar::getBits()
{
  return __state;
}
<commit_msg>Update Grove_LED_Bar.cpp<commit_after>/*
  LED bar library V2.0
  2010 Copyright (c) Seeed Technology Inc.  All right reserved.

  Original Author: LG

  Modify: Loovee, 2014-2-26
  User can choose which Io to be used.

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

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

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

//#include <Arduino.h>
#include "Grove_LED_Bar.h"

Grove_LED_Bar::Grove_LED_Bar(unsigned char pinClock, unsigned char pinData, bool greenToRed)
{
  __pinClock = pinClock;
  __pinData = pinData;
  __greenToRed = greenToRed;  // ascending or decending

  __state = 0x00;  // persist state so individual leds can be toggled

  pinMode(__pinClock, OUTPUT);
  pinMode(__pinData, OUTPUT);
}

// Send the latch command
void Grove_LED_Bar::latchData()
{
  digitalWrite(__pinData, LOW);
  delayMicroseconds(10);

  for (unsigned char i = 0; i < 4; i++)
  {
    digitalWrite(__pinData, HIGH);
    digitalWrite(__pinData, LOW);
  }
}

// Send 16 bits of data
void Grove_LED_Bar::sendData(unsigned int data)
{
  for (unsigned char i = 0; i < 16; i++)
  {
    unsigned int state = (data & 0x8000) ? HIGH : LOW;
    digitalWrite(__pinData, state);

    state = digitalRead(__pinClock) ? LOW : HIGH;
    digitalWrite(__pinClock, state);

    data <<= 1;
  }
}

// Change the orientation
// Green to red, or red to green
void Grove_LED_Bar::setGreenToRed(bool greenToRed)
{
  __greenToRed = greenToRed;

  setBits(__state);
}

// Set level (0-10)
// Level 0 means all leds off
// Level 10 means all leds on
void Grove_LED_Bar::setLevel(unsigned char level)
{
  level = max(0, min(10, level));

  // Set level number of bits from the left to 1
  __state = ~(~0 << level);

  setBits(__state);
}

// Set a single led
// led (1-10)
// state (0=off, 1=on)
void Grove_LED_Bar::setLed(unsigned char led, bool state)
{
  led = max(1, min(10, led));

  // Zero based index 0-9 for bitwise operations
  led--;

  // Bitwise OR or bitwise AND
  __state = state ? (__state | (0x01<<led)) : (__state & ~(0x01<<led));

  setBits(__state);
}

// Toggle a single led
// led (1-10)
void Grove_LED_Bar::toggleLed(unsigned char led)
{
  led = max(1, min(10, led));

  // Zero based index 0-9 for bitwise operations
  led--;

  // Bitwise XOR the leds current value
  __state ^= (0x01<<led);

  setBits(__state);
}

// Set the current state, one bit for each led
// 0    = 0x0   = 0b000000000000000 = all leds off
// 5    = 0x05  = 0b000000000000101 = leds 1 and 3 on, all others off
// 341  = 0x155 = 0b000000101010101 = leds 1,3,5,7,9 on, 2,4,6,8,10 off
// 1023 = 0x3ff = 0b000001111111111 = all leds on
//                       |        |
//                       10       1
void Grove_LED_Bar::setBits(unsigned int bits)
{
  sendData(CMDMODE);

  for (unsigned char i = 0; i < 10; i++)
  {
    if (__greenToRed)
    {
      // Bitwise AND the 10th bit (0x200) and left shift to cycle through all bits
      sendData((bits << i) & 0x200 ? ON : OFF);
    }
    else
    {
      // Bitwise AND the 1st bit (0x01) and right shift to cycle through all bits
      sendData((bits >> i) & 0x01 ? ON : OFF);
    }
  }

  // Two extra empty bits for padding the command to the correct length
  sendData(0x00);
  sendData(0x00);

  latchData();
}

// Return the current state
unsigned int Grove_LED_Bar::getBits()
{
  return __state;
}
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */
#ifndef NTA_YAML_HPP
#define NTA_YAML_HPP

#include <nupic/types/Types.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/Collection.hpp>
#include <nupic/engine/Spec.hpp>

namespace nupic
{

  namespace YAMLUtils
  {
    /*
     * For converting param specs for Regions and LinkPolicies
     */
    ValueMap toValueMap(
      const char* yamlstring,
      Collection<ParameterSpec>& parameters,
      const std::string & nodeType = "",
      const std::string & regionName = ""
      );

  } // namespace YAMLUtils
} // namespace nupic

#endif //  NTA_YAML_HPP

<commit_msg>Revert "YAML Utils: remove toValue() from public API"<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */
#ifndef NTA_YAML_HPP
#define NTA_YAML_HPP

#include <nupic/types/Types.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/Collection.hpp>
#include <nupic/engine/Spec.hpp>

namespace nupic
{

  namespace YAMLUtils
  {
    /*
     * For converting default values
     */
    Value toValue(const std::string& yamlstring, NTA_BasicType dataType);

    /*
     * For converting param specs for Regions and LinkPolicies
     */
    ValueMap toValueMap(
      const char* yamlstring,
      Collection<ParameterSpec>& parameters,
      const std::string & nodeType = "",
      const std::string & regionName = ""
      );

  } // namespace YAMLUtils
} // namespace nupic

#endif //  NTA_YAML_HPP

<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */
#ifndef NTA_YAML_HPP
#define NTA_YAML_HPP

#include <nupic/types/Types.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/Collection.hpp>
#include <nupic/engine/Spec.hpp>

namespace nupic
{

  namespace YAMLUtils
  {
    /*
     * For converting default values
     */
    Value toValue(const std::string& yamlstring, NTA_BasicType dataType);

    /*
     * For converting param specs for Regions and LinkPolicies
     */
    ValueMap toValueMap(
      const char* yamlstring,
      Collection<ParameterSpec>& parameters,
      const std::string & nodeType = "",
      const std::string & regionName = ""
      );

  } // namespace YAMLUtils
} // namespace nupic

#endif //  NTA_YAML_HPP

<commit_msg>YAML Utils: remove toValue() from public API<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */
#ifndef NTA_YAML_HPP
#define NTA_YAML_HPP

#include <nupic/types/Types.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/Collection.hpp>
#include <nupic/engine/Spec.hpp>

namespace nupic
{

  namespace YAMLUtils
  {
    /*
     * For converting param specs for Regions and LinkPolicies
     */
    ValueMap toValueMap(
      const char* yamlstring,
      Collection<ParameterSpec>& parameters,
      const std::string & nodeType = "",
      const std::string & regionName = ""
      );

  } // namespace YAMLUtils
} // namespace nupic

#endif //  NTA_YAML_HPP

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: formatclipboard.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 04:30:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "formatclipboard.hxx"

#ifndef _E3D_GLOBL3D_HXX
#include <svx/globl3d.hxx>
#endif

// header for class SfxItemIter
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif

// header for class SfxStyleSheet
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif

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

SdFormatClipboard::SdFormatClipboard()
        : m_pItemSet(0)
        , m_bPersistentCopy(false)
        , m_nType_Inventor(0)
        , m_nType_Identifier(0)
{
}
SdFormatClipboard::~SdFormatClipboard()
{
    if(m_pItemSet)
        delete m_pItemSet;
}

bool SdFormatClipboard::HasContent() const
{
    return m_pItemSet!=0;
}

bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor )
        return false;
    switch(nObjectIdentifier)
    {
        case OBJ_NONE:
        case OBJ_GRUP:
            return false;
            break;
        case OBJ_LINE:
        case OBJ_RECT:
        case OBJ_CIRC:
        case OBJ_SECT:
        case OBJ_CARC:
        case OBJ_CCUT:
        case OBJ_POLY:
        case OBJ_PLIN:
        case OBJ_PATHLINE:
        case OBJ_PATHFILL:
        case OBJ_FREELINE:
        case OBJ_FREEFILL:
        case OBJ_SPLNLINE:
        case OBJ_SPLNFILL:
        case OBJ_TEXT:
        case OBJ_TEXTEXT:
        case OBJ_TITLETEXT:
            return true;
            break;
        case OBJ_OUTLINETEXT:
        case OBJ_GRAF:
        case OBJ_OLE2:
        case OBJ_EDGE:
        case OBJ_CAPTION:
            return false;
            break;
        case OBJ_PATHPOLY:
        case OBJ_PATHPLIN:
            return true;
            break;
        case OBJ_PAGE:
        case OBJ_MEASURE:
        case OBJ_DUMMY:
        case OBJ_FRAME:
        case OBJ_UNO:
            return false;
            break;
        case OBJ_CUSTOMSHAPE:
            return true;
            break;
        default:
            return false;
            break;
    }
    return true;
}

bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( !HasContent() )
        return false;
    if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) )
        return false;
    return true;
}

void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy )
{
    this->Erase();
    m_bPersistentCopy = bPersistentCopy;

    const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
    if( rMarkList.GetMarkCount() >= 1 )
    {
        BOOL bOnlyHardAttr = FALSE;
        m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) );

        SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
        m_nType_Inventor = pObj->GetObjInventor();
        m_nType_Identifier = pObj->GetObjIdentifier();
    }
}

void SdFormatClipboard::Paste( ::sd::View& rDrawView
                              , bool bNoCharacterFormats, bool bNoParagraphFormats )
{
    if( !rDrawView.AreObjectsMarked() )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }

    SdrObject* pObj = 0;

    bool bWrongTargetType = false;
    {
        const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
        if( rMarkList.GetMarkCount() != 1 )
            bWrongTargetType = true;
        else
        {
            pObj = rMarkList.GetMark(0)->GetObj();
            if( pObj && pObj->GetStyleSheet() )
                bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() );
        }
    }
    if( bWrongTargetType )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }
    if(m_pItemSet)
    {
        //modify source itemset
        {
            BOOL bOnlyHardAttr = FALSE;
            SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() );

            USHORT nWhich=0;
            SfxItemState nSourceState;
            SfxItemState nTargetState;
            const SfxPoolItem* pSourceItem=0;
            const SfxPoolItem* pTargetItem=0;
            SfxItemIter aSourceIter(*m_pItemSet);
            pSourceItem = aSourceIter.FirstItem();
            while( pSourceItem!=NULL )
            {
                if (!IsInvalidItem(pSourceItem))
                {
                    nWhich = pSourceItem->Which();
                    if(nWhich)
                    {
                        nSourceState = m_pItemSet->GetItemState( nWhich );
                        nTargetState = aTargetSet.GetItemState( nWhich );
                        pTargetItem = aTargetSet.GetItem( nWhich );
                        ::com::sun::star::uno::Any aSourceValue, aTargetValue;

                        if(!pTargetItem)
                            m_pItemSet->ClearItem(nWhich);
                        else if( (*pSourceItem) == (*pTargetItem) )
                        {
                            //do not set items which have the same content in source and target
                            m_pItemSet->ClearItem(nWhich);
                        }
                    }
                }
                pSourceItem = aSourceIter.NextItem();
            }//end while
        }
        BOOL bReplaceAll = TRUE;
        rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll);
    }
    if(!m_bPersistentCopy)
        this->Erase();
}

void SdFormatClipboard::Erase()
{
    if(m_pItemSet)
    {
        delete m_pItemSet;
        m_pItemSet = 0;
    }
    m_nType_Inventor=0;
    m_nType_Identifier=0;
    m_bPersistentCopy = false;
}
<commit_msg>INTEGRATION: CWS aw035 (1.5.252); FILE MERGED 2006/07/13 16:05:12 aw 1.5.252.1: #126320# SdrMark::GetObj() -> SdrMark::GetMarkedSdrObj() for isolating selection handling<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: formatclipboard.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2006-07-25 11:31:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "formatclipboard.hxx"

#ifndef _E3D_GLOBL3D_HXX
#include <svx/globl3d.hxx>
#endif

// header for class SfxItemIter
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif

// header for class SfxStyleSheet
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif

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

SdFormatClipboard::SdFormatClipboard()
        : m_pItemSet(0)
        , m_bPersistentCopy(false)
        , m_nType_Inventor(0)
        , m_nType_Identifier(0)
{
}
SdFormatClipboard::~SdFormatClipboard()
{
    if(m_pItemSet)
        delete m_pItemSet;
}

bool SdFormatClipboard::HasContent() const
{
    return m_pItemSet!=0;
}

bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor )
        return false;
    switch(nObjectIdentifier)
    {
        case OBJ_NONE:
        case OBJ_GRUP:
            return false;
            break;
        case OBJ_LINE:
        case OBJ_RECT:
        case OBJ_CIRC:
        case OBJ_SECT:
        case OBJ_CARC:
        case OBJ_CCUT:
        case OBJ_POLY:
        case OBJ_PLIN:
        case OBJ_PATHLINE:
        case OBJ_PATHFILL:
        case OBJ_FREELINE:
        case OBJ_FREEFILL:
        case OBJ_SPLNLINE:
        case OBJ_SPLNFILL:
        case OBJ_TEXT:
        case OBJ_TEXTEXT:
        case OBJ_TITLETEXT:
            return true;
            break;
        case OBJ_OUTLINETEXT:
        case OBJ_GRAF:
        case OBJ_OLE2:
        case OBJ_EDGE:
        case OBJ_CAPTION:
            return false;
            break;
        case OBJ_PATHPOLY:
        case OBJ_PATHPLIN:
            return true;
            break;
        case OBJ_PAGE:
        case OBJ_MEASURE:
        case OBJ_DUMMY:
        case OBJ_FRAME:
        case OBJ_UNO:
            return false;
            break;
        case OBJ_CUSTOMSHAPE:
            return true;
            break;
        default:
            return false;
            break;
    }
    return true;
}

bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( !HasContent() )
        return false;
    if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) )
        return false;
    return true;
}

void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy )
{
    this->Erase();
    m_bPersistentCopy = bPersistentCopy;

    const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
    if( rMarkList.GetMarkCount() >= 1 )
    {
        BOOL bOnlyHardAttr = FALSE;
        m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) );

        SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
        m_nType_Inventor = pObj->GetObjInventor();
        m_nType_Identifier = pObj->GetObjIdentifier();
    }
}

void SdFormatClipboard::Paste( ::sd::View& rDrawView
                              , bool bNoCharacterFormats, bool bNoParagraphFormats )
{
    if( !rDrawView.AreObjectsMarked() )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }

    SdrObject* pObj = 0;

    bool bWrongTargetType = false;
    {
        const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
        if( rMarkList.GetMarkCount() != 1 )
            bWrongTargetType = true;
        else
        {
            pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
            if( pObj && pObj->GetStyleSheet() )
                bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() );
        }
    }
    if( bWrongTargetType )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }
    if(m_pItemSet)
    {
        //modify source itemset
        {
            BOOL bOnlyHardAttr = FALSE;
            SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() );

            USHORT nWhich=0;
            SfxItemState nSourceState;
            SfxItemState nTargetState;
            const SfxPoolItem* pSourceItem=0;
            const SfxPoolItem* pTargetItem=0;
            SfxItemIter aSourceIter(*m_pItemSet);
            pSourceItem = aSourceIter.FirstItem();
            while( pSourceItem!=NULL )
            {
                if (!IsInvalidItem(pSourceItem))
                {
                    nWhich = pSourceItem->Which();
                    if(nWhich)
                    {
                        nSourceState = m_pItemSet->GetItemState( nWhich );
                        nTargetState = aTargetSet.GetItemState( nWhich );
                        pTargetItem = aTargetSet.GetItem( nWhich );
                        ::com::sun::star::uno::Any aSourceValue, aTargetValue;

                        if(!pTargetItem)
                            m_pItemSet->ClearItem(nWhich);
                        else if( (*pSourceItem) == (*pTargetItem) )
                        {
                            //do not set items which have the same content in source and target
                            m_pItemSet->ClearItem(nWhich);
                        }
                    }
                }
                pSourceItem = aSourceIter.NextItem();
            }//end while
        }
        BOOL bReplaceAll = TRUE;
        rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll);
    }
    if(!m_bPersistentCopy)
        this->Erase();
}

void SdFormatClipboard::Erase()
{
    if(m_pItemSet)
    {
        delete m_pItemSet;
        m_pItemSet = 0;
    }
    m_nType_Inventor=0;
    m_nType_Identifier=0;
    m_bPersistentCopy = false;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================

#include <iostream>
#include <cassert>

#include "Litteral.hpp"

#include "StringPool.hpp"
#include "AssemblyFileWriter.hpp"
#include "Variable.hpp"

#include "il/IntermediateProgram.hpp"
#include "il/Operands.hpp"

using namespace eddic;

void Litteral::checkStrings(StringPool& pool) {
    m_label = pool.label(m_litteral);
}

void Litteral::write(AssemblyFileWriter& writer) {
    writer.stream() << "pushl $" << getStringLabel() << std::endl;
    writer.stream() << "pushl $" << getStringSize() << std::endl;
}

bool Litteral::isConstant() {
    return true;
}

std::string Litteral::getStringValue() {
    return m_litteral;
}

std::string Litteral::getStringLabel(){
    return m_label;
}

int Litteral::getStringSize(){
    return m_litteral.size() - 2;
}

void Litteral::assignTo(std::shared_ptr<Variable> variable, IntermediateProgram& program){
    std::pair<std::shared_ptr<Operand>, std::shared_ptr<Operand>> operands = variable->toStringOperand();

    program.addInstruction(
        program.factory().createMove(
            createGlobalOperand(getStringLabel()),
            operands.first
        )
    );

    program.addInstruction(
        program.factory().createMove(
            createImmediateOperand(getStringSize()),
            operands.second
        )
    );
}

void Litteral::assignTo(std::shared_ptr<Operand>, IntermediateProgram&){
    assert(false); //Cannot assign a string to a single operand
}

void Litteral::push(IntermediateProgram& program){
    //TODO Verify that it is corresponding to pushl $label
    program.addInstruction(
        program.factory().createPush(
            createGlobalOperand(getStringLabel())
        )
    );

    program.addInstruction(
        program.factory().createPush(
            createImmediateOperand(getStringSize())
        )
    );
}
<commit_msg>Use immediate operands for strings<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================

#include <iostream>
#include <cassert>

#include "Litteral.hpp"

#include "StringPool.hpp"
#include "AssemblyFileWriter.hpp"
#include "Variable.hpp"

#include "il/IntermediateProgram.hpp"
#include "il/Operands.hpp"

using namespace eddic;

void Litteral::checkStrings(StringPool& pool) {
    m_label = pool.label(m_litteral);
}

void Litteral::write(AssemblyFileWriter& writer) {
    writer.stream() << "pushl $" << getStringLabel() << std::endl;
    writer.stream() << "pushl $" << getStringSize() << std::endl;
}

bool Litteral::isConstant() {
    return true;
}

std::string Litteral::getStringValue() {
    return m_litteral;
}

std::string Litteral::getStringLabel(){
    return m_label;
}

int Litteral::getStringSize(){
    return m_litteral.size() - 2;
}

void Litteral::assignTo(std::shared_ptr<Variable> variable, IntermediateProgram& program){
    std::pair<std::shared_ptr<Operand>, std::shared_ptr<Operand>> operands = variable->toStringOperand();

    program.addInstruction(
        program.factory().createMove(
            createImmediateOperand(getStringLabel()),
            operands.first
        )
    );

    program.addInstruction(
        program.factory().createMove(
            createImmediateOperand(getStringSize()),
            operands.second
        )
    );
}

void Litteral::assignTo(std::shared_ptr<Operand>, IntermediateProgram&){
    assert(false); //Cannot assign a string to a single operand
}

void Litteral::push(IntermediateProgram& program){
    //TODO Verify that it is corresponding to pushl $label
    program.addInstruction(
        program.factory().createPush(
            createImmediateOperand(getStringLabel())
        )
    );

    program.addInstruction(
        program.factory().createPush(
            createImmediateOperand(getStringSize())
        )
    );
}
<|endoftext|>


<commit_before>/*
 FILNAMN: 		NetClient.cc
 PROGRAMMERARE:	hanel742, eriek984, jened502, tobgr602, niker917, davha227
 SKAPAD DATUM:	2013-11-19
 BESKRIVNING:
 */

#include "NetClient.h"
#include "../gui/gui.h"

using namespace std;

NetClient::NetClient(QString username, QString inAddress, Gui* myGui, QObject *parent) : QObject(parent){

    guiPointer = myGui;
    name=username;
    address=inAddress;
    compare += 0x1F;
    breaker +=0x1E;
}

// ---------------------------------------------

void NetClient::start(){
    TcpSocket = new QTcpSocket(this);

    connect(TcpSocket,SIGNAL(connected()),this,SLOT(connected()));
    connect(TcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected()));
    connect(TcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead()));

    QHostInfo info = QHostInfo::fromName(address);

    if (info.addresses().size() == 0){
        guiPointer->noConnection();
    }
    else{
        TcpSocket->connectToHost(info.addresses().at(0),quint16(40001));
        if(!TcpSocket->waitForConnected(1000)){
            guiPointer->noConnection();
        }
    }
}

//------Slots---------

void NetClient::connected(){
    QByteArray array = "/initiate";
    array += 0x1F; //unit separator
    array += name;
    array += breaker;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

void NetClient::disconnected(){
    guiPointer->disconnectedFromServer();

}

// --------readyRead------------------

void NetClient::readyRead(){

    QByteArray Data = TcpSocket->readAll();

    QString commandName;
    QString inData = Data;
    QString rest;
    int n = inData.indexOf(breaker);
    int i;

    do {
        rest = inData.mid(n+1);
        inData = inData.left(n);
        i = inData.indexOf(compare);

        commandName = inData.left(i);

        inData = inData.mid(i+1);

        QString temp = inData;
        string stdInData = temp.toStdString();

        // Check which command that's supposed to run
        if (commandName == "/reinitiate") {
            guiPointer->userNameTaken();
            break;
        }

        else if ( commandName == "/userAccepted") {
            guiPointer->connected();
        }

        else if (commandName == "/history") {
            handleHistory(inData);
        }

        else if (commandName == "/oldHistory") {
            handleOldHistory(inData);
        }

        else if (commandName == "/message") {
            handleMessage(inData);
        }

        else if ( commandName == "/requestStruct") {
            handleRequestStruct();
        }

        else if ( commandName == "/structure" ) {
            handleStructure(inData);
        }

        else {
            throw logic_error("Unknown command: " + commandName.toStdString());
        }

        inData = rest;
        n = inData.indexOf(breaker);

    }while (n != -1 );
}

// ---------------------------------------------

void NetClient::sendMessage(QString from, QString to, QString message){
    QByteArray array = "/message";
    array += 0x1F; //unit separator
    array += from;
    array += 0x1F;
    array += to;
    array += 0x1F;
    array += message;
    array += breaker;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

void NetClient::setName(QString inName) {
    name=inName;
}

void NetClient::getStruct(){
    QByteArray array = "/structure";
    array += 0x1E;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

//--------------------------------------------
//Helpfunctions

void NetClient::handleRequestStruct(){
    QByteArray array = "/structure";
    array += compare;
    array += breaker;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

// ---------------------------------------------

void NetClient::handleMessage(QString inData){

    int i;
    // Get from
    i = inData.indexOf(compare);
    QString from = inData.left(i);
    inData = inData.mid(i+1);

    // Get to
    i = inData.indexOf(compare);
    QString to = inData.left(i);
    inData = inData.mid(i+1);

    // Get message
    i = inData.indexOf(compare);
    QString contents = inData.left(i);
    inData = inData.mid(i+1);

    // Get time
    QString dateTime = inData;

    //Send message to Gui
    guiPointer->receiveMessage(from, to, contents, dateTime);

}

// ---------------------------------------------

void NetClient::handleHistory(QString inData){
    QVector<QString> history;
    int i = inData.indexOf(compare);
    while(i != -1 ){

        // Get from
        i = inData.indexOf(compare);
        QString from = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(from);

        // Get to
        i = inData.indexOf(compare);
        QString to = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(to);

        // Get message
        i = inData.indexOf(compare);
        QString contents = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(contents);

        //Get time
        i = inData.indexOf(compare);
        QString time = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(time);
    }
    guiPointer->receiveHistory(history);
}

// ---------------------------------------------

void NetClient::handleOldHistory(QString inData){
    QVector<QString> history;
    int i = inData.indexOf(compare);
    while(i != -1 ){

        // Get from
        i = inData.indexOf(compare);
        QString from = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(from);

        // Get to
        i = inData.indexOf(compare);
        QString to = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(to);

        // Get message
        i = inData.indexOf(compare);
        QString contents = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(contents);

        //Get time
        i = inData.indexOf(compare);
        QString time = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(time);
    }
    guiPointer->receiveOldHistory(history);
}

// ---------------------------------------------

void NetClient::handleStructure(QString inData){
    QVector<QString> output;
    int i = inData.indexOf(compare);

    while(i  != -1){
        //Create vector output, containing room content structure
        QString data = inData.left(i);
        inData = inData.mid(i+1);
        output.push_back(data);

        i = inData.indexOf(compare);
    }

    output.push_back(inData);

    guiPointer->updateStruct(output);

}

// ---------------------------------------------

void NetClient::getHistory(unsigned int daysBack) {
    QString temp;
    string daysBackString = to_string(daysBack);

    temp = QString::fromStdString(daysBackString);

    QByteArray array = "/oldHistory";
    array += compare; //unit separator
    array += temp;
    array += breaker;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

<commit_msg>Lacking default initiation on commandName strings. In event of crash command could be left in the string<commit_after>/*
 FILNAMN: 		NetClient.cc
 PROGRAMMERARE:	hanel742, eriek984, jened502, tobgr602, niker917, davha227
 SKAPAD DATUM:	2013-11-19
 BESKRIVNING:
 */

#include "NetClient.h"
#include "../gui/gui.h"

using namespace std;

NetClient::NetClient(QString username, QString inAddress, Gui* myGui, QObject *parent) : QObject(parent){

    guiPointer = myGui;
    name=username;
    address=inAddress;
    compare += 0x1F;
    breaker +=0x1E;
}

// ---------------------------------------------

void NetClient::start(){
    TcpSocket = new QTcpSocket(this);

    connect(TcpSocket,SIGNAL(connected()),this,SLOT(connected()));
    connect(TcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected()));
    connect(TcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead()));

    QHostInfo info = QHostInfo::fromName(address);

    if (info.addresses().size() == 0){
        guiPointer->noConnection();
    }
    else{
        TcpSocket->connectToHost(info.addresses().at(0),quint16(40001));
        if(!TcpSocket->waitForConnected(1000)){
            guiPointer->noConnection();
        }
    }
}

//------Slots---------

void NetClient::connected(){
    QByteArray array = "/initiate";
    array += 0x1F; //unit separator
    array += name;
    array += breaker;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

void NetClient::disconnected(){
    guiPointer->disconnectedFromServer();

}

// --------readyRead------------------

void NetClient::readyRead(){

    QByteArray Data = TcpSocket->readAll();

    QString commandName = "";
    QString inData = Data;
    QString rest = "";
    int n = inData.indexOf(breaker);
    int i;

    do {
        rest = inData.mid(n+1);
        inData = inData.left(n);
        i = inData.indexOf(compare);

        commandName = inData.left(i);

        inData = inData.mid(i+1);

        QString temp = inData;
        string stdInData = temp.toStdString();

        // Check which command that's supposed to run
        if (commandName == "/reinitiate") {
            guiPointer->userNameTaken();
            break;
        }

        else if ( commandName == "/userAccepted") {
            guiPointer->connected();
        }

        else if (commandName == "/history") {
            handleHistory(inData);
        }

        else if (commandName == "/oldHistory") {
            handleOldHistory(inData);
        }

        else if (commandName == "/message") {
            handleMessage(inData);
        }

        else if ( commandName == "/requestStruct") {
            handleRequestStruct();
        }

        else if ( commandName == "/structure" ) {
            handleStructure(inData);
        }

        else {

            throw logic_error("Unknown command: " + commandName.toStdString());
        }

        inData = rest;
        n = inData.indexOf(breaker);

    }while (n != -1 );
}

// ---------------------------------------------

void NetClient::sendMessage(QString from, QString to, QString message){
    QByteArray array = "/message";
    array += 0x1F; //unit separator
    array += from;
    array += 0x1F;
    array += to;
    array += 0x1F;
    array += message;
    array += breaker;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

void NetClient::setName(QString inName) {
    name=inName;
}

void NetClient::getStruct(){
    QByteArray array = "/structure";
    array += 0x1E;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

//--------------------------------------------
//Helpfunctions

void NetClient::handleRequestStruct(){
    QByteArray array = "/structure";
    array += compare;
    array += breaker;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

// ---------------------------------------------

void NetClient::handleMessage(QString inData){

    int i;
    // Get from
    i = inData.indexOf(compare);
    QString from = inData.left(i);
    inData = inData.mid(i+1);

    // Get to
    i = inData.indexOf(compare);
    QString to = inData.left(i);
    inData = inData.mid(i+1);

    // Get message
    i = inData.indexOf(compare);
    QString contents = inData.left(i);
    inData = inData.mid(i+1);

    // Get time
    QString dateTime = inData;

    //Send message to Gui
    guiPointer->receiveMessage(from, to, contents, dateTime);

}

// ---------------------------------------------

void NetClient::handleHistory(QString inData){
    QVector<QString> history;
    int i = inData.indexOf(compare);
    while(i != -1 ){

        // Get from
        i = inData.indexOf(compare);
        QString from = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(from);

        // Get to
        i = inData.indexOf(compare);
        QString to = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(to);

        // Get message
        i = inData.indexOf(compare);
        QString contents = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(contents);

        //Get time
        i = inData.indexOf(compare);
        QString time = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(time);
    }
    guiPointer->receiveHistory(history);
}

// ---------------------------------------------

void NetClient::handleOldHistory(QString inData){
    QVector<QString> history;
    int i = inData.indexOf(compare);
    while(i != -1 ){

        // Get from
        i = inData.indexOf(compare);
        QString from = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(from);

        // Get to
        i = inData.indexOf(compare);
        QString to = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(to);

        // Get message
        i = inData.indexOf(compare);
        QString contents = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(contents);

        //Get time
        i = inData.indexOf(compare);
        QString time = inData.left(i);
        inData = inData.mid(i+1);
        history.push_back(time);
    }
    guiPointer->receiveOldHistory(history);
}

// ---------------------------------------------

void NetClient::handleStructure(QString inData){
    QVector<QString> output;
    int i = inData.indexOf(compare);

    while(i  != -1){
        //Create vector output, containing room content structure
        QString data = inData.left(i);
        inData = inData.mid(i+1);
        output.push_back(data);

        i = inData.indexOf(compare);
    }

    output.push_back(inData);

    guiPointer->updateStruct(output);

}

// ---------------------------------------------

void NetClient::getHistory(unsigned int daysBack) {
    QString temp;
    string daysBackString = to_string(daysBack);

    temp = QString::fromStdString(daysBackString);

    QByteArray array = "/oldHistory";
    array += compare; //unit separator
    array += temp;
    array += breaker;

    TcpSocket->write(array);
    TcpSocket->waitForBytesWritten(1000);
}

<|endoftext|>


<commit_before>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Miodrag Milanovic <miodrag@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "treemodel.h"

NEXTPNR_NAMESPACE_BEGIN

static bool contextTreeItemLessThan(const ContextTreeItem *v1, const ContextTreeItem *v2)
 {
     return v1->name() < v2->name();
 }

ContextTreeItem::ContextTreeItem() { parentNode = nullptr; }

ContextTreeItem::ContextTreeItem(QString name)
        : parentNode(nullptr), itemId(IdString()), itemType(ElementType::NONE), itemName(name)
{
}

ContextTreeItem::ContextTreeItem(IdString id, ElementType type, QString name)
        : parentNode(nullptr), itemId(id), itemType(type), itemName(name)
{
}

ContextTreeItem::~ContextTreeItem()
{
    if (parentNode)
        parentNode->children.removeOne(this);
    qDeleteAll(children);
}
void ContextTreeItem::addChild(ContextTreeItem *item)
{
    item->parentNode = this;
    children.append(item);
}

void ContextTreeItem::sort()
{
    for (auto item : children)
        if (item->count()>1) item->sort();
    qSort(children.begin(), children.end(), contextTreeItemLessThan);
}

ContextTreeModel::ContextTreeModel(QObject *parent) : QAbstractItemModel(parent) { root = new ContextTreeItem(); }

ContextTreeModel::~ContextTreeModel() { delete root; }

void ContextTreeModel::loadData(Context *ctx)
{
    if (!ctx)
        return;

    beginResetModel();

    delete root;
    root = new ContextTreeItem();

    for (int i = 0; i < 6; i++)
        nameToItem[i].clear();

    IdString none;

    ContextTreeItem *bels_root = new ContextTreeItem("Bels");
    root->addChild(bels_root);
    QMap<QString, ContextTreeItem *> bel_items;

    // Add bels to tree
    for (auto bel : ctx->getBels()) {
        IdString id = ctx->getBelName(bel);
        QStringList items = QString(id.c_str(ctx)).split("/");
        QString name;
        ContextTreeItem *parent = bels_root;
        for (int i = 0; i < items.size(); i++) {
            if (!name.isEmpty())
                name += "/";
            name += items.at(i);
            if (!bel_items.contains(name)) {
                if (i == items.size() - 1) {
                    ContextTreeItem *item = new ContextTreeItem(id, ElementType::BEL, items.at(i));
                    parent->addChild(item);
                    nameToItem[0].insert(name, item);
                } else {
                    ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
                    parent->addChild(item);
                    bel_items.insert(name, item);
                }
            }
            parent = bel_items[name];
        }
    }
    bels_root->sort();

    ContextTreeItem *wire_root = new ContextTreeItem("Wires");
    root->addChild(wire_root);
    QMap<QString, ContextTreeItem *> wire_items;

    // Add wires to tree
    for (auto wire : ctx->getWires()) {
        auto id = ctx->getWireName(wire);
        QStringList items = QString(id.c_str(ctx)).split("/");
        QString name;
        ContextTreeItem *parent = wire_root;
        for (int i = 0; i < items.size(); i++) {
            if (!name.isEmpty())
                name += "/";
            name += items.at(i);
            if (!wire_items.contains(name)) {
                if (i == items.size() - 1) {
                    ContextTreeItem *item = new ContextTreeItem(id, ElementType::WIRE, items.at(i));
                    parent->addChild(item);
                    nameToItem[1].insert(name, item);
                } else {
                    ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
                    parent->addChild(item);
                    wire_items.insert(name, item);
                }
            }
            parent = wire_items[name];
        }
    }
    wire_root->sort();

    ContextTreeItem *pip_root = new ContextTreeItem("Pips");
    root->addChild(pip_root);
    QMap<QString, ContextTreeItem *> pip_items;

    // Add pips to tree
    for (auto pip : ctx->getPips()) {
        auto id = ctx->getPipName(pip);
        QStringList items = QString(id.c_str(ctx)).split("/");
        QString name;
        ContextTreeItem *parent = pip_root;
        for (int i = 0; i < items.size(); i++) {
            if (!name.isEmpty())
                name += "/";
            name += items.at(i);
            if (!pip_items.contains(name)) {
                if (i == items.size() - 1) {
                    ContextTreeItem *item = new ContextTreeItem(id, ElementType::PIP, items.at(i));
                    parent->addChild(item);
                    nameToItem[2].insert(name, item);
                } else {
                    ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
                    parent->addChild(item);
                    pip_items.insert(name, item);
                }
            }
            parent = pip_items[name];
        }
    }
    pip_root->sort();

    nets_root = new ContextTreeItem("Nets");
    root->addChild(nets_root);

    cells_root = new ContextTreeItem("Cells");
    root->addChild(cells_root);

    endResetModel();
}

void ContextTreeModel::updateData(Context *ctx)
{
    if (!ctx)
        return;

    beginResetModel();

    //QModelIndex nets_index = indexFromNode(nets_root);
    // Remove nets not existing any more
    QMap<QString, ContextTreeItem *>::iterator i = nameToItem[3].begin();
    while (i != nameToItem[3].end()) {
        QMap<QString, ContextTreeItem *>::iterator prev = i;
        ++i;
        if (ctx->nets.find(ctx->id(prev.key().toStdString())) == ctx->nets.end()) {
            //int pos = prev.value()->parent()->indexOf(prev.value());
            //beginRemoveRows(nets_index, pos, pos);
            delete prev.value();
            nameToItem[3].erase(prev);
            //endRemoveRows();
        }
    }
    // Add nets to tree
    for (auto &item : ctx->nets) {
        auto id = item.first;
        QString name = QString(id.c_str(ctx));
        if (!nameToItem[3].contains(name)) {
            //beginInsertRows(nets_index, nets_root->count() + 1, nets_root->count() + 1);
            ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::NET, name);
            nets_root->addChild(newItem);
            nameToItem[3].insert(name, newItem);
            //endInsertRows();
        }
    }

    nets_root->sort();

    //QModelIndex cell_index = indexFromNode(cells_root);
    // Remove cells not existing any more
    i = nameToItem[4].begin();
    while (i != nameToItem[4].end()) {
        QMap<QString, ContextTreeItem *>::iterator prev = i;
        ++i;
        if (ctx->cells.find(ctx->id(prev.key().toStdString())) == ctx->cells.end()) {
            //int pos = prev.value()->parent()->indexOf(prev.value());
            //beginRemoveRows(cell_index, pos, pos);
            delete prev.value();
            nameToItem[4].erase(prev);
            //endRemoveRows();
        }
    }
    // Add cells to tree
    for (auto &item : ctx->cells) {
        auto id = item.first;
        QString name = QString(id.c_str(ctx));
        if (!nameToItem[4].contains(name)) {
            //beginInsertRows(cell_index, cells_root->count() + 1, cells_root->count() + 1);
            ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::CELL, name);
            cells_root->addChild(newItem);
            nameToItem[4].insert(name, newItem);
            //endInsertRows();
        }
    }

    cells_root->sort();

    endResetModel();
}

int ContextTreeModel::rowCount(const QModelIndex &parent) const { return nodeFromIndex(parent)->count(); }

int ContextTreeModel::columnCount(const QModelIndex &parent) const { return 1; }

QModelIndex ContextTreeModel::index(int row, int column, const QModelIndex &parent) const
{
    ContextTreeItem *node = nodeFromIndex(parent);
    if (row >= node->count())
        return QModelIndex();
    return createIndex(row, column, node->at(row));
}

QModelIndex ContextTreeModel::parent(const QModelIndex &child) const
{
    ContextTreeItem *parent = nodeFromIndex(child)->parent();
    if (parent == root)
        return QModelIndex();
    ContextTreeItem *node = parent->parent();
    return createIndex(node->indexOf(parent), 0, parent);
}

QVariant ContextTreeModel::data(const QModelIndex &index, int role) const
{
    if (index.column() != 0)
        return QVariant();
    if (role != Qt::DisplayRole)
        return QVariant();
    ContextTreeItem *node = nodeFromIndex(index);
    return node->name();
}

QVariant ContextTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    Q_UNUSED(section);
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
        return QString("Items");

    return QVariant();
}

ContextTreeItem *ContextTreeModel::nodeFromIndex(const QModelIndex &idx) const
{
    if (idx.isValid())
        return (ContextTreeItem *)idx.internalPointer();
    return root;
}

static int getElementIndex(ElementType type)
{
    if (type == ElementType::BEL)
        return 0;
    if (type == ElementType::WIRE)
        return 1;
    if (type == ElementType::PIP)
        return 2;
    if (type == ElementType::NET)
        return 3;
    if (type == ElementType::CELL)
        return 4;
    return -1;
}

ContextTreeItem *ContextTreeModel::nodeForIdType(const ElementType type, const QString name) const
{
    int index = getElementIndex(type);
    if (type != ElementType::NONE && nameToItem[index].contains(name))
        return nameToItem[index].value(name);
    return nullptr;
}

QModelIndex ContextTreeModel::indexFromNode(ContextTreeItem *node)
{
    ContextTreeItem *parent = node->parent();
    if (parent == root)
        return QModelIndex();
    return createIndex(parent->indexOf(node), 0, node);
}

Qt::ItemFlags ContextTreeModel::flags(const QModelIndex &index) const
{
    ContextTreeItem *node = nodeFromIndex(index);
    return Qt::ItemIsEnabled | (node->type() != ElementType::NONE ? Qt::ItemIsSelectable : Qt::NoItemFlags);
}
NEXTPNR_NAMESPACE_END<commit_msg>gui: sort tree elements somewhat smarter<commit_after>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Miodrag Milanovic <miodrag@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "treemodel.h"

NEXTPNR_NAMESPACE_BEGIN

ContextTreeItem::ContextTreeItem() { parentNode = nullptr; }

ContextTreeItem::ContextTreeItem(QString name)
        : parentNode(nullptr), itemId(IdString()), itemType(ElementType::NONE), itemName(name)
{
}

ContextTreeItem::ContextTreeItem(IdString id, ElementType type, QString name)
        : parentNode(nullptr), itemId(id), itemType(type), itemName(name)
{
}

ContextTreeItem::~ContextTreeItem()
{
    if (parentNode)
        parentNode->children.removeOne(this);
    qDeleteAll(children);
}
void ContextTreeItem::addChild(ContextTreeItem *item)
{
    item->parentNode = this;
    children.append(item);
}

void ContextTreeItem::sort()
{
    for (auto item : children)
        if (item->count()>1) item->sort();
    qSort(children.begin(), children.end(), [&](const ContextTreeItem *a, const ContextTreeItem *b){
        QString name_a = a->name();
        QString name_b = b->name();
        // Try to extract a common prefix from both strings.
        QString common;
        for (int i = 0; i < std::min(name_a.size(), name_b.size()); i++) {
            const QChar c_a = name_a[i];
            const QChar c_b = name_b[i];
            if (c_a == c_b) {
                common.push_back(c_a);
            } else {
                break;
            }
        }
        // No common part? lexical sort.
        if (common.size() == 0) {
            return a->name() < b->name();
        }

        // Get the non-common parts.
        name_a.remove(0, common.size());
        name_b.remove(0, common.size());
        // And see if they're strings.
        bool ok = true;
        int num_a = name_a.toInt(&ok);
        if (!ok) {
            return a->name() < b->name();
        }
        int num_b = name_b.toInt(&ok);
        if (!ok) {
            return a->name() < b->name();
        }
        return num_a < num_b;
    });
}

ContextTreeModel::ContextTreeModel(QObject *parent) : QAbstractItemModel(parent) { root = new ContextTreeItem(); }

ContextTreeModel::~ContextTreeModel() { delete root; }

void ContextTreeModel::loadData(Context *ctx)
{
    if (!ctx)
        return;

    beginResetModel();

    delete root;
    root = new ContextTreeItem();

    for (int i = 0; i < 6; i++)
        nameToItem[i].clear();

    IdString none;

    ContextTreeItem *bels_root = new ContextTreeItem("Bels");
    root->addChild(bels_root);
    QMap<QString, ContextTreeItem *> bel_items;

    // Add bels to tree
    for (auto bel : ctx->getBels()) {
        IdString id = ctx->getBelName(bel);
        QStringList items = QString(id.c_str(ctx)).split("/");
        QString name;
        ContextTreeItem *parent = bels_root;
        for (int i = 0; i < items.size(); i++) {
            if (!name.isEmpty())
                name += "/";
            name += items.at(i);
            if (!bel_items.contains(name)) {
                if (i == items.size() - 1) {
                    ContextTreeItem *item = new ContextTreeItem(id, ElementType::BEL, items.at(i));
                    parent->addChild(item);
                    nameToItem[0].insert(name, item);
                } else {
                    ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
                    parent->addChild(item);
                    bel_items.insert(name, item);
                }
            }
            parent = bel_items[name];
        }
    }
    bels_root->sort();

    ContextTreeItem *wire_root = new ContextTreeItem("Wires");
    root->addChild(wire_root);
    QMap<QString, ContextTreeItem *> wire_items;

    // Add wires to tree
    for (auto wire : ctx->getWires()) {
        auto id = ctx->getWireName(wire);
        QStringList items = QString(id.c_str(ctx)).split("/");
        QString name;
        ContextTreeItem *parent = wire_root;
        for (int i = 0; i < items.size(); i++) {
            if (!name.isEmpty())
                name += "/";
            name += items.at(i);
            if (!wire_items.contains(name)) {
                if (i == items.size() - 1) {
                    ContextTreeItem *item = new ContextTreeItem(id, ElementType::WIRE, items.at(i));
                    parent->addChild(item);
                    nameToItem[1].insert(name, item);
                } else {
                    ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
                    parent->addChild(item);
                    wire_items.insert(name, item);
                }
            }
            parent = wire_items[name];
        }
    }
    wire_root->sort();

    ContextTreeItem *pip_root = new ContextTreeItem("Pips");
    root->addChild(pip_root);
    QMap<QString, ContextTreeItem *> pip_items;

    // Add pips to tree
    for (auto pip : ctx->getPips()) {
        auto id = ctx->getPipName(pip);
        QStringList items = QString(id.c_str(ctx)).split("/");
        QString name;
        ContextTreeItem *parent = pip_root;
        for (int i = 0; i < items.size(); i++) {
            if (!name.isEmpty())
                name += "/";
            name += items.at(i);
            if (!pip_items.contains(name)) {
                if (i == items.size() - 1) {
                    ContextTreeItem *item = new ContextTreeItem(id, ElementType::PIP, items.at(i));
                    parent->addChild(item);
                    nameToItem[2].insert(name, item);
                } else {
                    ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
                    parent->addChild(item);
                    pip_items.insert(name, item);
                }
            }
            parent = pip_items[name];
        }
    }
    pip_root->sort();

    nets_root = new ContextTreeItem("Nets");
    root->addChild(nets_root);

    cells_root = new ContextTreeItem("Cells");
    root->addChild(cells_root);

    endResetModel();
}

void ContextTreeModel::updateData(Context *ctx)
{
    if (!ctx)
        return;

    beginResetModel();

    //QModelIndex nets_index = indexFromNode(nets_root);
    // Remove nets not existing any more
    QMap<QString, ContextTreeItem *>::iterator i = nameToItem[3].begin();
    while (i != nameToItem[3].end()) {
        QMap<QString, ContextTreeItem *>::iterator prev = i;
        ++i;
        if (ctx->nets.find(ctx->id(prev.key().toStdString())) == ctx->nets.end()) {
            //int pos = prev.value()->parent()->indexOf(prev.value());
            //beginRemoveRows(nets_index, pos, pos);
            delete prev.value();
            nameToItem[3].erase(prev);
            //endRemoveRows();
        }
    }
    // Add nets to tree
    for (auto &item : ctx->nets) {
        auto id = item.first;
        QString name = QString(id.c_str(ctx));
        if (!nameToItem[3].contains(name)) {
            //beginInsertRows(nets_index, nets_root->count() + 1, nets_root->count() + 1);
            ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::NET, name);
            nets_root->addChild(newItem);
            nameToItem[3].insert(name, newItem);
            //endInsertRows();
        }
    }

    nets_root->sort();

    //QModelIndex cell_index = indexFromNode(cells_root);
    // Remove cells not existing any more
    i = nameToItem[4].begin();
    while (i != nameToItem[4].end()) {
        QMap<QString, ContextTreeItem *>::iterator prev = i;
        ++i;
        if (ctx->cells.find(ctx->id(prev.key().toStdString())) == ctx->cells.end()) {
            //int pos = prev.value()->parent()->indexOf(prev.value());
            //beginRemoveRows(cell_index, pos, pos);
            delete prev.value();
            nameToItem[4].erase(prev);
            //endRemoveRows();
        }
    }
    // Add cells to tree
    for (auto &item : ctx->cells) {
        auto id = item.first;
        QString name = QString(id.c_str(ctx));
        if (!nameToItem[4].contains(name)) {
            //beginInsertRows(cell_index, cells_root->count() + 1, cells_root->count() + 1);
            ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::CELL, name);
            cells_root->addChild(newItem);
            nameToItem[4].insert(name, newItem);
            //endInsertRows();
        }
    }

    cells_root->sort();

    endResetModel();
}

int ContextTreeModel::rowCount(const QModelIndex &parent) const { return nodeFromIndex(parent)->count(); }

int ContextTreeModel::columnCount(const QModelIndex &parent) const { return 1; }

QModelIndex ContextTreeModel::index(int row, int column, const QModelIndex &parent) const
{
    ContextTreeItem *node = nodeFromIndex(parent);
    if (row >= node->count())
        return QModelIndex();
    return createIndex(row, column, node->at(row));
}

QModelIndex ContextTreeModel::parent(const QModelIndex &child) const
{
    ContextTreeItem *parent = nodeFromIndex(child)->parent();
    if (parent == root)
        return QModelIndex();
    ContextTreeItem *node = parent->parent();
    return createIndex(node->indexOf(parent), 0, parent);
}

QVariant ContextTreeModel::data(const QModelIndex &index, int role) const
{
    if (index.column() != 0)
        return QVariant();
    if (role != Qt::DisplayRole)
        return QVariant();
    ContextTreeItem *node = nodeFromIndex(index);
    return node->name();
}

QVariant ContextTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    Q_UNUSED(section);
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
        return QString("Items");

    return QVariant();
}

ContextTreeItem *ContextTreeModel::nodeFromIndex(const QModelIndex &idx) const
{
    if (idx.isValid())
        return (ContextTreeItem *)idx.internalPointer();
    return root;
}

static int getElementIndex(ElementType type)
{
    if (type == ElementType::BEL)
        return 0;
    if (type == ElementType::WIRE)
        return 1;
    if (type == ElementType::PIP)
        return 2;
    if (type == ElementType::NET)
        return 3;
    if (type == ElementType::CELL)
        return 4;
    return -1;
}

ContextTreeItem *ContextTreeModel::nodeForIdType(const ElementType type, const QString name) const
{
    int index = getElementIndex(type);
    if (type != ElementType::NONE && nameToItem[index].contains(name))
        return nameToItem[index].value(name);
    return nullptr;
}

QModelIndex ContextTreeModel::indexFromNode(ContextTreeItem *node)
{
    ContextTreeItem *parent = node->parent();
    if (parent == root)
        return QModelIndex();
    return createIndex(parent->indexOf(node), 0, node);
}

Qt::ItemFlags ContextTreeModel::flags(const QModelIndex &index) const
{
    ContextTreeItem *node = nodeFromIndex(index);
    return Qt::ItemIsEnabled | (node->type() != ElementType::NONE ? Qt::ItemIsSelectable : Qt::NoItemFlags);
}
NEXTPNR_NAMESPACE_END
<|endoftext|>


<commit_before>#include "quimby/MMapFile.h"

/*
#include <errno.h>
#include <math.h>
#include <string.h>
*/

#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdexcept>

namespace quimby {

MMapFile::MMapFile() :
	_fd(-1), _size(0), _data((char *)MAP_FAILED) {

}

MMapFile::MMapFile(const std::string& filename, MappingType mtype) :
	_fd(-1), _size(0), _data((char *)MAP_FAILED) {
	open(filename, mtype);
}

MMapFile::~MMapFile() {
	close();
}

void MMapFile::open(const std::string& filename, MappingType mtype ) {
	close();

	_fd = ::open(filename.c_str(), O_RDONLY);

	if (_fd == -1) {
		perror("MMapFile");
		throw std::runtime_error("[MMapFile] error opening file!");
	}

	_size = ::lseek(_fd, 0, SEEK_END);

	int flags = MAP_PRIVATE;

	if (mtype == ReadAhead)
		flags |= MAP_POPULATE;
	else if (mtype == Auto) {
		size_t mem = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE);

		if (_size < mem - 200) {
#ifdef DEBUG
			std::cout << "[MMapFile] Automatic mapping: ReadAhead, " << mem / 1000 / 1000 << " MB physical, " << _size / 1000 / 1000 << " MB required" << std::endl;
#endif
			flags |= MAP_POPULATE;
		} else {
#ifdef DEBUG
			std::cout << "[MMapFile] Automatic mapping: OnDemand, " << mem / 1000 / 1000 << " MB physical, " << _size / 1000 / 1000 << " MB required" << std::endl;
#endif
		}
	}

	_data = mmap(NULL, _size, PROT_READ, flags, _fd, 0);

	if (_data == MAP_FAILED) {
		perror("MMapFile");
		close();
		throw std::runtime_error("[HCubeFile] error mapping file: " + filename);
	}
}

void MMapFile::close() {
	if (_data != MAP_FAILED) {
		int result = munmap(_data, _size);
//          if (result < 0) {
//              printf("Error unmapping 0x0%lx of size %ld\n",
//                      (unsigned long) _data, _size);
//          }
		_data = MAP_FAILED;
	}

	_size = 0;

	if (_fd >= 0) {
		::close(_fd);
		_fd = -1;
	}
}

MMapFileWrite::MMapFileWrite(const std::string filename, size_t size, bool resume) :
	_file(-1), _data(MAP_FAILED), _data_size(size) {
	if (resume)
		_file = ::open(filename.c_str(), O_RDWR, 0666);
	else
		_file = ::open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0666);

	if (_file == -1)
		throw std::runtime_error("[MappedFile] error opening file!");

	truncate(_data_size);

	_data = ::mmap(NULL, _data_size, PROT_READ | PROT_WRITE, MAP_PRIVATE,
	               _file, 0);

	if (_data == MAP_FAILED) {
	    perror("MappedFile");
		throw std::runtime_error("[MappedFileWrite] error mapping file: " + filename);
	}
}

void MMapFileWrite::truncate(size_t size) {
	if (_file == -1)
		return;

	if (ftruncate(_file, size) == -1)
		throw std::runtime_error("[MappedFile Write] error truncating file!");
}

MMapFileWrite::~MMapFileWrite() {
	unmap();
	close();
}

void MMapFileWrite::unmap() {
	if (_data != MAP_FAILED) {
		::msync(_data, _data_size, MS_SYNC);
		::munmap(_data, _data_size);
		_data = MAP_FAILED;
	}

}
void MMapFileWrite::close() {
	if (_file != -1) {
		::close(_file);
		_file = -1;
	}

}

void* MMapFileWrite::data() {
	return _data;
}

} // namespace quimby
<commit_msg>fix mmap<commit_after>#include "quimby/MMapFile.h"

/*
#include <errno.h>
#include <math.h>
#include <string.h>
*/

#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdexcept>
#include <iostream>

namespace quimby {

MMapFile::MMapFile() :
	_fd(-1), _size(0), _data((char *)MAP_FAILED) {

}

MMapFile::MMapFile(const std::string& filename, MappingType mtype) :
	_fd(-1), _size(0), _data((char *)MAP_FAILED) {
	open(filename, mtype);
}

MMapFile::~MMapFile() {
	close();
}

void MMapFile::open(const std::string& filename, MappingType mtype ) {
	close();

	_fd = ::open(filename.c_str(), O_RDONLY);

	if (_fd == -1) {
		perror("MMapFile");
		throw std::runtime_error("[MMapFile] error opening file!");
	}

	_size = ::lseek(_fd, 0, SEEK_END);

	int flags = MAP_SHARED;

	if (mtype == ReadAhead)
		flags |= MAP_POPULATE;
	else if (mtype == Auto) {
		size_t mem = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE);

		if (_size < mem - 200) {
#ifdef DEBUG
			std::cout << "[MMapFile] Automatic mapping: ReadAhead, " << mem / 1000 / 1000 << " MB physical, " << _size / 1000 / 1000 << " MB required" << std::endl;
#endif
			flags |= MAP_POPULATE;
		} else {
#ifdef DEBUG
			std::cout << "[MMapFile] Automatic mapping: OnDemand, " << mem / 1000 / 1000 << " MB physical, " << _size / 1000 / 1000 << " MB required" << std::endl;
#endif
		}
	}

	_data = mmap(NULL, _size, PROT_READ, flags, _fd, 0);

	if (_data == MAP_FAILED) {
		perror("MMapFile");
		close();
		throw std::runtime_error("[HCubeFile] error mapping file: " + filename);
	}
}

void MMapFile::close() {
	if (_data != MAP_FAILED) {
		int result = munmap(_data, _size);
//          if (result < 0) {
//              printf("Error unmapping 0x0%lx of size %ld\n",
//                      (unsigned long) _data, _size);
//          }
		_data = MAP_FAILED;
	}

	_size = 0;

	if (_fd >= 0) {
		::close(_fd);
		_fd = -1;
	}
}

MMapFileWrite::MMapFileWrite(const std::string filename, size_t size, bool resume) :
	_file(-1), _data(MAP_FAILED), _data_size(size) {
	if (resume)
		_file = ::open(filename.c_str(), O_RDWR, 0666);
	else
		_file = ::open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0666);

	if (_file == -1)
		throw std::runtime_error("[MappedFile] error opening file!");

	truncate(_data_size);

	_data = ::mmap(NULL, _data_size, PROT_READ | PROT_WRITE, MAP_SHARED,
	               _file, 0);

	if (_data == MAP_FAILED) {
        std::cout << "[MappedFileWrite] " << _data_size << std::endl;
	    perror("[MappedFileWrite]");
		throw std::runtime_error("[MappedFileWrite] error mapping file: " + filename);
	}
}

void MMapFileWrite::truncate(size_t size) {
	if (_file == -1)
		return;

	if (ftruncate(_file, size) == -1)
		throw std::runtime_error("[MappedFile Write] error truncating file!");
}

MMapFileWrite::~MMapFileWrite() {
	unmap();
	close();
}

void MMapFileWrite::unmap() {
	if (_data != MAP_FAILED) {
		::msync(_data, _data_size, MS_SYNC);
		::munmap(_data, _data_size);
		_data = MAP_FAILED;
	}

}
void MMapFileWrite::close() {
	if (_file != -1) {
		::close(_file);
		_file = -1;
	}

}

void* MMapFileWrite::data() {
	return _data;
}

} // namespace quimby
<|endoftext|>