<commit_before>#include <jni.h>
// To get free disk space
#include <sys/vfs.h>

#include "../../../../../defines.hpp"

#include "../../../../../platform/http_request.hpp"

#include "../../../../../base/logging.hpp"
#include "../../../../../base/string_utils.hpp"

#include "../../../../../coding/zip_reader.hpp"
#include "../../../../../coding/url_encode.hpp"
#include "../../../../../coding/reader_streambuf.hpp"
#include "../../../../../coding/internal/file_data.hpp"

#include "../../../../../platform/platform.hpp"
#include "../../../../../platform/http_request.hpp"

#include "../../../../../std/vector.hpp"
#include "../../../../../std/string.hpp"
#include "../../../../../std/bind.hpp"

#include "../core/jni_helper.hpp"

#include "Framework.hpp"

// Special error codes to notify GUI about free space
//@{
#define ERR_DOWNLOAD_SUCCESS   0
#define ERR_NOT_ENOUGH_MEMORY     -1
#define ERR_NOT_ENOUGH_FREE_SPACE -2
#define ERR_STORAGE_DISCONNECTED  -3
#define ERR_DOWNLOAD_ERROR -4
#define ERR_NO_MORE_FILES -5
#define ERR_FILE_IN_PROGRESS -6
//@}

struct FileToDownload
{
  vector<string> m_urls;
  string m_fileName;
  string m_pathOnSdcard;
  uint64_t m_fileSize;
};

static string g_apkPath;
static string g_sdcardPath;
static vector<FileToDownload> g_filesToDownload;
static int g_totalDownloadedBytes;
static int g_totalBytesToDownload;
static downloader::HttpRequest * g_currentRequest;

extern "C"
{
  int HasSpaceForFiles(size_t fileSize)
  {
    struct statfs st;

    if (statfs(g_sdcardPath.c_str(), &st) != 0)
      return ERR_STORAGE_DISCONNECTED;

    if (st.f_bsize * st.f_bavail <= fileSize)
      return ERR_NOT_ENOUGH_FREE_SPACE;

    return fileSize;
  }

  JNIEXPORT jint JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_getBytesToDownload(JNIEnv * env, jobject thiz,
      jstring apkPath, jstring sdcardPath)
  {
    g_apkPath = jni::ToString(apkPath);
    g_sdcardPath = jni::ToString(sdcardPath);

    jint totalBytesToDownload = 0;

    ReaderStreamBuf buffer(GetPlatform().GetReader("external_resources.txt"));

    istream in(&buffer);

    string name;
    int size;

    while (true)
    {
      in >> name;

      if (!in.good())
        break;

      in >> size;

      if (!in.good())
        break;

      FileToDownload f;

      f.m_pathOnSdcard = g_sdcardPath + name;
      f.m_fileName = name;

      uint64_t sizeOnSdcard = 0;
      Platform::GetFileSizeByFullPath(f.m_pathOnSdcard, sizeOnSdcard);

      if (size != sizeOnSdcard)
      {
        LOG(LINFO, ("should check : ", name, "sized", size, "bytes"));
        f.m_fileSize = size;
        g_filesToDownload.push_back(f);
        totalBytesToDownload += size;
      }
    }

    g_totalDownloadedBytes = 0;

    int res = HasSpaceForFiles(totalBytesToDownload);

    switch (res)
    {
    case ERR_STORAGE_DISCONNECTED:
      LOG(LWARNING, ("External file system is not available"));
      break;
    case ERR_NOT_ENOUGH_FREE_SPACE:
      LOG(LWARNING, ("Not enough space to extract files"));
      break;
    };

    g_totalBytesToDownload = totalBytesToDownload;
    g_currentRequest = 0;

    return res;
  }

  void DownloadFileFinished(shared_ptr<jobject> obj, downloader::HttpRequest & req)
  {
    int errorCode = 0;

    ASSERT(req.Status() != downloader::HttpRequest::EInProgress, ("should be either Completed or Failed"));

    switch (req.Status())
    {
    case downloader::HttpRequest::ECompleted:
      errorCode = ERR_DOWNLOAD_SUCCESS;
      break;
    case downloader::HttpRequest::EFailed:
      errorCode = ERR_DOWNLOAD_ERROR;
      break;
    };

    if (errorCode == ERR_DOWNLOAD_SUCCESS)
    {
      FileToDownload & curFile = g_filesToDownload.back();

      /// cleaning up by ourselves
      FileWriter::DeleteFileX(curFile.m_pathOnSdcard + DOWNLOADING_FILE_EXTENSION);
      FileWriter::DeleteFileX(curFile.m_pathOnSdcard + RESUME_FILE_EXTENSION);

      LOG(LDEBUG, ("finished downloading", curFile.m_fileName, "sized", curFile.m_fileSize, "bytes"));

      /// slight hack, check manually for Maps extension and AddMap accordingly
      if (curFile.m_fileName.find(".mwm") != string::npos)
      {
        LOG(LINFO, ("adding it as a map"));
        g_framework->AddMap(curFile.m_fileName);
      }

      g_totalDownloadedBytes += curFile.m_fileSize;

      LOG(LDEBUG, ("totalDownloadedBytes:", g_totalDownloadedBytes));

      g_filesToDownload.pop_back();
    }

    JNIEnv * env = jni::GetEnv();

    jmethodID methodID = jni::GetJavaMethodID(env, *obj.get(), "onDownloadFinished", "(I)V");
    env->CallVoidMethod(*obj.get(), methodID, errorCode);
  }

  void DownloadFileProgress(shared_ptr<jobject> obj, downloader::HttpRequest & req)
  {
    LOG(LDEBUG, (req.Progress().first, "bytes for", g_filesToDownload.back().m_fileName, "was downloaded"));

    FileToDownload & curFile = g_filesToDownload.back();

    jint curTotal = req.Progress().second;
    jint curProgress = req.Progress().first;
    jint glbTotal = g_totalBytesToDownload;
    jint glbProgress = g_totalDownloadedBytes + req.Progress().first;

    JNIEnv * env = jni::GetEnv();

    jmethodID methodID = jni::GetJavaMethodID(env, *obj.get(), "onDownloadProgress", "(IIII)V");
    env->CallVoidMethod(*obj.get(), methodID,
                         curTotal, curProgress,
                         glbTotal, glbProgress);
  }

  void DownloadURLListFinished(downloader::HttpRequest & req,
      downloader::HttpRequest::CallbackT onFinish,
      downloader::HttpRequest::CallbackT onProgress)
  {
    if (req.Status() == downloader::HttpRequest::EFailed)
      onFinish(req);
    else
    {
      FileToDownload & curFile = g_filesToDownload.back();

      LOG(LDEBUG, ("finished URL list download for", curFile.m_fileName));

      downloader::ParseServerList(req.Data(), curFile.m_urls);

      for (size_t i = 0; i < curFile.m_urls.size(); ++i)
      {
        curFile.m_urls[i] = curFile.m_urls[i] + OMIM_OS_NAME "/"
                          + strings::to_string(g_framework->Storage().GetCurrentVersion()) + "/"
                          + UrlEncode(curFile.m_fileName);
        LOG(LDEBUG, (curFile.m_urls[i]));
      }

      g_currentRequest = downloader::HttpRequest::GetFile(curFile.m_urls,
                                                          curFile.m_pathOnSdcard,
                                                          curFile.m_fileSize,
                                                          onFinish,
                                                          onProgress,
                                                          64 * 1024,
                                                          false);
    }
  }

  JNIEXPORT void JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_cancelCurrentFile(JNIEnv * env, jobject thiz)
  {
    LOG(LINFO, ("pauseDownload, currentRequest=", g_currentRequest));
    delete g_currentRequest;
    g_currentRequest = 0;
  }

  JNIEXPORT int JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_startNextFileDownload(JNIEnv * env,
      jobject thiz, jobject observer)
  {
    if (g_filesToDownload.empty())
      return ERR_NO_MORE_FILES;

    FileToDownload & curFile = g_filesToDownload.back();

    LOG(LINFO, ("downloading", curFile.m_fileName, "sized", curFile.m_fileSize, "bytes"));

    downloader::HttpRequest::CallbackT onFinish(bind(&DownloadFileFinished, jni::make_global_ref(observer), _1));
    downloader::HttpRequest::CallbackT onProgress(bind(&DownloadFileProgress, jni::make_global_ref(observer), _1));

    g_currentRequest = downloader::HttpRequest::PostJson(GetPlatform().MetaServerUrl(),
                                                         curFile.m_fileName,
                                                         bind(&DownloadURLListFinished, _1,
                                                             onFinish,
                                                             onProgress));

    return ERR_FILE_IN_PROGRESS;
  }

  // Move downloaded maps from /sdcard/Android/data/com.mapswithme.maps/files/
  // to /sdcard/MapsWithMe
  JNIEXPORT void JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_moveMaps(JNIEnv * env, jobject thiz,
      jstring fromPath, jstring toPath)
  {
    string from = jni::ToString(fromPath);
    string to = jni::ToString(toPath);

    Platform & pl = GetPlatform();
    Platform::FilesList files;
    // Move *.mwm files
    pl.GetFilesInDir(from, "*" DATA_FILE_EXTENSION, files);
    for (size_t i = 0; i < files.size(); ++i)
    {
      LOG(LDEBUG, ("moving map from:", from + files[i], ", to:", to + files[i]));
      my::RenameFileX((from + files[i]).c_str(), (to + files[i]).c_str());
    }

    // Delete not finished *.downloading files
    files.clear();
    pl.GetFilesInDir(from, "*" DOWNLOADING_FILE_EXTENSION, files);
    pl.GetFilesInDir(from, "*" RESUME_FILE_EXTENSION, files);
    for (size_t i = 0; i < files.size(); ++i)
      my::DeleteFileX((from + files[i]).c_str());
  }

  JNIEXPORT jstring JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_findCountryByPos(JNIEnv * env, jobject thiz,
      jdouble lat, jdouble lon)
  {
    double x = MercatorBounds::LonToX(lon);
    double y = MercatorBounds::LatToY(lat);

    string name = g_framework->GetCountryName(x, y);

    return env->NewStringUTF(name.c_str());
  }
}
<commit_msg>using shared_ptr to control lifetime of HttpRequest.<commit_after>#include <jni.h>
// To get free disk space
#include <sys/vfs.h>

#include "../../../../../defines.hpp"

#include "../../../../../platform/http_request.hpp"

#include "../../../../../base/logging.hpp"
#include "../../../../../base/string_utils.hpp"

#include "../../../../../coding/zip_reader.hpp"
#include "../../../../../coding/url_encode.hpp"
#include "../../../../../coding/reader_streambuf.hpp"
#include "../../../../../coding/internal/file_data.hpp"

#include "../../../../../platform/platform.hpp"
#include "../../../../../platform/http_request.hpp"

#include "../../../../../std/vector.hpp"
#include "../../../../../std/string.hpp"
#include "../../../../../std/bind.hpp"
#include "../../../../../std/shared_ptr.hpp"

#include "../core/jni_helper.hpp"

#include "Framework.hpp"

// Special error codes to notify GUI about free space
//@{
#define ERR_DOWNLOAD_SUCCESS   0
#define ERR_NOT_ENOUGH_MEMORY     -1
#define ERR_NOT_ENOUGH_FREE_SPACE -2
#define ERR_STORAGE_DISCONNECTED  -3
#define ERR_DOWNLOAD_ERROR -4
#define ERR_NO_MORE_FILES -5
#define ERR_FILE_IN_PROGRESS -6
//@}

struct FileToDownload
{
  vector<string> m_urls;
  string m_fileName;
  string m_pathOnSdcard;
  uint64_t m_fileSize;
};

static string g_apkPath;
static string g_sdcardPath;
static vector<FileToDownload> g_filesToDownload;
static int g_totalDownloadedBytes;
static int g_totalBytesToDownload;
static shared_ptr<downloader::HttpRequest> g_currentRequest;

extern "C"
{
  int HasSpaceForFiles(size_t fileSize)
  {
    struct statfs st;

    if (statfs(g_sdcardPath.c_str(), &st) != 0)
      return ERR_STORAGE_DISCONNECTED;

    if (st.f_bsize * st.f_bavail <= fileSize)
      return ERR_NOT_ENOUGH_FREE_SPACE;

    return fileSize;
  }

  JNIEXPORT jint JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_getBytesToDownload(JNIEnv * env, jobject thiz,
      jstring apkPath, jstring sdcardPath)
  {
    g_apkPath = jni::ToString(apkPath);
    g_sdcardPath = jni::ToString(sdcardPath);

    jint totalBytesToDownload = 0;

    ReaderStreamBuf buffer(GetPlatform().GetReader("external_resources.txt"));

    istream in(&buffer);

    string name;
    int size;

    while (true)
    {
      in >> name;

      if (!in.good())
        break;

      in >> size;

      if (!in.good())
        break;

      FileToDownload f;

      f.m_pathOnSdcard = g_sdcardPath + name;
      f.m_fileName = name;

      uint64_t sizeOnSdcard = 0;
      Platform::GetFileSizeByFullPath(f.m_pathOnSdcard, sizeOnSdcard);

      if (size != sizeOnSdcard)
      {
        LOG(LINFO, ("should check : ", name, "sized", size, "bytes"));
        f.m_fileSize = size;
        g_filesToDownload.push_back(f);
        totalBytesToDownload += size;
      }
    }

    g_totalDownloadedBytes = 0;

    int res = HasSpaceForFiles(totalBytesToDownload);

    switch (res)
    {
    case ERR_STORAGE_DISCONNECTED:
      LOG(LWARNING, ("External file system is not available"));
      break;
    case ERR_NOT_ENOUGH_FREE_SPACE:
      LOG(LWARNING, ("Not enough space to extract files"));
      break;
    };

    g_totalBytesToDownload = totalBytesToDownload;
    g_currentRequest.reset();

    return res;
  }

  void DownloadFileFinished(shared_ptr<jobject> obj, downloader::HttpRequest & req)
  {
    int errorCode = 0;

    ASSERT(req.Status() != downloader::HttpRequest::EInProgress, ("should be either Completed or Failed"));

    switch (req.Status())
    {
    case downloader::HttpRequest::ECompleted:
      errorCode = ERR_DOWNLOAD_SUCCESS;
      break;
    case downloader::HttpRequest::EFailed:
      errorCode = ERR_DOWNLOAD_ERROR;
      break;
    };

    g_currentRequest.reset();

    if (errorCode == ERR_DOWNLOAD_SUCCESS)
    {
      FileToDownload & curFile = g_filesToDownload.back();

      /// cleaning up by ourselves
      FileWriter::DeleteFileX(curFile.m_pathOnSdcard + DOWNLOADING_FILE_EXTENSION);
      FileWriter::DeleteFileX(curFile.m_pathOnSdcard + RESUME_FILE_EXTENSION);

      LOG(LDEBUG, ("finished downloading", curFile.m_fileName, "sized", curFile.m_fileSize, "bytes"));

      /// slight hack, check manually for Maps extension and AddMap accordingly
      if (curFile.m_fileName.find(".mwm") != string::npos)
      {
        LOG(LINFO, ("adding it as a map"));
        g_framework->AddMap(curFile.m_fileName);
      }

      g_totalDownloadedBytes += curFile.m_fileSize;

      LOG(LDEBUG, ("totalDownloadedBytes:", g_totalDownloadedBytes));

      g_filesToDownload.pop_back();
    }

    JNIEnv * env = jni::GetEnv();

    jmethodID methodID = jni::GetJavaMethodID(env, *obj.get(), "onDownloadFinished", "(I)V");
    env->CallVoidMethod(*obj.get(), methodID, errorCode);
  }

  void DownloadFileProgress(shared_ptr<jobject> obj, downloader::HttpRequest & req)
  {
    LOG(LDEBUG, (req.Progress().first, "bytes for", g_filesToDownload.back().m_fileName, "was downloaded"));

    FileToDownload & curFile = g_filesToDownload.back();

    jint curTotal = req.Progress().second;
    jint curProgress = req.Progress().first;
    jint glbTotal = g_totalBytesToDownload;
    jint glbProgress = g_totalDownloadedBytes + req.Progress().first;

    JNIEnv * env = jni::GetEnv();

    jmethodID methodID = jni::GetJavaMethodID(env, *obj.get(), "onDownloadProgress", "(IIII)V");
    env->CallVoidMethod(*obj.get(), methodID,
                         curTotal, curProgress,
                         glbTotal, glbProgress);
  }

  void DownloadURLListFinished(downloader::HttpRequest & req,
      downloader::HttpRequest::CallbackT onFinish,
      downloader::HttpRequest::CallbackT onProgress)
  {
    if (req.Status() == downloader::HttpRequest::EFailed)
      onFinish(req);
    else
    {
      FileToDownload & curFile = g_filesToDownload.back();

      LOG(LDEBUG, ("finished URL list download for", curFile.m_fileName));

      downloader::ParseServerList(req.Data(), curFile.m_urls);

      for (size_t i = 0; i < curFile.m_urls.size(); ++i)
      {
        curFile.m_urls[i] = curFile.m_urls[i] + OMIM_OS_NAME "/"
                          + strings::to_string(g_framework->Storage().GetCurrentVersion()) + "/"
                          + UrlEncode(curFile.m_fileName);
        LOG(LDEBUG, (curFile.m_urls[i]));
      }

      g_currentRequest.reset(downloader::HttpRequest::GetFile(curFile.m_urls,
                                                          curFile.m_pathOnSdcard,
                                                          curFile.m_fileSize,
                                                          onFinish,
                                                          onProgress,
                                                          64 * 1024,
                                                          false));
    }
  }

  JNIEXPORT void JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_cancelCurrentFile(JNIEnv * env, jobject thiz)
  {
    LOG(LINFO, ("pauseDownload, currentRequest=", g_currentRequest));
    g_currentRequest.reset();
  }

  JNIEXPORT int JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_startNextFileDownload(JNIEnv * env,
      jobject thiz, jobject observer)
  {
    if (g_filesToDownload.empty())
      return ERR_NO_MORE_FILES;

    FileToDownload & curFile = g_filesToDownload.back();

    LOG(LINFO, ("downloading", curFile.m_fileName, "sized", curFile.m_fileSize, "bytes"));

    downloader::HttpRequest::CallbackT onFinish(bind(&DownloadFileFinished, jni::make_global_ref(observer), _1));
    downloader::HttpRequest::CallbackT onProgress(bind(&DownloadFileProgress, jni::make_global_ref(observer), _1));

    g_currentRequest.reset(downloader::HttpRequest::PostJson(GetPlatform().MetaServerUrl(),
                                                         curFile.m_fileName,
                                                         bind(&DownloadURLListFinished, _1,
                                                             onFinish,
                                                             onProgress)));

    return ERR_FILE_IN_PROGRESS;
  }

  // Move downloaded maps from /sdcard/Android/data/com.mapswithme.maps/files/
  // to /sdcard/MapsWithMe
  JNIEXPORT void JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_moveMaps(JNIEnv * env, jobject thiz,
      jstring fromPath, jstring toPath)
  {
    string from = jni::ToString(fromPath);
    string to = jni::ToString(toPath);

    Platform & pl = GetPlatform();
    Platform::FilesList files;
    // Move *.mwm files
    pl.GetFilesInDir(from, "*" DATA_FILE_EXTENSION, files);
    for (size_t i = 0; i < files.size(); ++i)
    {
      LOG(LDEBUG, ("moving map from:", from + files[i], ", to:", to + files[i]));
      my::RenameFileX((from + files[i]).c_str(), (to + files[i]).c_str());
    }

    // Delete not finished *.downloading files
    files.clear();
    pl.GetFilesInDir(from, "*" DOWNLOADING_FILE_EXTENSION, files);
    pl.GetFilesInDir(from, "*" RESUME_FILE_EXTENSION, files);
    for (size_t i = 0; i < files.size(); ++i)
      my::DeleteFileX((from + files[i]).c_str());
  }

  JNIEXPORT jstring JNICALL
  Java_com_mapswithme_maps_DownloadResourcesActivity_findCountryByPos(JNIEnv * env, jobject thiz,
      jdouble lat, jdouble lon)
  {
    double x = MercatorBounds::LonToX(lon);
    double y = MercatorBounds::LatToY(lat);

    string name = g_framework->GetCountryName(x, y);

    return env->NewStringUTF(name.c_str());
  }
}
<|endoftext|>


<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif

#include "DisplayListManager.h"

/*const int NO_VARIANT = (-1); */

// initialize the singleton
template <>
DisplayListManager* Singleton<DisplayListManager>::_instance = (DisplayListManager*)0;

DisplayListManager::DisplayListManager()
{
  lists.clear();
  lastID = -1;
}

DisplayListManager::DisplayListManager(const DisplayListManager &dm)
{
  release();
  lists = dm.lists;
  lastID = dm.lastID;
  aquire();
}

DisplayListManager& DisplayListManager::operator=(const DisplayListManager &dm)
{
  release()
  lists = dm.lists;
  lastID = dm.lastID;
  aquire();
  return *this;
}

DisplayListManager::~DisplayListManager()
{
  lists.clear();
}

int DisplayListManager::newList ( DisplayListBuilder *builder )
{
  if (!builder)
    return -1;

  displayListItem newItem;
  newItem.builder = builder;
  newItem.list = glGenLists(1);
  int id = ++lastID;
  lists[id] = newItem;
  glNewList(newItem.list,GL_COMPILE);
    builder->build();
  glEndList();
  return id;
}

void DisplayListManager::freeList ( int list )
{
  displayListMap::iterator  it = lists.find(list);
  if (it == lists.end())
    return;

  glDeleteLists(it->second.list,1);
  lists.erase(it);
}

bool DisplayListManager::callList ( int list )
{
  displayListMap::iterator  it = lists.find(list);
  if (it == lists.end())
    return false;

  if (it->second.list != _GL_INVALID_ID)
    glCallList(it->second.list);
  else
    return false;
  return true;
}

void DisplayListManager::release ( void )
{
  displayListMap::iterator  it = lists.begin();

  while (it != lists.end())
  {
    glDeleteLists(it->second.list,1);
    it->second.list = _GL_INVALID_ID;
    it++;
  }
}

void DisplayListManager::acquire ( void )
{
  displayListMap::iterator  it = lists.begin();

  while (it != lists.end())
  {
    it->second.list = glGenLists(1);
    glNewList(it->second.list,GL_COMPILE);
     it->second.builder->build();
    glEndList();
    it++;
  }
}

void DisplayListManager::rebuildLists()
{
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<commit_msg>it would help if I wasn't stupid.<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif

#include "DisplayListManager.h"

/*const int NO_VARIANT = (-1); */

// initialize the singleton
template <>
DisplayListManager* Singleton<DisplayListManager>::_instance = (DisplayListManager*)0;

DisplayListManager::DisplayListManager()
{
  lists.clear();
  lastID = -1;
}

DisplayListManager::DisplayListManager(const DisplayListManager &dm)
{
  release();
  lists = dm.lists;
  lastID = dm.lastID;
  acquire();
}

DisplayListManager& DisplayListManager::operator=(const DisplayListManager &dm)
{
  release()
  lists = dm.lists;
  lastID = dm.lastID;
  acquire();
  return *this;
}

DisplayListManager::~DisplayListManager()
{
  lists.clear();
}

int DisplayListManager::newList ( DisplayListBuilder *builder )
{
  if (!builder)
    return -1;

  displayListItem newItem;
  newItem.builder = builder;
  newItem.list = glGenLists(1);
  int id = ++lastID;
  lists[id] = newItem;
  glNewList(newItem.list,GL_COMPILE);
    builder->build();
  glEndList();
  return id;
}

void DisplayListManager::freeList ( int list )
{
  displayListMap::iterator  it = lists.find(list);
  if (it == lists.end())
    return;

  glDeleteLists(it->second.list,1);
  lists.erase(it);
}

bool DisplayListManager::callList ( int list )
{
  displayListMap::iterator  it = lists.find(list);
  if (it == lists.end())
    return false;

  if (it->second.list != _GL_INVALID_ID)
    glCallList(it->second.list);
  else
    return false;
  return true;
}

void DisplayListManager::release ( void )
{
  displayListMap::iterator  it = lists.begin();

  while (it != lists.end())
  {
    glDeleteLists(it->second.list,1);
    it->second.list = _GL_INVALID_ID;
    it++;
  }
}

void DisplayListManager::acquire ( void )
{
  displayListMap::iterator  it = lists.begin();

  while (it != lists.end())
  {
    it->second.list = glGenLists(1);
    glNewList(it->second.list,GL_COMPILE);
     it->second.builder->build();
    glEndList();
    it++;
  }
}

void DisplayListManager::rebuildLists()
{
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<|endoftext|>


<commit_before>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_EIGEN_HPP_
#define WTL_EIGEN_HPP_

#include <vector>
#include <string>
#include <fstream>
#include <Eigen/Core>

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl { namespace eigen {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

Eigen::IOFormat tsv(const std::string& sep="\t") {
    return {Eigen::StreamPrecision, Eigen::DontAlignCols, sep, "", "", "\n"};
}

template <class T>
std::vector<T> as_vector(const Eigen::Matrix<T, Eigen::Dynamic, 1>& vec) {
    return std::vector<T>(vec.data(), vec.data() + vec.size());
}

template <class T>
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> read_matrix(const std::string& path, const char sep='\t') {
    std::ifstream fin0(path.c_str());
    std::string buffer;
    std::getline(fin0, buffer, '\n');
    size_t ncol = std::count(buffer.begin(), buffer.end(), sep) + 1;
    std::ifstream fin(path.c_str());
    std::vector<T> vec{std::istream_iterator<T>(fin), std::istream_iterator<T>()};
    assert(vec.size() % ncol == 0);
    return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Map(vec.data(), vec.size() / ncol, ncol);
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
}} // namespace wtl::eigen
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif // WTL_EIGEN_HPP_
<commit_msg>Add as_valarray()<commit_after>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_EIGEN_HPP_
#define WTL_EIGEN_HPP_

#include <vector>
#include <valarray>
#include <string>
#include <fstream>
#include <Eigen/Core>

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl { namespace eigen {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

Eigen::IOFormat tsv(const std::string& sep="\t") {
    return {Eigen::StreamPrecision, Eigen::DontAlignCols, sep, "", "", "\n"};
}

template <class T>
std::vector<T> as_vector(const Eigen::Matrix<T, Eigen::Dynamic, 1>& vec) {
    return std::vector<T>(vec.data(), vec.data() + vec.size());
}

template <class T>
std::valarray<T> as_valarray(const Eigen::Matrix<T, Eigen::Dynamic, 1>& vec) {
    return std::valarray<T>(vec.data(), vec.size());
}

template <class T>
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> read_matrix(const std::string& path, const char sep='\t') {
    std::ifstream fin0(path.c_str());
    std::string buffer;
    std::getline(fin0, buffer, '\n');
    size_t ncol = std::count(buffer.begin(), buffer.end(), sep) + 1;
    std::ifstream fin(path.c_str());
    std::vector<T> vec{std::istream_iterator<T>(fin), std::istream_iterator<T>()};
    assert(vec.size() % ncol == 0);
    return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Map(vec.data(), vec.size() / ncol, ncol);
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
}} // namespace wtl::eigen
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif // WTL_EIGEN_HPP_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ctrl.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: hr $ $Date: 2004-09-08 17:47:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _SV_CTRL_HXX
#include <ctrl.hxx>
#endif
#ifndef _SV_DECOVIEW_HXX
#include <decoview.hxx>
#endif
#ifndef _VCL_CONTROLLAYOUT_HXX
#include <controllayout.hxx>
#endif
#ifndef _SV_NATIVEWIDGETS_HXX
#include <salnativewidgets.hxx>
#endif

using namespace vcl;

// =======================================================================

void Control::ImplInitData()
{
    mbHasFocus      = FALSE;
    mpLayoutData    = NULL;
}

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

Control::Control( WindowType nType ) :
    Window( nType )
{
    ImplInitData();
}

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

Control::Control( Window* pParent, WinBits nStyle ) :
    Window( WINDOW_CONTROL )
{
    ImplInitData();
    Window::ImplInit( pParent, nStyle, NULL );
}

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

Control::Control( Window* pParent, const ResId& rResId ) :
    Window( WINDOW_CONTROL )
{
    ImplInitData();
    rResId.SetRT( RSC_CONTROL );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInit( pParent, nStyle, NULL );
    ImplLoadRes( rResId );

    if ( !(nStyle & WB_HIDE) )
        Show();
}

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

Control::~Control()
{
    delete mpLayoutData, mpLayoutData = NULL;
}

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

void Control::GetFocus()
{
    Window::GetFocus();
}

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

void Control::LoseFocus()
{
    Window::LoseFocus();
}

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

void Control::Resize()
{
    delete mpLayoutData, mpLayoutData = NULL;
    Window::Resize();
}

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

void Control::FillLayoutData() const
{
}

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

void Control::SetText( const String& rStr )
{
    delete mpLayoutData;
    mpLayoutData = NULL;
    Window::SetText( rStr );
}

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

Rectangle ControlLayoutData::GetCharacterBounds( long nIndex ) const
{
    return (nIndex >= 0 && nIndex < m_aUnicodeBoundRects.size()) ? m_aUnicodeBoundRects[ nIndex ] : Rectangle();
}

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

Rectangle Control::GetCharacterBounds( long nIndex ) const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->GetCharacterBounds( nIndex ) : Rectangle();
}

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

long ControlLayoutData::GetIndexForPoint( const Point& rPoint ) const
{
    long nIndex = -1;
    for( long i = m_aUnicodeBoundRects.size()-1; i >= 0; i-- )
    {
        if( m_aUnicodeBoundRects[ i ].IsInside( rPoint ) )
        {
            nIndex = i;
            break;
        }
    }
    return nIndex;
}

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

long Control::GetIndexForPoint( const Point& rPoint ) const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->GetIndexForPoint( rPoint ) : -1;
}

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

long ControlLayoutData::GetLineCount() const
{
    long nLines = m_aLineIndices.size();
    if( nLines == 0 && m_aDisplayText.Len() )
        nLines = 1;
    return nLines;
}

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

long Control::GetLineCount() const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->GetLineCount() : 0;
}

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

Pair ControlLayoutData::GetLineStartEnd( long nLine ) const
{
    Pair aPair( -1, -1 );

    int nDisplayLines = m_aLineIndices.size();
    if( nLine >= 0 && nLine < nDisplayLines )
    {
        aPair.A() = m_aLineIndices[nLine];
        if( nLine+1 < nDisplayLines )
            aPair.B() = m_aLineIndices[nLine+1]-1;
        else
            aPair.B() = m_aDisplayText.Len()-1;
    }
    else if( nLine == 0 && nDisplayLines == 0 && m_aDisplayText.Len() )
    {
        // special case for single line controls so the implementations
        // in that case do not have to fill in the line indices
        aPair.A() = 0;
        aPair.B() = m_aDisplayText.Len()-1;
    }
    return aPair;
}

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

Pair Control::GetLineStartEnd( long nLine ) const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->GetLineStartEnd( nLine ) : Pair( -1, -1 );
}

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

long ControlLayoutData::ToRelativeLineIndex( long nIndex ) const
{
    // is the index sensible at all ?
    if( nIndex >= 0 && nIndex < m_aDisplayText.Len() )
    {
        int nDisplayLines = m_aLineIndices.size();
        // if only 1 line exists, then absolute and relative index are
        // identical -> do nothing
        if( nDisplayLines > 1 )
        {
            int nLine;
            for( nLine = nDisplayLines-1; nLine >= 0; nLine-- )
            {
                if( m_aLineIndices[nLine] <= nIndex )
                {
                    nIndex -= m_aLineIndices[nLine];
                    break;
                }
            }
            if( nLine < 0 )
            {
                DBG_ASSERT( nLine >= 0, "ToRelativeLineIndex failed" );
                nIndex = -1;
            }
        }
    }
    else
        nIndex = -1;

    return nIndex;
}

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

long Control::ToRelativeLineIndex( long nIndex ) const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->ToRelativeLineIndex( nIndex ) : -1;
}

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

String Control::GetDisplayText() const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->m_aDisplayText : GetText();
}

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

long Control::Notify( NotifyEvent& rNEvt )
{
    if ( rNEvt.GetType() == EVENT_GETFOCUS )
    {
        if ( !mbHasFocus )
        {
            mbHasFocus = TRUE;
            ImplDelData aDelData;
            ImplAddDel( &aDelData );
            ImplCallEventListeners( VCLEVENT_CONTROL_GETFOCUS );
            if ( aDelData.IsDelete() )
                return TRUE;
            maGetFocusHdl.Call( this );
            if ( aDelData.IsDelete() )
                return TRUE;
            ImplRemoveDel( &aDelData );
        }
    }
    else
    {
        if ( rNEvt.GetType() == EVENT_LOSEFOCUS )
        {
            Window* pFocusWin = Application::GetFocusWindow();
            if ( !pFocusWin || !ImplIsWindowOrChild( pFocusWin ) )
            {
                mbHasFocus = FALSE;
                ImplDelData aDelData;
                ImplAddDel( &aDelData );
                ImplCallEventListeners( VCLEVENT_CONTROL_LOSEFOCUS );
                if ( aDelData.IsDelete() )
                    return TRUE;
                maLoseFocusHdl.Call( this );
                if ( aDelData.IsDelete() )
                    return TRUE;
                ImplRemoveDel( &aDelData );
            }
        }
    }

    return Window::Notify( rNEvt );
}

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

void Control::StateChanged( StateChangedType nStateChange )
{
    if( nStateChange == STATE_CHANGE_INITSHOW   ||
        nStateChange == STATE_CHANGE_VISIBLE    ||
        nStateChange == STATE_CHANGE_FORMAT     ||
        nStateChange == STATE_CHANGE_ZOOM       ||
        nStateChange == STATE_CHANGE_BORDER     ||
        nStateChange == STATE_CHANGE_CONTROLFONT
        )
    {
        delete mpLayoutData;
        mpLayoutData = NULL;
    }
    Window::StateChanged( nStateChange );
}

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

void Control::AppendLayoutData( const Control& rSubControl ) const
{
    if( ! rSubControl.mpLayoutData )
        rSubControl.FillLayoutData();
    if( ! rSubControl.mpLayoutData || ! rSubControl.mpLayoutData->m_aDisplayText.Len() )
        return;

    long nCurrentIndex = mpLayoutData->m_aDisplayText.Len();
    mpLayoutData->m_aDisplayText.Append( rSubControl.mpLayoutData->m_aDisplayText );
    int nLines = rSubControl.mpLayoutData->m_aLineIndices.size();
    int n;
    mpLayoutData->m_aLineIndices.push_back( nCurrentIndex );
    for( n = 1; n < nLines; n++ )
        mpLayoutData->m_aLineIndices.push_back( rSubControl.mpLayoutData->m_aLineIndices[n] + nCurrentIndex );
    int nRectangles = rSubControl.mpLayoutData->m_aUnicodeBoundRects.size();
        Rectangle aRel = const_cast<Control&>(rSubControl).GetWindowExtentsRelative( const_cast<Control*>(this) );
    for( n = 0; n < nRectangles; n++ )
    {
        Rectangle aRect = rSubControl.mpLayoutData->m_aUnicodeBoundRects[n];
        aRect.Move( aRel.Left(), aRel.Top() );
        mpLayoutData->m_aUnicodeBoundRects.push_back( aRect );
    }
}

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

void Control::SetLayoutDataParent( const Control* pParent ) const
{
    if( mpLayoutData )
        mpLayoutData->m_pParent = pParent;
}

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

void Control::ImplClearLayoutData() const
{
    delete mpLayoutData, mpLayoutData = NULL;
}

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

void Control::ImplDrawFrame( OutputDevice* pDev, Rectangle& rRect )
{
    // use a deco view to draw the frame
    // However, since there happens a lot of magic there, we need to fake some (style) settings
    // on the device
    AllSettings aOriginalSettings( pDev->GetSettings() );

    AllSettings aNewSettings( aOriginalSettings );
    StyleSettings aStyle( aNewSettings.GetStyleSettings() );

    // The *only known* clients of the Draw methods of the various VCL-controls are form controls:
    // During print preview, and during printing, Draw is called. Thus, drawing always happens with a
    // mono (colored) border
    aStyle.SetOptions( aStyle.GetOptions() | STYLE_OPTION_MONO );
    aStyle.SetMonoColor( GetSettings().GetStyleSettings().GetMonoColor() );

    aNewSettings.SetStyleSettings( aStyle );
    pDev->SetSettings( aNewSettings );

    DecorationView aDecoView( pDev );
    rRect = aDecoView.DrawFrame( rRect, FRAME_DRAW_WINDOWBORDER );

    pDev->SetSettings( aOriginalSettings );
}

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

void Control::DataChanged( const DataChangedEvent& rDCEvt)
{
    // we don't want to loose some style settings for controls created with the
    // toolkit
    if ( IsCreatedWithToolkit() &&
         (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
         (rDCEvt.GetFlags() & SETTINGS_STYLE) )
    {
        AllSettings     aSettings = GetSettings();
        StyleSettings   aStyleSettings = aSettings.GetStyleSettings();
        ULONG           nOldOptions = rDCEvt.GetOldSettings()->GetStyleSettings().GetOptions();
        ULONG           nNewOptions = aStyleSettings.GetOptions();

        if ( !(nNewOptions & STYLE_OPTION_MONO) && ( nOldOptions & STYLE_OPTION_MONO ) )
        {
            nNewOptions |= STYLE_OPTION_MONO;
            aStyleSettings.SetOptions( nNewOptions );
            aStyleSettings.SetMonoColor( rDCEvt.GetOldSettings()->GetStyleSettings().GetMonoColor() );
            aSettings.SetStyleSettings( aStyleSettings );
            SetSettings( aSettings );
        }
    }
}

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

ControlLayoutData::~ControlLayoutData()
{
    if( m_pParent )
        m_pParent->ImplClearLayoutData();
}
<commit_msg>INTEGRATION: CWS dba17 (1.15.70); FILE MERGED 2004/09/20 14:51:10 fs 1.15.70.2: RESYNC: (1.15-1.16); FILE MERGED 2004/09/08 13:18:05 fs 1.15.70.1: #i33728# (approved by ssa) +ImplCallEventListenersAndHandler<commit_after>/*************************************************************************
 *
 *  $RCSfile: ctrl.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-10-22 12:12:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _SV_CTRL_HXX
#include <ctrl.hxx>
#endif
#ifndef _SV_DECOVIEW_HXX
#include <decoview.hxx>
#endif
#ifndef _VCL_CONTROLLAYOUT_HXX
#include <controllayout.hxx>
#endif
#ifndef _SV_NATIVEWIDGETS_HXX
#include <salnativewidgets.hxx>
#endif

using namespace vcl;

// =======================================================================

void Control::ImplInitData()
{
    mbHasFocus      = FALSE;
    mpLayoutData    = NULL;
}

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

Control::Control( WindowType nType ) :
    Window( nType )
{
    ImplInitData();
}

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

Control::Control( Window* pParent, WinBits nStyle ) :
    Window( WINDOW_CONTROL )
{
    ImplInitData();
    Window::ImplInit( pParent, nStyle, NULL );
}

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

Control::Control( Window* pParent, const ResId& rResId ) :
    Window( WINDOW_CONTROL )
{
    ImplInitData();
    rResId.SetRT( RSC_CONTROL );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInit( pParent, nStyle, NULL );
    ImplLoadRes( rResId );

    if ( !(nStyle & WB_HIDE) )
        Show();
}

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

Control::~Control()
{
    delete mpLayoutData, mpLayoutData = NULL;
}

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

void Control::GetFocus()
{
    Window::GetFocus();
}

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

void Control::LoseFocus()
{
    Window::LoseFocus();
}

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

void Control::Resize()
{
    delete mpLayoutData, mpLayoutData = NULL;
    Window::Resize();
}

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

void Control::FillLayoutData() const
{
}

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

void Control::SetText( const String& rStr )
{
    delete mpLayoutData;
    mpLayoutData = NULL;
    Window::SetText( rStr );
}

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

Rectangle ControlLayoutData::GetCharacterBounds( long nIndex ) const
{
    return (nIndex >= 0 && nIndex < m_aUnicodeBoundRects.size()) ? m_aUnicodeBoundRects[ nIndex ] : Rectangle();
}

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

Rectangle Control::GetCharacterBounds( long nIndex ) const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->GetCharacterBounds( nIndex ) : Rectangle();
}

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

long ControlLayoutData::GetIndexForPoint( const Point& rPoint ) const
{
    long nIndex = -1;
    for( long i = m_aUnicodeBoundRects.size()-1; i >= 0; i-- )
    {
        if( m_aUnicodeBoundRects[ i ].IsInside( rPoint ) )
        {
            nIndex = i;
            break;
        }
    }
    return nIndex;
}

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

long Control::GetIndexForPoint( const Point& rPoint ) const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->GetIndexForPoint( rPoint ) : -1;
}

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

long ControlLayoutData::GetLineCount() const
{
    long nLines = m_aLineIndices.size();
    if( nLines == 0 && m_aDisplayText.Len() )
        nLines = 1;
    return nLines;
}

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

long Control::GetLineCount() const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->GetLineCount() : 0;
}

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

Pair ControlLayoutData::GetLineStartEnd( long nLine ) const
{
    Pair aPair( -1, -1 );

    int nDisplayLines = m_aLineIndices.size();
    if( nLine >= 0 && nLine < nDisplayLines )
    {
        aPair.A() = m_aLineIndices[nLine];
        if( nLine+1 < nDisplayLines )
            aPair.B() = m_aLineIndices[nLine+1]-1;
        else
            aPair.B() = m_aDisplayText.Len()-1;
    }
    else if( nLine == 0 && nDisplayLines == 0 && m_aDisplayText.Len() )
    {
        // special case for single line controls so the implementations
        // in that case do not have to fill in the line indices
        aPair.A() = 0;
        aPair.B() = m_aDisplayText.Len()-1;
    }
    return aPair;
}

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

Pair Control::GetLineStartEnd( long nLine ) const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->GetLineStartEnd( nLine ) : Pair( -1, -1 );
}

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

long ControlLayoutData::ToRelativeLineIndex( long nIndex ) const
{
    // is the index sensible at all ?
    if( nIndex >= 0 && nIndex < m_aDisplayText.Len() )
    {
        int nDisplayLines = m_aLineIndices.size();
        // if only 1 line exists, then absolute and relative index are
        // identical -> do nothing
        if( nDisplayLines > 1 )
        {
            int nLine;
            for( nLine = nDisplayLines-1; nLine >= 0; nLine-- )
            {
                if( m_aLineIndices[nLine] <= nIndex )
                {
                    nIndex -= m_aLineIndices[nLine];
                    break;
                }
            }
            if( nLine < 0 )
            {
                DBG_ASSERT( nLine >= 0, "ToRelativeLineIndex failed" );
                nIndex = -1;
            }
        }
    }
    else
        nIndex = -1;

    return nIndex;
}

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

long Control::ToRelativeLineIndex( long nIndex ) const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->ToRelativeLineIndex( nIndex ) : -1;
}

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

String Control::GetDisplayText() const
{
    if( ! mpLayoutData )
        FillLayoutData();
    return mpLayoutData ? mpLayoutData->m_aDisplayText : GetText();
}

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

long Control::Notify( NotifyEvent& rNEvt )
{
    if ( rNEvt.GetType() == EVENT_GETFOCUS )
    {
        if ( !mbHasFocus )
        {
            mbHasFocus = TRUE;
            if ( ImplCallEventListenersAndHandler( VCLEVENT_CONTROL_GETFOCUS, maGetFocusHdl, this ) )
                // been destroyed within the handler
                return TRUE;
        }
    }
    else
    {
        if ( rNEvt.GetType() == EVENT_LOSEFOCUS )
        {
            Window* pFocusWin = Application::GetFocusWindow();
            if ( !pFocusWin || !ImplIsWindowOrChild( pFocusWin ) )
            {
                mbHasFocus = FALSE;
                if ( ImplCallEventListenersAndHandler( VCLEVENT_CONTROL_LOSEFOCUS, maLoseFocusHdl, this ) )
                    // been destroyed within the handler
                    return TRUE;
            }
        }
    }

    return Window::Notify( rNEvt );
}

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

void Control::StateChanged( StateChangedType nStateChange )
{
    if( nStateChange == STATE_CHANGE_INITSHOW   ||
        nStateChange == STATE_CHANGE_VISIBLE    ||
        nStateChange == STATE_CHANGE_FORMAT     ||
        nStateChange == STATE_CHANGE_ZOOM       ||
        nStateChange == STATE_CHANGE_BORDER     ||
        nStateChange == STATE_CHANGE_CONTROLFONT
        )
    {
        delete mpLayoutData;
        mpLayoutData = NULL;
    }
    Window::StateChanged( nStateChange );
}

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

void Control::AppendLayoutData( const Control& rSubControl ) const
{
    if( ! rSubControl.mpLayoutData )
        rSubControl.FillLayoutData();
    if( ! rSubControl.mpLayoutData || ! rSubControl.mpLayoutData->m_aDisplayText.Len() )
        return;

    long nCurrentIndex = mpLayoutData->m_aDisplayText.Len();
    mpLayoutData->m_aDisplayText.Append( rSubControl.mpLayoutData->m_aDisplayText );
    int nLines = rSubControl.mpLayoutData->m_aLineIndices.size();
    int n;
    mpLayoutData->m_aLineIndices.push_back( nCurrentIndex );
    for( n = 1; n < nLines; n++ )
        mpLayoutData->m_aLineIndices.push_back( rSubControl.mpLayoutData->m_aLineIndices[n] + nCurrentIndex );
    int nRectangles = rSubControl.mpLayoutData->m_aUnicodeBoundRects.size();
        Rectangle aRel = const_cast<Control&>(rSubControl).GetWindowExtentsRelative( const_cast<Control*>(this) );
    for( n = 0; n < nRectangles; n++ )
    {
        Rectangle aRect = rSubControl.mpLayoutData->m_aUnicodeBoundRects[n];
        aRect.Move( aRel.Left(), aRel.Top() );
        mpLayoutData->m_aUnicodeBoundRects.push_back( aRect );
    }
}

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

BOOL Control::ImplCallEventListenersAndHandler(  ULONG nEvent, const Link& rHandler, void* pCaller )
{
    ImplDelData aCheckDelete;
    ImplAddDel( &aCheckDelete );

    ImplCallEventListeners( nEvent );
    if ( !aCheckDelete.IsDelete() )
    {
        rHandler.Call( pCaller );

        if ( !aCheckDelete.IsDelete() )
        {
            ImplRemoveDel( &aCheckDelete );
            return FALSE;
        }
    }
    return TRUE;
}

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

void Control::SetLayoutDataParent( const Control* pParent ) const
{
    if( mpLayoutData )
        mpLayoutData->m_pParent = pParent;
}

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

void Control::ImplClearLayoutData() const
{
    delete mpLayoutData, mpLayoutData = NULL;
}

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

void Control::ImplDrawFrame( OutputDevice* pDev, Rectangle& rRect )
{
    // use a deco view to draw the frame
    // However, since there happens a lot of magic there, we need to fake some (style) settings
    // on the device
    AllSettings aOriginalSettings( pDev->GetSettings() );

    AllSettings aNewSettings( aOriginalSettings );
    StyleSettings aStyle( aNewSettings.GetStyleSettings() );

    // The *only known* clients of the Draw methods of the various VCL-controls are form controls:
    // During print preview, and during printing, Draw is called. Thus, drawing always happens with a
    // mono (colored) border
    aStyle.SetOptions( aStyle.GetOptions() | STYLE_OPTION_MONO );
    aStyle.SetMonoColor( GetSettings().GetStyleSettings().GetMonoColor() );

    aNewSettings.SetStyleSettings( aStyle );
    pDev->SetSettings( aNewSettings );

    DecorationView aDecoView( pDev );
    rRect = aDecoView.DrawFrame( rRect, FRAME_DRAW_WINDOWBORDER );

    pDev->SetSettings( aOriginalSettings );
}

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

void Control::DataChanged( const DataChangedEvent& rDCEvt)
{
    // we don't want to loose some style settings for controls created with the
    // toolkit
    if ( IsCreatedWithToolkit() &&
         (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
         (rDCEvt.GetFlags() & SETTINGS_STYLE) )
    {
        AllSettings     aSettings = GetSettings();
        StyleSettings   aStyleSettings = aSettings.GetStyleSettings();
        ULONG           nOldOptions = rDCEvt.GetOldSettings()->GetStyleSettings().GetOptions();
        ULONG           nNewOptions = aStyleSettings.GetOptions();

        if ( !(nNewOptions & STYLE_OPTION_MONO) && ( nOldOptions & STYLE_OPTION_MONO ) )
        {
            nNewOptions |= STYLE_OPTION_MONO;
            aStyleSettings.SetOptions( nNewOptions );
            aStyleSettings.SetMonoColor( rDCEvt.GetOldSettings()->GetStyleSettings().GetMonoColor() );
            aSettings.SetStyleSettings( aStyleSettings );
            SetSettings( aSettings );
        }
    }
}

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

ControlLayoutData::~ControlLayoutData()
{
    if( m_pParent )
        m_pParent->ImplClearLayoutData();
}
<|endoftext|>


<commit_before>#include "Scorpio/min-max.hpp"

#include "board.hpp"
#include "enemy.hpp"
#include "random.hpp"

namespace roadagain
{

Enemy::Enemy(Level level) : level_(level)
{
}

Enemy::~Enemy()
{
}

Point Enemy::select(const Board* board, BoardState stone) const
{
    switch (level_){
        case EASY:
            return (randomized_select(board, stone));
        default:
            return (maximized_select(board, stone));
    }
}

Point Enemy::randomized_select(const Board* board, BoardState stone) const
{
    int n = random();
    int y = 0;
    int x = 0;

    do {
        y++;
        if (y >= Board::ROW){
            y = 0;
            x = (x + 1) % Board::COL;
        }
        while (!board->can_put(Point(y, x), stone)){
            y++;
            if (y >= Board::ROW){
                y = 0;
                x = (x + 1) % Board::COL;
            }
        }
        n--;
    } while (n > 0);

    return (Point(y, x));
}

Point Enemy::maximized_select(const Board* board, BoardState stone) const
{
    int y = 0;
    int x = 0;
    int maximum = 0;

    for (int i = 0; i < Board::ROW; i++){
        for (int j = 0; j < Board::COL; j++){
            if (board->can_put(Point(i, j), stone)){
                int tmp = board->reverse_num(Point(i, j), stone);
                if (maximum < tmp){
                    maximum = tmp;
                    y = i;
                    x = j;
                }
                else if (maximum == tmp && random() % 2 == 0){
                    y = i;
                    x = j;
                }
            }
        }
    }

    return (Point(y, x));
}

}
<commit_msg>Wrap local y and x with Point in enemy<commit_after>#include "Scorpio/min-max.hpp"

#include "board.hpp"
#include "enemy.hpp"
#include "random.hpp"

namespace roadagain
{

Enemy::Enemy(Level level) : level_(level)
{
}

Enemy::~Enemy()
{
}

Point Enemy::select(const Board* board, BoardState stone) const
{
    switch (level_){
        case EASY:
            return (randomized_select(board, stone));
        default:
            return (maximized_select(board, stone));
    }
}

Point Enemy::randomized_select(const Board* board, BoardState stone) const
{
    int n = random();
    Point p;

    do {
        p.y++;
        if (p.y >= Board::ROW){
            p.y = 0;
            p.x = (p.x + 1) % Board::COL;
        }
        while (!board->can_put(p, stone)){
            p.y++;
            if (p.y >= Board::ROW){
                p.y = 0;
                p.x = (p.x + 1) % Board::COL;
            }
        }
        n--;
    } while (n > 0);

    return (p);
}

Point Enemy::maximized_select(const Board* board, BoardState stone) const
{
    Point p;
    int maximum = 0;

    for (int i = 0; i < Board::ROW; i++){
        for (int j = 0; j < Board::COL; j++){
            if (board->can_put(Point(i, j), stone)){
                int tmp = board->reverse_num(Point(i, j), stone);
                if (maximum < tmp){
                    maximum = tmp;
                    p.y = i;
                    p.x = j;
                }
                else if (maximum == tmp && random() % 2 == 0){
                    p.y = i;
                    p.x = j;
                }
            }
        }
    }

    return (p);
}

}
<|endoftext|>


<commit_before>#include <bsoncxx/builder.hpp>

#include <mongocxx/client.hpp>

using namespace bsoncxx::builder::helpers;
using bsoncxx::builder::document;

int main(int, char**) {
    mongocxx::client conn{};

    auto db = conn["test"];

    // Update top-level fields in a single document.
    {
        // @begin: cpp-update-top-level-fields
        document filter, update;
        filter << "name" << "Juni";
        update << "$set" << open_doc
                   << "cuisine" << "American (New)" << close_doc
               << "$currentDate" << open_doc
                   << "lastModified" << true << close_doc;
        db["restaurants"].update_one(filter, update);
        // @end: cpp-update-top-level-fields
    }

    // Update an embedded document in a single document.
    {
        // @begin: cpp-update-embedded-field
        document filter, update;
        filter << "restaurant_id" << "41156888";
        update << "$set" << open_doc <<
                   "address.street" << "East 31st Street" << close_doc;
        // @end: cpp-update-embedded-field
        db["restaurants"].update_one(filter, update);
    }

    // Update multiple documents.
    {
        // @begin: cpp-update-multiple-documents
        document filter, update;
        filter << "address.zipcode" << "10016";
        update << "$set" << open_doc
                   << "borough" << "Midtown" << close_doc
               << "$currentDate" << open_doc
                   << "lastModified" << true << close_doc;

        // @end: cpp-update-multiple-documents
        db["restaurants"].update_many(filter, update);
    }

    // Replace the contents of a single document.
    {
        // @begin: cpp-replace-document
        document filter, replacement;
        filter << "restaurant_id" << "41704620";
        replacement << "name" << "Vella 2"
                    << "address" << open_doc
                        << "coord" << open_array
                            << -73.9557413 << 40.7720266 << close_array
                        << "building" << "1480"
                        << "street" << "2 Avenue"
                        << "zipcode" << "10075" << close_doc;
        db["restaurants"].replace_one(filter, replacement);
        // @end: cpp-replace-document
    }
}
<commit_msg>cleanup update examples<commit_after>#include <bsoncxx/builder.hpp>

#include <mongocxx/client.hpp>

using namespace bsoncxx::builder::helpers;
using bsoncxx::builder::document;

int main(int, char**) {
    mongocxx::client conn{};

    auto db = conn["test"];

    // Update top-level fields in a single document.
    {
        // @begin: cpp-update-top-level-fields
        document filter, update;
        filter << "name" << "Juni";
        update << "$set" << open_doc
                   << "cuisine" << "American (New)" << close_doc
               << "$currentDate" << open_doc
                   << "lastModified" << true << close_doc;

        db["restaurants"].update_one(filter, update);
        // @end: cpp-update-top-level-fields
    }

    // Update an embedded document in a single document.
    {
        // @begin: cpp-update-embedded-field
        document filter, update;
        filter << "restaurant_id" << "41156888";
        update << "$set" << open_doc <<
                   "address.street" << "East 31st Street" << close_doc;

        db["restaurants"].update_one(filter, update);
        // @end: cpp-update-embedded-field
    }

    // Update multiple documents.
    {
        // @begin: cpp-update-multiple-documents
        document filter, update;
        filter << "address.zipcode" << "10016";
        update << "$set" << open_doc
                   << "borough" << "Midtown" << close_doc
               << "$currentDate" << open_doc
                   << "lastModified" << true << close_doc;

        db["restaurants"].update_many(filter, update);
        // @end: cpp-update-multiple-documents
    }

    // Replace the contents of a single document.
    {
        // @begin: cpp-replace-document
        document filter, replacement;
        filter << "restaurant_id" << "41704620";
        replacement << "name" << "Vella 2"
                    << "address" << open_doc
                        << "coord" << open_array
                            << -73.9557413 << 40.7720266 << close_array
                        << "building" << "1480"
                        << "street" << "2 Avenue"
                        << "zipcode" << "10075" << close_doc;

        db["restaurants"].replace_one(filter, replacement);
        // @end: cpp-replace-document
    }
}
<|endoftext|>


<commit_before>#include "vsr_root.h"
#include "vsr_GLVimpl.h"
#include "vsr_ega3D_draw.h"

using namespace vsr;

typedef EGAMV< 4, Blade1<4>::VEC > V4;

//idositetrachoron 24 cell

auto D4 = Root::System<4>( V4(1,0,0,0), V4(0,1,0,0), V4(0,0,1,0), ( V4(-1,-1,-1, 1) * .5 ) );

auto F4 = Root::System<4>( V4(0,1,-1,0), V4(1,-1,0,0), V4(0,0,1,0), ( V4(-1,-1,-1, 1) * .5 ) );

auto H4 = Root::System<4>( V4(0,-1,0,0), V4(0,1.618,1,-.618) * .5, V4(0,0,-1,0), ( V4(-.618,0,1, 1.618) * .5 ) );

struct MyApp : App {

	bool d4, f4, h4, bSpin, bOrtho;

	virtual void initGui(){
		gui(d4,"d4")(f4,"f4")(h4,"h4");
		gui(bSpin, "spin")(bOrtho, "ortho");
		d4 = true;
	}

	void onDraw(){

	  scene.camera.lens.bOrtho = bOrtho;

	  if (d4){
	   for (auto &i : D4 ){
			if (bSpin) i = i.sp( Gen::rot( EGAMV<4, MV<10,12> > (.01,.01) ) );
			Vec tp = Proj<4>::Call(5.0 , i);
			Vec to = Proj<4>::Ortho<3>(i);
			Draw( bOrtho ? to : tp );

		}
	  }

	  if (f4){
	   for (auto &i : F4 ){
			if (bSpin) i = i.sp( Gen::rot( EGAMV<4, MV<10,12> > (.01,.01) ) );
			Vec tp = Proj<4>::Call(5.0 , i);
			Vec to = Proj<4>::Ortho<3>(i);
			Draw( bOrtho ? to : tp );

		}
	  }

	if (h4){
		  for (auto &i : H4 ){
			if (bSpin) i = i.sp( Gen::rot( EGAMV<4, MV<12> > (.01) ) );
			Vec tp = Proj<4>::Call(5.0 , i);
			Vec to = Proj<4>::Ortho<3>(i);
			Draw( bOrtho ? to : tp );

		}
			  }

	text("Alt + Mouse to Rotate the Group\nShift + Mouse to Zoom in");
	}

};

MyApp * myApp;

int main(){

    cout << "D4: NumRoots =" << D4.size() << endl;
   for (auto i : D4 ){

	 i.vprint();

	}

	cout << "\nF4: NumRoots = " << F4.size() << endl;
   for (auto i : F4 ){

	 i.vprint();

	}

	cout << "\nH4: NumRoots = " << H4.size() << endl;
	   for (auto i : H4 ){

	 i.vprint();

	}

	GLV glv(0,0);

	Window * win = new Window(500,500,"4D ROOTS",&glv);
    myApp = new MyApp;
	myApp -> init( win );
	myApp -> initGui();

	glv << *myApp;

	Application::run();

	return 0;

}
<commit_msg>readme fix and xRoot fix<commit_after>#include "vsr_root.h"
#include "vsr_GLVimpl.h"
#include "vsr_ega3D_draw.h"

using namespace vsr;

typedef EGAMV< 4, Blade1<4>::VEC > V4;

//idositetrachoron 24 cell

auto D4 = Root::System( V4(1,0,0,0), V4(0,1,0,0), V4(0,0,1,0), ( V4(-1,-1,-1, 1) * .5 ) );

auto F4 = Root::System( V4(0,1,-1,0), V4(1,-1,0,0), V4(0,0,1,0), ( V4(-1,-1,-1, 1) * .5 ) );

auto H4 = Root::System( V4(0,-1,0,0), V4(0,1.618,1,-.618) * .5, V4(0,0,-1,0), ( V4(-.618,0,1, 1.618) * .5 ) );

struct MyApp : App {

	bool d4, f4, h4, bSpin, bOrtho;

	virtual void initGui(){
		gui(d4,"d4")(f4,"f4")(h4,"h4");
		gui(bSpin, "spin")(bOrtho, "ortho");
		d4 = true;
	}

	void onDraw(){

	  scene.camera.lens.bOrtho = bOrtho;

	  if (d4){
	   for (auto &i : D4 ){
			if (bSpin) i = i.sp( Gen::rot( EGAMV<4, MV<10,12> > (.01,.01) ) );
			Vec tp = Proj<4>::Call(5.0 , i);
			Vec to = Proj<4>::Ortho<3>(i);
			Draw( bOrtho ? to : tp );

		}
	  }

	  if (f4){
	   for (auto &i : F4 ){
			if (bSpin) i = i.sp( Gen::rot( EGAMV<4, MV<10,12> > (.01,.01) ) );
			Vec tp = Proj<4>::Call(5.0 , i);
			Vec to = Proj<4>::Ortho<3>(i);
			Draw( bOrtho ? to : tp );

		}
	  }

	if (h4){
		  for (auto &i : H4 ){
			if (bSpin) i = i.sp( Gen::rot( EGAMV<4, MV<12> > (.01) ) );
			Vec tp = Proj<4>::Call(5.0 , i);
			Vec to = Proj<4>::Ortho<3>(i);
			Draw( bOrtho ? to : tp );

		}
			  }

	text("Alt + Mouse to Rotate the Group\nShift + Mouse to Zoom in");
	}

};

MyApp * myApp;

int main(){

    cout << "D4: NumRoots =" << D4.size() << endl;
   for (auto i : D4 ){

	 i.vprint();

	}

	cout << "\nF4: NumRoots = " << F4.size() << endl;
   for (auto i : F4 ){

	 i.vprint();

	}

	cout << "\nH4: NumRoots = " << H4.size() << endl;
	   for (auto i : H4 ){

	 i.vprint();

	}

	GLV glv(0,0);

	Window * win = new Window(500,500,"4D ROOTS",&glv);
    myApp = new MyApp;
	myApp -> init( win );
	myApp -> initGui();

	glv << *myApp;

	Application::run();

	return 0;

}
<|endoftext|>


<commit_before>#ifndef ENEMY_H
#define ENEMY_H

#include <sprite.h>

class Enemy : public sprite
{
    public:
        Enemy();

        float Get_direction() {
            return direction;
        }
        void Set_direction(float val) {
            direction = val;
        }
        float Get_damageOnContact() {
            return damageOnContact;
        }
        void Set_damageOnContact(float val) {
            damageOnContact = val;
        }
        char Get_currentMove() {
            return aiMoveSequence[moveIndex];
        }
        void Set_moveSequence(char *sequence) {
            aiMoveSequence = sequence;
        }
        void move(){
        char curr = aiMoveSequence[moveIndex];
        switch(curr){
        {
          case 'A':
          case 'a':
          attack(); //TODO implement void method that deals damage to other entities.
          break;
          case 'U':
          case 'u':
          direction = 90; //Our coordinate grid starts at 0,0 in the top left corner.  Until someone changes it.
          yPosition-=1;
          break;
          case 'D':
          case 'd':
          direction = 270;
          yPosition+=1;
          break;
          case 'L':
          case 'l':
          direction = 180;
          xPosition-=1;
          break;
          case 'R':
          case 'r':
          direction = 0;
          xPosition+=1;
          break;
	        default:
	        cout<<"lol unidentified move in the array."
        }
        moveIndex++;
        if(moveIndex>=(sizeof(aiMoveSequence)/sizeof(aiMoveSequence[0]))){//If we're now outside the range of good values.
        moveIndex =0;
        }
        }

    private:
        float direction;
        float damageOnContact;
        char *aiMoveSequence;
        int moveIndex;
};

#endif // PLAYER_H
<commit_msg>Update enemy.hpp<commit_after>#ifndef ENEMY_H
#define ENEMY_H
#include <math.h>
#include <sprite.h>
#define PI 3.14159265

class Enemy : public sprite
{
    public:
        Enemy();

        float Get_direction() {
            return direction;
        }
        void Set_direction(float val) {
            direction = val;
        }
        float Get_damageOnContact() {
            return damageOnContact;
        }
        void Set_damageOnContact(float val) {
            damageOnContact = val;
        }
        char Get_currentMove() {
            return aiMoveSequence[moveIndex];
        }
        void Set_moveSequence(char *sequence) {
            aiMoveSequence = sequence;
        }
        void Set_player(Player player){
        	toChase = player;
        }
        void stepForward(){
        	if(direction==45)
        		direction+=(1.0-((double)rand(1))*2.0);
        	if(direction==135)
        		direction+=(1.0-((double)rand(1))*2.0);
        	if(direction==225)
        		direction+=(1.0-((double)rand(1))*2.0);
        	if(direction==315)
        		direction+=(1.0-((double)rand(1))*2.0); //Just some stupid tiebreaker code for 45 degree angle chases.
        	direction%=360;
        	if(direction<=45 || direction > 315)
        		xPosition++;
        	else if(direction<=135)
        		yPosition--;
        	else if(direction<=225)
        		xPosition--;
        	else if(direction<=315)
        		yPosition++;
        }
        double toPlayer(){//degrees
        //if y is negative and x isn't +270, both neg add 180, y pos x neg add 90.
        double x= toChase.xPosition - xPosition;
        double y= yPosition - toChase.yPosition;
        double r = (x*x + y*y)^(1.0/2.0);
   	double theta = acos(x/r)*180.0/PI;
        if(y>=0 && x<0) //Uh yeah someone check my work on this logic LOL
        	theta+=90.0;
        if(y<0 && x<0)
        	theta+=180.0;
        if(y<0 && x>=0)
        	theta+=270.0;
        }
        void move(){
        char curr = aiMoveSequence[moveIndex];
        switch(curr){
        {
          case 'A':
          case 'a':
          attack(); //TODO implement void method that deals damage to other entities.
          break;
          case 'C':
          case 'c':
          Set_direction(toPlayer());
          stepForward();
          break;
          case 'U':
          case 'u':
          direction = 90; //Our coordinate grid starts at 0,0 in the top left corner.  Until someone changes it.
          yPosition-=1;
          break;
          case 'D':
          case 'd':
          direction = 270;
          yPosition+=1;
          break;
          case 'L':
          case 'l':
          direction = 180;
          xPosition-=1;
          break;
          case 'R':
          case 'r':
          direction = 0;
          xPosition+=1;
          break;
	        default:
	        cout<<"lol unidentified move in the array."
        }
        moveIndex++;
        if(moveIndex>=(sizeof(aiMoveSequence)/sizeof(aiMoveSequence[0]))){//If we're now outside the range of good values.
        moveIndex =0;
        }
        }

    private:
        float direction;
        float damageOnContact;
        char *aiMoveSequence;
        int moveIndex;
        Player toChase;
};

#endif // PLAYER_H
<|endoftext|>


<commit_before>#include "sqlite.hpp"
#include "../File.hpp"
#include "../CriticalCode.hpp"
#include "../MemoryFile.hpp"
#include "../Exception.hpp"
#include <cstring>

BEGIN_INANITY_DATA

//*** SqliteDb

SqliteDb::Files SqliteDb::files;
CriticalSection SqliteDb::csFiles;

SqliteDb::SqliteDb(sqlite3* db) :
	db(db),
	stmtSavepoint(nullptr),
	stmtRelease(nullptr),
	stmtRollbackTo(nullptr)
{}

SqliteDb::~SqliteDb()
{
	if(stmtSavepoint)
		sqlite3_finalize(stmtSavepoint);
	if(stmtRelease)
		sqlite3_finalize(stmtRelease);
	if(stmtRollbackTo)
		sqlite3_finalize(stmtRollbackTo);

	sqlite3_close(db);
}

ptr<SqliteDb> SqliteDb::Open(const char* fileName)
{
	sqlite3* db;
	if(sqlite3_open(fileName, &db) != SQLITE_OK)
	{
		if(db)
			sqlite3_close(db);
		THROW("Can't open SQLite database");
	}

	return NEW(SqliteDb(db));
}

SqliteDb::operator sqlite3*() const
{
	return db;
}

void SqliteDb::AcquireFile(ptr<File> file)
{
	CriticalCode cc(csFiles);
	files.insert(std::make_pair(file->GetData(), file));
}

void SqliteDb::FreeFile(void* data)
{
	CriticalCode cc(csFiles);
	Files::iterator i = files.find(data);
	if(i == files.end())
		THROW("Invalid call of SqliteDb::FreeFile");
	files.erase(i);
}

ptr<SqliteStatement> SqliteDb::CreateStatement(const char* query)
{
	sqlite3_stmt* stmt;
	if(sqlite3_prepare_v2(db, query, -1, &stmt, nullptr) != SQLITE_OK)
		THROW_SECONDARY("Can't create SQLite statement", Error());
	return NEW(SqliteStatement(this, stmt));
}

long long SqliteDb::LastInsertRowId() const
{
	return sqlite3_last_insert_rowid(db);
}

ptr<Exception> SqliteDb::Error() const
{
	return NEW(Exception(sqlite3_errmsg(db)));
}

//*** SqliteStatement

SqliteStatement::SqliteStatement(ptr<SqliteDb> db, sqlite3_stmt* stmt)
: db(db), stmt(stmt) {}

SqliteStatement::~SqliteStatement()
{
	sqlite3_finalize(stmt);
}

void SqliteStatement::Bind(int number, const char* value)
{
	if(sqlite3_bind_text(stmt, number, value, -1, SQLITE_TRANSIENT) != SQLITE_OK)
		THROW_SECONDARY("Can't bind text to SQLite statement", db->Error());
}

void SqliteStatement::Bind(int number, const String& value)
{
	Bind(number, value.c_str());
}

void SqliteStatement::Bind(int number, int value)
{
	if(sqlite3_bind_int(stmt, number, value) != SQLITE_OK)
		THROW_SECONDARY("Can't bind int to SQLite statement", db->Error());
}

void SqliteStatement::Bind(int number, long long value)
{
	if(sqlite3_bind_int64(stmt, number, value) != SQLITE_OK)
		THROW_SECONDARY("Can't bind int64 to SQLite statement", db->Error());
}

void SqliteStatement::Bind(int number, const void* data, size_t size)
{
	if(sqlite3_bind_blob(stmt, number, data, (int)size, SQLITE_TRANSIENT) != SQLITE_OK)
		THROW_SECONDARY("Can't bind blob data to SqliteStatement", db->Error());
}

void SqliteStatement::Bind(int number, ptr<File> value)
{
	SqliteDb::AcquireFile(value);
	if(sqlite3_bind_blob(stmt, number, value->GetData(), (int)value->GetSize(), &SqliteDb::FreeFile) != SQLITE_OK)
		THROW_SECONDARY("Can't bind blob file to SQLite statement", db->Error());
}

void SqliteStatement::BindNull(int number)
{
	if(sqlite3_bind_null(stmt, number) != SQLITE_OK)
		THROW_SECONDARY("Can't bind null to SQLite statement", db->Error());
}

String SqliteStatement::ColumnText(int number) const
{
	return (const char*)sqlite3_column_text(stmt, number);
}

int SqliteStatement::ColumnInt(int number) const
{
	return sqlite3_column_int(stmt, number);
}

long long SqliteStatement::ColumnInt64(int number) const
{
	return sqlite3_column_int64(stmt, number);
}

ptr<File> SqliteStatement::ColumnBlob(int number) const
{
	int size = sqlite3_column_bytes(stmt, number);
	ptr<MemoryFile> file = NEW(MemoryFile(size));
	memcpy(file->GetData(), sqlite3_column_blob(stmt, number), size);
	return file;
}

size_t SqliteStatement::ColumnBlobSize(int number) const
{
	return sqlite3_column_bytes(stmt, number);
}

int SqliteStatement::Step()
{
	return sqlite3_step(stmt);
}

void SqliteStatement::Reset()
{
	sqlite3_reset(stmt);
	sqlite3_clear_bindings(stmt);
}

SqliteStatement::operator sqlite3_stmt*() const
{
	return stmt;
}

//*** SqliteQuery

SqliteQuery::SqliteQuery(ptr<SqliteStatement> statement)
: statement(statement) {}

SqliteQuery::~SqliteQuery()
{
	statement->Reset();
}

//*** SqliteTransaction

SqliteTransaction::SqliteTransaction(ptr<SqliteDb> db)
: db(db), finished(false)
{
	if(!db->stmtSavepoint)
	{
		if(sqlite3_prepare_v2(*db, "SAVEPOINT T", -1, &db->stmtSavepoint, nullptr) != SQLITE_OK)
			THROW_SECONDARY("Can't create SQLite SAVEPOINT statement", db->Error());
		if(sqlite3_prepare_v2(*db, "RELEASE T", -1, &db->stmtRelease, nullptr) != SQLITE_OK)
			THROW_SECONDARY("Can't create SQLite RELEASE statement", db->Error());
		if(sqlite3_prepare_v2(*db, "ROLLBACK TO T", -1, &db->stmtRollbackTo, nullptr) != SQLITE_OK)
			THROW_SECONDARY("Can't create SQLite ROLLBACK TO statement", db->Error());
	}

	sqlite3_reset(db->stmtSavepoint);
	if(sqlite3_step(db->stmtSavepoint) != SQLITE_DONE)
		THROW_SECONDARY("Can't make SQLite savepoint", db->Error());
}

SqliteTransaction::~SqliteTransaction()
{
	if(finished)
		return;

	sqlite3_reset(db->stmtRollbackTo);
	sqlite3_step(db->stmtRollbackTo);
	sqlite3_reset(db->stmtRelease);
	sqlite3_step(db->stmtRelease);
}

void SqliteTransaction::Commit()
{
	if(finished)
		THROW("Can't commit finished transaction");

	sqlite3_reset(db->stmtRelease);
	if(sqlite3_step(db->stmtRelease) != SQLITE_DONE)
		THROW_SECONDARY("Can't release savepoint", db->Error());

	finished = true;
}

END_INANITY_DATA
<commit_msg>better reporting SQLite errors<commit_after>#include "sqlite.hpp"
#include "../File.hpp"
#include "../CriticalCode.hpp"
#include "../MemoryFile.hpp"
#include "../Exception.hpp"
#include <sstream>
#include <cstring>

BEGIN_INANITY_DATA

//*** SqliteDb

SqliteDb::Files SqliteDb::files;
CriticalSection SqliteDb::csFiles;

SqliteDb::SqliteDb(sqlite3* db) :
	db(db),
	stmtSavepoint(nullptr),
	stmtRelease(nullptr),
	stmtRollbackTo(nullptr)
{}

SqliteDb::~SqliteDb()
{
	if(stmtSavepoint)
		sqlite3_finalize(stmtSavepoint);
	if(stmtRelease)
		sqlite3_finalize(stmtRelease);
	if(stmtRollbackTo)
		sqlite3_finalize(stmtRollbackTo);

	sqlite3_close(db);
}

ptr<SqliteDb> SqliteDb::Open(const char* fileName)
{
	sqlite3* db;
	if(sqlite3_open(fileName, &db) != SQLITE_OK)
	{
		if(db)
			sqlite3_close(db);
		THROW("Can't open SQLite database");
	}

	return NEW(SqliteDb(db));
}

SqliteDb::operator sqlite3*() const
{
	return db;
}

void SqliteDb::AcquireFile(ptr<File> file)
{
	CriticalCode cc(csFiles);
	files.insert(std::make_pair(file->GetData(), file));
}

void SqliteDb::FreeFile(void* data)
{
	CriticalCode cc(csFiles);
	Files::iterator i = files.find(data);
	if(i == files.end())
		THROW("Invalid call of SqliteDb::FreeFile");
	files.erase(i);
}

ptr<SqliteStatement> SqliteDb::CreateStatement(const char* query)
{
	sqlite3_stmt* stmt;
	if(sqlite3_prepare_v2(db, query, -1, &stmt, nullptr) != SQLITE_OK)
		THROW_SECONDARY("Can't create SQLite statement", Error());
	return NEW(SqliteStatement(this, stmt));
}

long long SqliteDb::LastInsertRowId() const
{
	return sqlite3_last_insert_rowid(db);
}

ptr<Exception> SqliteDb::Error() const
{
	std::ostringstream ss;
	ss << "SQLite error #" << sqlite3_errcode(db) << ": " << sqlite3_errmsg(db);
	return NEW(Exception(ss.str()));
}

//*** SqliteStatement

SqliteStatement::SqliteStatement(ptr<SqliteDb> db, sqlite3_stmt* stmt)
: db(db), stmt(stmt) {}

SqliteStatement::~SqliteStatement()
{
	sqlite3_finalize(stmt);
}

void SqliteStatement::Bind(int number, const char* value)
{
	if(sqlite3_bind_text(stmt, number, value, -1, SQLITE_TRANSIENT) != SQLITE_OK)
		THROW_SECONDARY("Can't bind text to SQLite statement", db->Error());
}

void SqliteStatement::Bind(int number, const String& value)
{
	Bind(number, value.c_str());
}

void SqliteStatement::Bind(int number, int value)
{
	if(sqlite3_bind_int(stmt, number, value) != SQLITE_OK)
		THROW_SECONDARY("Can't bind int to SQLite statement", db->Error());
}

void SqliteStatement::Bind(int number, long long value)
{
	if(sqlite3_bind_int64(stmt, number, value) != SQLITE_OK)
		THROW_SECONDARY("Can't bind int64 to SQLite statement", db->Error());
}

void SqliteStatement::Bind(int number, const void* data, size_t size)
{
	if(sqlite3_bind_blob(stmt, number, data, (int)size, SQLITE_TRANSIENT) != SQLITE_OK)
		THROW_SECONDARY("Can't bind blob data to SqliteStatement", db->Error());
}

void SqliteStatement::Bind(int number, ptr<File> value)
{
	SqliteDb::AcquireFile(value);
	if(sqlite3_bind_blob(stmt, number, value->GetData(), (int)value->GetSize(), &SqliteDb::FreeFile) != SQLITE_OK)
		THROW_SECONDARY("Can't bind blob file to SQLite statement", db->Error());
}

void SqliteStatement::BindNull(int number)
{
	if(sqlite3_bind_null(stmt, number) != SQLITE_OK)
		THROW_SECONDARY("Can't bind null to SQLite statement", db->Error());
}

String SqliteStatement::ColumnText(int number) const
{
	return (const char*)sqlite3_column_text(stmt, number);
}

int SqliteStatement::ColumnInt(int number) const
{
	return sqlite3_column_int(stmt, number);
}

long long SqliteStatement::ColumnInt64(int number) const
{
	return sqlite3_column_int64(stmt, number);
}

ptr<File> SqliteStatement::ColumnBlob(int number) const
{
	int size = sqlite3_column_bytes(stmt, number);
	ptr<MemoryFile> file = NEW(MemoryFile(size));
	memcpy(file->GetData(), sqlite3_column_blob(stmt, number), size);
	return file;
}

size_t SqliteStatement::ColumnBlobSize(int number) const
{
	return sqlite3_column_bytes(stmt, number);
}

int SqliteStatement::Step()
{
	return sqlite3_step(stmt);
}

void SqliteStatement::Reset()
{
	sqlite3_reset(stmt);
	sqlite3_clear_bindings(stmt);
}

SqliteStatement::operator sqlite3_stmt*() const
{
	return stmt;
}

//*** SqliteQuery

SqliteQuery::SqliteQuery(ptr<SqliteStatement> statement)
: statement(statement) {}

SqliteQuery::~SqliteQuery()
{
	statement->Reset();
}

//*** SqliteTransaction

SqliteTransaction::SqliteTransaction(ptr<SqliteDb> db)
: db(db), finished(false)
{
	if(!db->stmtSavepoint)
	{
		if(sqlite3_prepare_v2(*db, "SAVEPOINT T", -1, &db->stmtSavepoint, nullptr) != SQLITE_OK)
			THROW_SECONDARY("Can't create SQLite SAVEPOINT statement", db->Error());
		if(sqlite3_prepare_v2(*db, "RELEASE T", -1, &db->stmtRelease, nullptr) != SQLITE_OK)
			THROW_SECONDARY("Can't create SQLite RELEASE statement", db->Error());
		if(sqlite3_prepare_v2(*db, "ROLLBACK TO T", -1, &db->stmtRollbackTo, nullptr) != SQLITE_OK)
			THROW_SECONDARY("Can't create SQLite ROLLBACK TO statement", db->Error());
	}

	sqlite3_reset(db->stmtSavepoint);
	if(sqlite3_step(db->stmtSavepoint) != SQLITE_DONE)
		THROW_SECONDARY("Can't make SQLite savepoint", db->Error());
}

SqliteTransaction::~SqliteTransaction()
{
	if(finished)
		return;

	sqlite3_reset(db->stmtRollbackTo);
	sqlite3_step(db->stmtRollbackTo);
	sqlite3_reset(db->stmtRelease);
	sqlite3_step(db->stmtRelease);
}

void SqliteTransaction::Commit()
{
	if(finished)
		THROW("Can't commit finished transaction");

	sqlite3_reset(db->stmtRelease);
	if(sqlite3_step(db->stmtRelease) != SQLITE_DONE)
		THROW_SECONDARY("Can't release savepoint", db->Error());

	finished = true;
}

END_INANITY_DATA
<|endoftext|>


<commit_before>#pragma ident "$Id$"

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk 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
//  any later version.
//
//  The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Copyright 2004, The University of Texas at Austin
//
//============================================================================

#include "ANSITime.hpp"
#include "TimeConstants.hpp"

namespace gpstk
{
   ANSITime& ANSITime::operator=( const ANSITime& right )
      throw()
   {
      time = right.time;
      return *this;
   }

   CommonTime ANSITime::convertToCommonTime() const
   {
      return CommonTime( ( MJD_JDAY + UNIX_MJD + time / SEC_PER_DAY ),
                         ( time % SEC_PER_DAY ),
                         0 );
   }

   void ANSITime::convertFromCommonTime( const CommonTime& ct )
   {
      long jday, sod;
      double fsod;
      ct.get( jday, sod, fsod );

      time =
         static_cast<time_t>((jday - MJD_JDAY - UNIX_MJD) * SEC_PER_DAY + sod);
   }

   std::string ANSITime::printf( const std::string& fmt ) const
      throw( gpstk::StringUtils::StringException )
   {
      try
      {
         using gpstk::StringUtils::formattedPrint;
         std::string rv( fmt );

         rv = formattedPrint( rv, getFormatPrefixInt() + "K",
                              "Kd", time );

         return rv;
      }
      catch( gpstk::StringUtils::StringException& se )
      {
         GPSTK_RETHROW( se );
      }
   }

   bool ANSITime::setFromInfo( const IdToValue& info )
      throw()
   {
      using namespace gpstk::StringUtils;

      IdToValue::const_iterator i = info.find('K');
      if( i != info.end() )
      {
         time = asInt( i->second );
         return true;
      }

      return false;
   }

   bool ANSITime::isValid() const
      throw()
   {
      ANSITime temp;
      temp.convertFromCommonTime( convertToCommonTime() );
      if( *this == temp )
      {
         return true;
      }
      return false;
   }

   void ANSITime::reset()
      throw()
   {
      time = 0;
   }

   bool ANSITime::operator==( const ANSITime& right ) const
      throw()
   {
      if( time == right.time )
      {
         return true;
      }
      return false;
   }

   bool ANSITime::operator!=( const ANSITime& right ) const
      throw()
   {
      return ( !operator==( right ) );
   }

   bool ANSITime::operator<( const ANSITime& right ) const
      throw()
   {
      return ( time < right.time );
   }

   bool ANSITime::operator>( const ANSITime& right ) const
      throw()
   {
      return ( !operator<=( right ) );
   }

   bool ANSITime::operator<=( const ANSITime& right ) const
      throw()
   {
      return ( operator<( right ) ||
               operator==( right ) );
   }

   bool ANSITime::operator>=( const ANSITime& right ) const
      throw()
   {
      return ( !operator<( right ) );
   }

} // namespace
<commit_msg>Modified ANSITime to not check values scanned in setFromInfo().<commit_after>#pragma ident "$Id$"

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk 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
//  any later version.
//
//  The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Copyright 2004, The University of Texas at Austin
//
//============================================================================

#include "ANSITime.hpp"
#include "TimeConstants.hpp"

namespace gpstk
{
   ANSITime& ANSITime::operator=( const ANSITime& right )
      throw()
   {
      time = right.time;
      return *this;
   }

   CommonTime ANSITime::convertToCommonTime() const
   {
      return CommonTime( ( MJD_JDAY + UNIX_MJD + time / SEC_PER_DAY ),
                         ( time % SEC_PER_DAY ),
                         0 );
   }

   void ANSITime::convertFromCommonTime( const CommonTime& ct )
   {
      long jday, sod;
      double fsod;
      ct.get( jday, sod, fsod );

      time =
         static_cast<time_t>((jday - MJD_JDAY - UNIX_MJD) * SEC_PER_DAY + sod);
   }

   std::string ANSITime::printf( const std::string& fmt ) const
      throw( gpstk::StringUtils::StringException )
   {
      try
      {
         using gpstk::StringUtils::formattedPrint;
         std::string rv( fmt );

         rv = formattedPrint( rv, getFormatPrefixInt() + "K",
                              "Kd", time );

         return rv;
      }
      catch( gpstk::StringUtils::StringException& se )
      {
         GPSTK_RETHROW( se );
      }
   }

   bool ANSITime::setFromInfo( const IdToValue& info )
      throw()
   {
      using namespace gpstk::StringUtils;

      IdToValue::const_iterator i = info.find('K');
      if( i != info.end() )
      {
         time = asInt( i->second );
      }

      return true;
   }

   bool ANSITime::isValid() const
      throw()
   {
      ANSITime temp;
      temp.convertFromCommonTime( convertToCommonTime() );
      if( *this == temp )
      {
         return true;
      }
      return false;
   }

   void ANSITime::reset()
      throw()
   {
      time = 0;
   }

   bool ANSITime::operator==( const ANSITime& right ) const
      throw()
   {
      if( time == right.time )
      {
         return true;
      }
      return false;
   }

   bool ANSITime::operator!=( const ANSITime& right ) const
      throw()
   {
      return ( !operator==( right ) );
   }

   bool ANSITime::operator<( const ANSITime& right ) const
      throw()
   {
      return ( time < right.time );
   }

   bool ANSITime::operator>( const ANSITime& right ) const
      throw()
   {
      return ( !operator<=( right ) );
   }

   bool ANSITime::operator<=( const ANSITime& right ) const
      throw()
   {
      return ( operator<( right ) ||
               operator==( right ) );
   }

   bool ANSITime::operator>=( const ANSITime& right ) const
      throw()
   {
      return ( !operator<( right ) );
   }

} // namespace
<|endoftext|>


<commit_before>#include "EpsilonDashboard.h"
#include <QApplication>
#include <QLockFile>
#include <QDebug>
#include <QDir>

int main(int argc, char* argv[])
{
    QString tmpDir = QDir::tempPath();
    QLockFile lockFile(tmpDir + "/epsilonDashboard.lock");

    /* Trying to close the Lock File, if the attempt is unsuccessful for 100 milliseconds,
     * then there is a Lock File already created by another process.
     * Therefore, we issue a warning and close the program
     */
    if(!lockFile.tryLock(100)){
        qDebug()<<"An instance of dashboard already exists.\n Quitting...\n";
        return 1;
    }
    else{
        qDebug()<<"No other instance of dashboard. Launching dashboard...\n";
    }

    QScopedPointer<EpsilonDashboard> app;
    app.reset(new EpsilonDashboard(argc, argv));
    return app->exec();
}
<commit_msg>Ran format<commit_after>#include "EpsilonDashboard.h"
#include <QApplication>
#include <QLockFile>
#include <QDebug>
#include <QDir>

int main(int argc, char* argv[])
{
    QString tmpDir = QDir::tempPath();
    QLockFile lockFile(tmpDir + "/epsilonDashboard.lock");

    /* Trying to close the Lock File, if the attempt is unsuccessful for 100 milliseconds,
     * then there is a Lock File already created by another process.
     * Therefore, we issue a warning and close the program
     */
    if (!lockFile.tryLock(100))
    {
        qDebug() << "An instance of dashboard already exists.\nQuitting...\n";
        return 1;
    }
    else
    {
        qDebug() << "No other instance of dashboard exists.\nLaunching dashboard...\n";
    }

    QScopedPointer<EpsilonDashboard> app;
    app.reset(new EpsilonDashboard(argc, argv));
    return app->exec();
}
<|endoftext|>