<commit_before>#include "platform/platform.hpp"
#include "platform/platform_unix_impl.hpp"
#include "platform/constants.hpp"
#include "platform/settings.hpp"

#include "coding/zip_reader.hpp"
#include "coding/file_name_utils.hpp"

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

#include <unistd.h>     // for sysconf
#include <sys/stat.h>

Platform::Platform()
{
  /// @see initialization routine in android/jni/com/.../Platform.hpp
}

namespace
{
enum SourceT
{
  EXTERNAL_RESOURCE,
  RESOURCE,
  WRITABLE_PATH,
  SETTINGS_PATH,
  FULL_PATH,
  SOURCE_COUNT
};

bool IsResource(string const & file, string const & ext)
{
  if (ext == DATA_FILE_EXTENSION)
  {
    return (strings::StartsWith(file, WORLD_COASTS_FILE_NAME) ||
            strings::StartsWith(file, WORLD_FILE_NAME));
  }
  else if (ext == BOOKMARKS_FILE_EXTENSION ||
           ext == ROUTING_FILE_EXTENSION ||
           file == SETTINGS_FILE_NAME)
  {
    return false;
  }

  return true;
}

size_t GetSearchSources(string const & file, string const & searchScope,
                        SourceT (&arr)[SOURCE_COUNT])
{
  size_t ret = 0;

  for (size_t i = 0; i < searchScope.size(); ++i)
  {
    switch (searchScope[i])
    {
    case 'w': arr[ret++] = WRITABLE_PATH; break;
    case 'r': arr[ret++] = RESOURCE; break;
    case 'e': arr[ret++] = EXTERNAL_RESOURCE; break;
    case 's': arr[ret++] = SETTINGS_PATH; break;
    case 'f':
      if (strings::StartsWith(file, "/"))
        arr[ret++] = FULL_PATH;
      break;
    default : CHECK(false, ("Unsupported searchScope:", searchScope)); break;
    }
  }

  return ret;
}

#ifdef DEBUG
class DbgLogger
{
  string const & m_file;
  SourceT m_src;
public:
  DbgLogger(string const & file) : m_file(file) {}
  void SetSource(SourceT src) { m_src = src; }
  ~DbgLogger()
  {
    LOG(LDEBUG, ("Source for file", m_file, "is", m_src));
  }
};
#endif

}

ModelReader * Platform::GetReader(string const & file, string const & searchScope) const
{
  string const ext = my::GetFileExtension(file);
  ASSERT(!ext.empty(), ());

  uint32_t const logPageSize = (ext == DATA_FILE_EXTENSION) ? READER_CHUNK_LOG_SIZE : 10;
  uint32_t const logPageCount = (ext == DATA_FILE_EXTENSION) ? READER_CHUNK_LOG_COUNT : 4;

  SourceT sources[SOURCE_COUNT];
  size_t n = 0;

  if (searchScope.empty())
  {
    // Default behaviour - use predefined scope for resource files and writable path for all others.

    if (IsResource(file, ext))
      n = GetSearchSources(file, m_androidDefResScope, sources);
    else
    {
      // Add source for map files and other dynamic stored data.
      sources[n++] = WRITABLE_PATH;
    }
  }
  else
  {
    // Use passed scope as client wishes.
    n = GetSearchSources(file, searchScope, sources);
  }

#ifdef DEBUG
  DbgLogger logger(file);
#endif

  for (size_t i = 0; i < n; ++i)
  {
#ifdef DEBUG
    logger.SetSource(sources[i]);
#endif

    switch (sources[i])
    {
    case EXTERNAL_RESOURCE:
      for (size_t j = 0; j < m_extResFiles.size(); ++j)
      {
        try
        {
          return new ZipFileReader(m_extResFiles[j], file, logPageSize, logPageCount);
        }
        catch (Reader::OpenException const &)
        {
        }
      }
      break;

    case WRITABLE_PATH:
    {
      string const path = m_writableDir + file;
      if (IsFileExistsByFullPath(path))
        return new FileReader(path, logPageSize, logPageCount);
      break;
    }

    case SETTINGS_PATH:
    {
      string const path = m_settingsDir + file;
      if (IsFileExistsByFullPath(path))
        return new FileReader(path, logPageSize, logPageCount);
      break;
    }

    case FULL_PATH:
      if (IsFileExistsByFullPath(file))
        return new FileReader(file, logPageSize, logPageCount);
      break;

    case RESOURCE:
      ASSERT_EQUAL(file.find("assets/"), string::npos, ());
      try
      {
        return new ZipFileReader(m_resourcesDir, "assets/" + file, logPageSize, logPageCount);
      }
      catch (Reader::OpenException const &)
      {
      }
      break;

    default:
      CHECK(false, ("Unsupported source:", sources[i]));
      break;
    }
  }

  LOG(LERROR, ("Can't get reader for:", file));
  MYTHROW(FileAbsentException, ("File not found", file));
  return 0;
}

void Platform::GetFilesByRegExp(string const & directory, string const & regexp, FilesList & res)
{
  if (ZipFileReader::IsZip(directory))
  {
    // Get files list inside zip file
    typedef ZipFileReader::FileListT FilesT;
    FilesT fList;
    ZipFileReader::FilesList(directory, fList);

    regexp::RegExpT exp;
    regexp::Create(regexp, exp);

    for (FilesT::iterator it = fList.begin(); it != fList.end(); ++it)
    {
      string & name = it->first;
      if (regexp::IsExist(name, exp))
      {
        // Remove assets/ prefix - clean files are needed for fonts white/blacklisting logic
        size_t const ASSETS_LENGTH = 7;
        if (name.find("assets/") == 0)
          name.erase(0, ASSETS_LENGTH);

        res.push_back(name);
      }
    }
  }
  else
    pl::EnumerateFilesByRegExp(directory, regexp, res);
}

int Platform::CpuCores() const
{
  static long const numCPU = sysconf(_SC_NPROCESSORS_CONF);

  // for debugging only. _SC_NPROCESSORS_ONLN could change, so
  // we should test whether _SC_NPROCESSORS_CONF could change too

  long const newNumCPU = sysconf(_SC_NPROCESSORS_CONF);

  if (newNumCPU != numCPU)
    LOG(LWARNING, ("initially retrived", numCPU, "and now got", newNumCPU, "processors"));

  return (numCPU > 1 ? static_cast<int>(numCPU) : 1);
}

int Platform::VideoMemoryLimit() const
{
  return 10 * 1024 * 1024;
}

int Platform::PreCachingDepth() const
{
  return 3;
}

bool Platform::GetFileSizeByName(string const & fileName, uint64_t & size) const
{
  try
  {
    size = ReaderPtr<Reader>(GetReader(fileName)).Size();
    return true;
  }
  catch (RootException const & ex)
  {
    LOG(LWARNING, ("Can't get file size for:", fileName));
    return false;
  }
}

Platform::EError Platform::MkDir(string const & dirName) const
{
  if (mkdir(dirName.c_str(), 0755))
  {
    LOG(LWARNING, ("Can't create directory: ", dirName));
    return ErrnoToError();
  }
  return Platform::ERR_OK;
}

void Platform::SetupMeasurementSystem() const
{
  Settings::Units u;
  if (Settings::Get("Units", u))
    return;
  // @TODO Add correct implementation
  u = Settings::Metric;
  Settings::Set("Units", u);
}

namespace
{
class FunctorWrapper : public threads::IRoutine
{
  Platform::TFunctor m_fn;

public:
  FunctorWrapper(Platform::TFunctor const & fn) : m_fn(fn) {}

  void Do() override { m_fn(); }
};
}

void Platform::RunAsync(TFunctor const & fn, Priority p)
{
  UNUSED_VALUE(p);

  // We don't need to store thread handler in POSIX, just create and
  // run.  Unfortunately we can't use std::async() here since it
  // doesn't attach to JVM threads.
  threads::Thread().Create(make_unique<FunctorWrapper>(fn));
}
<commit_msg>Supressing excess warnings on directory creation API.<commit_after>#include "platform/platform.hpp"
#include "platform/platform_unix_impl.hpp"
#include "platform/constants.hpp"
#include "platform/settings.hpp"

#include "coding/zip_reader.hpp"
#include "coding/file_name_utils.hpp"

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

#include <unistd.h>     // for sysconf
#include <sys/stat.h>

Platform::Platform()
{
  /// @see initialization routine in android/jni/com/.../Platform.hpp
}

namespace
{
enum SourceT
{
  EXTERNAL_RESOURCE,
  RESOURCE,
  WRITABLE_PATH,
  SETTINGS_PATH,
  FULL_PATH,
  SOURCE_COUNT
};

bool IsResource(string const & file, string const & ext)
{
  if (ext == DATA_FILE_EXTENSION)
  {
    return (strings::StartsWith(file, WORLD_COASTS_FILE_NAME) ||
            strings::StartsWith(file, WORLD_FILE_NAME));
  }
  else if (ext == BOOKMARKS_FILE_EXTENSION ||
           ext == ROUTING_FILE_EXTENSION ||
           file == SETTINGS_FILE_NAME)
  {
    return false;
  }

  return true;
}

size_t GetSearchSources(string const & file, string const & searchScope,
                        SourceT (&arr)[SOURCE_COUNT])
{
  size_t ret = 0;

  for (size_t i = 0; i < searchScope.size(); ++i)
  {
    switch (searchScope[i])
    {
    case 'w': arr[ret++] = WRITABLE_PATH; break;
    case 'r': arr[ret++] = RESOURCE; break;
    case 'e': arr[ret++] = EXTERNAL_RESOURCE; break;
    case 's': arr[ret++] = SETTINGS_PATH; break;
    case 'f':
      if (strings::StartsWith(file, "/"))
        arr[ret++] = FULL_PATH;
      break;
    default : CHECK(false, ("Unsupported searchScope:", searchScope)); break;
    }
  }

  return ret;
}

#ifdef DEBUG
class DbgLogger
{
  string const & m_file;
  SourceT m_src;
public:
  DbgLogger(string const & file) : m_file(file) {}
  void SetSource(SourceT src) { m_src = src; }
  ~DbgLogger()
  {
    LOG(LDEBUG, ("Source for file", m_file, "is", m_src));
  }
};
#endif

}

ModelReader * Platform::GetReader(string const & file, string const & searchScope) const
{
  string const ext = my::GetFileExtension(file);
  ASSERT(!ext.empty(), ());

  uint32_t const logPageSize = (ext == DATA_FILE_EXTENSION) ? READER_CHUNK_LOG_SIZE : 10;
  uint32_t const logPageCount = (ext == DATA_FILE_EXTENSION) ? READER_CHUNK_LOG_COUNT : 4;

  SourceT sources[SOURCE_COUNT];
  size_t n = 0;

  if (searchScope.empty())
  {
    // Default behaviour - use predefined scope for resource files and writable path for all others.

    if (IsResource(file, ext))
      n = GetSearchSources(file, m_androidDefResScope, sources);
    else
    {
      // Add source for map files and other dynamic stored data.
      sources[n++] = WRITABLE_PATH;
    }
  }
  else
  {
    // Use passed scope as client wishes.
    n = GetSearchSources(file, searchScope, sources);
  }

#ifdef DEBUG
  DbgLogger logger(file);
#endif

  for (size_t i = 0; i < n; ++i)
  {
#ifdef DEBUG
    logger.SetSource(sources[i]);
#endif

    switch (sources[i])
    {
    case EXTERNAL_RESOURCE:
      for (size_t j = 0; j < m_extResFiles.size(); ++j)
      {
        try
        {
          return new ZipFileReader(m_extResFiles[j], file, logPageSize, logPageCount);
        }
        catch (Reader::OpenException const &)
        {
        }
      }
      break;

    case WRITABLE_PATH:
    {
      string const path = m_writableDir + file;
      if (IsFileExistsByFullPath(path))
        return new FileReader(path, logPageSize, logPageCount);
      break;
    }

    case SETTINGS_PATH:
    {
      string const path = m_settingsDir + file;
      if (IsFileExistsByFullPath(path))
        return new FileReader(path, logPageSize, logPageCount);
      break;
    }

    case FULL_PATH:
      if (IsFileExistsByFullPath(file))
        return new FileReader(file, logPageSize, logPageCount);
      break;

    case RESOURCE:
      ASSERT_EQUAL(file.find("assets/"), string::npos, ());
      try
      {
        return new ZipFileReader(m_resourcesDir, "assets/" + file, logPageSize, logPageCount);
      }
      catch (Reader::OpenException const &)
      {
      }
      break;

    default:
      CHECK(false, ("Unsupported source:", sources[i]));
      break;
    }
  }

  LOG(LERROR, ("Can't get reader for:", file));
  MYTHROW(FileAbsentException, ("File not found", file));
  return 0;
}

void Platform::GetFilesByRegExp(string const & directory, string const & regexp, FilesList & res)
{
  if (ZipFileReader::IsZip(directory))
  {
    // Get files list inside zip file
    typedef ZipFileReader::FileListT FilesT;
    FilesT fList;
    ZipFileReader::FilesList(directory, fList);

    regexp::RegExpT exp;
    regexp::Create(regexp, exp);

    for (FilesT::iterator it = fList.begin(); it != fList.end(); ++it)
    {
      string & name = it->first;
      if (regexp::IsExist(name, exp))
      {
        // Remove assets/ prefix - clean files are needed for fonts white/blacklisting logic
        size_t const ASSETS_LENGTH = 7;
        if (name.find("assets/") == 0)
          name.erase(0, ASSETS_LENGTH);

        res.push_back(name);
      }
    }
  }
  else
    pl::EnumerateFilesByRegExp(directory, regexp, res);
}

int Platform::CpuCores() const
{
  static long const numCPU = sysconf(_SC_NPROCESSORS_CONF);

  // for debugging only. _SC_NPROCESSORS_ONLN could change, so
  // we should test whether _SC_NPROCESSORS_CONF could change too

  long const newNumCPU = sysconf(_SC_NPROCESSORS_CONF);

  if (newNumCPU != numCPU)
    LOG(LWARNING, ("initially retrived", numCPU, "and now got", newNumCPU, "processors"));

  return (numCPU > 1 ? static_cast<int>(numCPU) : 1);
}

int Platform::VideoMemoryLimit() const
{
  return 10 * 1024 * 1024;
}

int Platform::PreCachingDepth() const
{
  return 3;
}

bool Platform::GetFileSizeByName(string const & fileName, uint64_t & size) const
{
  try
  {
    size = ReaderPtr<Reader>(GetReader(fileName)).Size();
    return true;
  }
  catch (RootException const & ex)
  {
    LOG(LWARNING, ("Can't get file size for:", fileName));
    return false;
  }
}

Platform::EError Platform::MkDir(string const & dirName) const
{
  if (mkdir(dirName.c_str(), 0755))
    return ErrnoToError();
  return Platform::ERR_OK;
}

void Platform::SetupMeasurementSystem() const
{
  Settings::Units u;
  if (Settings::Get("Units", u))
    return;
  // @TODO Add correct implementation
  u = Settings::Metric;
  Settings::Set("Units", u);
}

namespace
{
class FunctorWrapper : public threads::IRoutine
{
  Platform::TFunctor m_fn;

public:
  FunctorWrapper(Platform::TFunctor const & fn) : m_fn(fn) {}

  void Do() override { m_fn(); }
};
}

void Platform::RunAsync(TFunctor const & fn, Priority p)
{
  UNUSED_VALUE(p);

  // We don't need to store thread handler in POSIX, just create and
  // run.  Unfortunately we can't use std::async() here since it
  // doesn't attach to JVM threads.
  threads::Thread().Create(make_unique<FunctorWrapper>(fn));
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
#include "shape_featureset.hpp"
#include "shape_index_featureset.hpp"

#include "shape.hpp"

DATASOURCE_PLUGIN(shape_datasource)

shape_datasource::shape_datasource(const parameters &params)
   : datasource (params) ,
     shape_name_(params.get("file")),
     type_(datasource::Vector),
     file_length_(0),
     indexed_(false),
     desc_(params.get("name"),"utf-8")
{
   try
   {
      std::string encoding = params.get("encoding");
      if (encoding.length() > 0) desc_.set_encoding(encoding);
      shape_io shape(shape_name_);
      init(shape);
      for (int i=0;i<shape.dbf().num_fields();++i)
      {
         field_descriptor const& fd=shape.dbf().descriptor(i);
         std::string fld_name=fd.name_;
         switch (fd.type_)
         {
            case 'C':
            case 'D':
            case 'M':
            case 'L':
               desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
               break;
            case 'N':
            case 'F':
            {
               if (fd.dec_>0)
               {
                  desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,8));
               }
               else
               {
                  desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,4));
               }
               break;
            }
            default:
#ifdef MAPNIK_DEBUG
               std::clog << "unknown type "<<fd.type_<<"\n";
#endif
               break;
         }
      }
   }
   catch  (datasource_exception& ex)
   {
      std::clog<<ex.what()<<std::endl;
      throw;
   }
}

shape_datasource::~shape_datasource()
{
}

const std::string shape_datasource::name_="shape";

void  shape_datasource::init(shape_io& shape)
{
   //first read header from *.shp
   int file_code=shape.shp().read_xdr_integer();
   if (file_code!=9994)
   {
      //invalid
      throw datasource_exception("wrong file code");
   }
   shape.shp().skip(5*4);
   file_length_=shape.shp().read_xdr_integer();
   int version=shape.shp().read_ndr_integer();
   if (version!=1000)
   {
      //invalid version number
      throw datasource_exception("invalid version number");
   }
#ifdef MAPNIK_DEBUG
   int shape_type = shape.shp().read_ndr_integer();
#else
   shape.shp().skip(4);
#endif
   shape.shp().read_envelope(extent_);
   shape.shp().skip(4*8);

   // check if we have an index file around
   std::string index_name(shape_name_+".index");
   std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary);
   if (file)
   {
      indexed_=true;
      file.close();
   }

#ifdef MAPNIK_DEBUG
   int shape_type = shape.shp().read_ndr_integer();
   std::clog << extent_ << std::endl;
   std::clog << "file_length=" << file_length_ << std::endl;
   std::clog << "shape_type=" << shape_type << std::endl;
#endif

}

int shape_datasource::type() const
{
   return type_;
}

layer_descriptor shape_datasource::get_descriptor() const
{
   return desc_;
}

std::string shape_datasource::name()
{
   return name_;
}

featureset_ptr shape_datasource::features(const query& q) const
{
   filter_in_box filter(q.get_bbox());
   if (indexed_)
   {
      return featureset_ptr
         (new shape_index_featureset<filter_in_box>(filter,
                                                    shape_name_,
                                                    q.property_names(),
                                                    desc_.get_encoding()));
   }
   else
   {
      return featureset_ptr
         (new shape_featureset<filter_in_box>(filter,
                                              shape_name_,
                                              q.property_names(),
                                              desc_.get_encoding(),
                                              file_length_));
   }
}

featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const
{
   filter_at_point filter(pt);
   // collect all attribute names
   std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors();
   std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
   std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
   std::set<std::string> names;

   while (itr != end)
   {
      names.insert(itr->get_name());
      ++itr;
   }

   if (indexed_)
   {
      return featureset_ptr
         (new shape_index_featureset<filter_at_point>(filter,
                                                      shape_name_,
                                                      names,
                                                      desc_.get_encoding()));
   }
   else
   {
      return featureset_ptr
         (new shape_featureset<filter_at_point>(filter,
                                                shape_name_,
                                                names,
                                                desc_.get_encoding(),
                                                file_length_));
   }
}

Envelope<double> shape_datasource::envelope() const
{
   return extent_;
}
<commit_msg>and another one :)<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
#include "shape_featureset.hpp"
#include "shape_index_featureset.hpp"

#include "shape.hpp"

DATASOURCE_PLUGIN(shape_datasource)

shape_datasource::shape_datasource(const parameters &params)
   : datasource (params) ,
     shape_name_(params.get("file")),
     type_(datasource::Vector),
     file_length_(0),
     indexed_(false),
     desc_(params.get("name"),"utf-8")
{
   try
   {
      std::string encoding = params.get("encoding");
      if (encoding.length() > 0) desc_.set_encoding(encoding);
      shape_io shape(shape_name_);
      init(shape);
      for (int i=0;i<shape.dbf().num_fields();++i)
      {
         field_descriptor const& fd=shape.dbf().descriptor(i);
         std::string fld_name=fd.name_;
         switch (fd.type_)
         {
            case 'C':
            case 'D':
            case 'M':
            case 'L':
               desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
               break;
            case 'N':
            case 'F':
            {
               if (fd.dec_>0)
               {
                  desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,8));
               }
               else
               {
                  desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,4));
               }
               break;
            }
            default:
#ifdef MAPNIK_DEBUG
               std::clog << "unknown type "<<fd.type_<<"\n";
#endif
               break;
         }
      }
   }
   catch  (datasource_exception& ex)
   {
      std::clog<<ex.what()<<std::endl;
      throw;
   }
}

shape_datasource::~shape_datasource()
{
}

const std::string shape_datasource::name_="shape";

void  shape_datasource::init(shape_io& shape)
{
   //first read header from *.shp
   int file_code=shape.shp().read_xdr_integer();
   if (file_code!=9994)
   {
      //invalid
      throw datasource_exception("wrong file code");
   }
   shape.shp().skip(5*4);
   file_length_=shape.shp().read_xdr_integer();
   int version=shape.shp().read_ndr_integer();
   if (version!=1000)
   {
      //invalid version number
      throw datasource_exception("invalid version number");
   }
#ifdef MAPNIK_DEBUG
   int shape_type = shape.shp().read_ndr_integer();
#else
   shape.shp().skip(4);
#endif
   shape.shp().read_envelope(extent_);
   shape.shp().skip(4*8);

   // check if we have an index file around
   std::string index_name(shape_name_+".index");
   std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary);
   if (file)
   {
      indexed_=true;
      file.close();
   }

#ifdef MAPNIK_DEBUG
   std::clog << extent_ << std::endl;
   std::clog << "file_length=" << file_length_ << std::endl;
   std::clog << "shape_type=" << shape_type << std::endl;
#endif

}

int shape_datasource::type() const
{
   return type_;
}

layer_descriptor shape_datasource::get_descriptor() const
{
   return desc_;
}

std::string shape_datasource::name()
{
   return name_;
}

featureset_ptr shape_datasource::features(const query& q) const
{
   filter_in_box filter(q.get_bbox());
   if (indexed_)
   {
      return featureset_ptr
         (new shape_index_featureset<filter_in_box>(filter,
                                                    shape_name_,
                                                    q.property_names(),
                                                    desc_.get_encoding()));
   }
   else
   {
      return featureset_ptr
         (new shape_featureset<filter_in_box>(filter,
                                              shape_name_,
                                              q.property_names(),
                                              desc_.get_encoding(),
                                              file_length_));
   }
}

featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const
{
   filter_at_point filter(pt);
   // collect all attribute names
   std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors();
   std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
   std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
   std::set<std::string> names;

   while (itr != end)
   {
      names.insert(itr->get_name());
      ++itr;
   }

   if (indexed_)
   {
      return featureset_ptr
         (new shape_index_featureset<filter_at_point>(filter,
                                                      shape_name_,
                                                      names,
                                                      desc_.get_encoding()));
   }
   else
   {
      return featureset_ptr
         (new shape_featureset<filter_at_point>(filter,
                                                shape_name_,
                                                names,
                                                desc_.get_encoding(),
                                                file_length_));
   }
}

Envelope<double> shape_datasource::envelope() const
{
   return extent_;
}
<|endoftext|>


<commit_before>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 1.0.0, packaged on August, 2008.

 http://glc-lib.sourceforge.net

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

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

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

//! \file glc_light.cpp implementation of the GLC_Light class.

#include "glc_light.h"
#include "glc_openglexception.h"

#include <QtDebug>

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light()
:GLC_Object("Light")
, m_LightID(GL_LIGHT1)	// Default Light ID
, m_ListID(0)			// By default display list ID= 0
, m_ListIsValid(false)	// By default display list is not valid
, m_AmbientColor(Qt::black)		// By default diffuse color is set to black
, m_DiffuseColor(Qt::white)		// By default diffuse color is set to white
, m_SpecularColor(Qt::white)	// By default specular color is set to white
, m_Position()
, m_TwoSided(false)
{
	//! \todo modify class to support multi light
}

GLC_Light::GLC_Light(const QColor& color)
:GLC_Object("Light")
, m_LightID(GL_LIGHT1)	// Default Light ID
, m_ListID(0)			// By default display list ID= 0
, m_ListIsValid(false)	// By default display list is not valid
, m_AmbientColor(Qt::black)		// By default diffuse color is set to black
, m_DiffuseColor(color)			// Diffuse color is set to color
, m_SpecularColor(Qt::white)	// By default specular color is set to white
, m_Position()
, m_TwoSided(false)
{
	//! \todo modify class to support multi light
}

GLC_Light::~GLC_Light(void)
{
	deleteList();
}

/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////

// Set the lihgt position by a 4D point
void GLC_Light::setPosition(const GLC_Point4d &pos)
{
	m_Position= pos;
	m_ListIsValid = false;
}

// Set the lihgt position by a 3 GLfloat
void GLC_Light::setPosition(GLfloat x, GLfloat y, GLfloat z)
{
	m_Position.setVect(static_cast<double>(x), static_cast<double>(y), static_cast<double>(z));
	m_ListIsValid = false;
}

// Set light's ambiant color by a QColor
void GLC_Light::setAmbientColor(const QColor& color)
{
	m_AmbientColor= color;
	m_ListIsValid = false;
}

// Set light's diffuse color by a QColor
void GLC_Light::setDiffuseColor(const QColor& color)
{
	m_DiffuseColor= color;
	m_ListIsValid = false;
}

// Set light's specular color by a QColor
void GLC_Light::setSpecularColor(const QColor& color)
{
	m_SpecularColor= color;
	m_ListIsValid = false;
}

//! Set Mode
void setMode(const GLenum);

//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////

// Create light's OpenGL list
void GLC_Light::creationList(GLenum Mode)
{
	if(!m_ListID)		// OpenGL list not created
	{
		m_ListID= glGenLists(1);

		if (!m_ListID)	// OpenGL List Id not get
		{
			glDraw();
			qDebug("GLC_Lumiere::CreationListe Display list not create");
		}
	}
	// OpenGL list creation and execution
	glNewList(m_ListID, Mode);

	// Light execution
	glDraw();

	glEndList();

	// Indicateur de la validit de la liste
	m_ListIsValid= true;

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::CreationList ", error);
		throw(OpenGlException);
	}
}

// Execute OpenGL light
void GLC_Light::glExecute(GLenum Mode)
{
	// Object Name
	glLoadName(getID());

	if (!m_ListIsValid)
	{
		// OpenGL list is not valid

		creationList(Mode);
	}
	else
	{
		glCallList(m_ListID);
	}

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::GlExecute ", error);
		throw(OpenGlException);
	}

}

// OpenGL light set up
void GLC_Light::glDraw(void)
{
	// Set the lighting model
	if (m_TwoSided)
	{
		qDebug() << "Two sided";
		glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
	}
	else
	{
		qDebug() << "One Sided";
		glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
	}

	// Color
	GLfloat setArray[4]= {static_cast<GLfloat>(m_AmbientColor.redF()),
									static_cast<GLfloat>(m_AmbientColor.greenF()),
									static_cast<GLfloat>(m_AmbientColor.blueF()),
									static_cast<GLfloat>(m_AmbientColor.alphaF())};
	glLightfv(m_LightID, GL_AMBIENT, setArray);		// Setup The Ambient Light

	setArray[0]= static_cast<GLfloat>(m_DiffuseColor.redF());
	setArray[1]= static_cast<GLfloat>(m_DiffuseColor.greenF());
	setArray[2]= static_cast<GLfloat>(m_DiffuseColor.blueF());
	setArray[3]= static_cast<GLfloat>(m_DiffuseColor.alphaF());
	glLightfv(m_LightID, GL_DIFFUSE, setArray);		// Setup The Diffuse Light

	setArray[0]= static_cast<GLfloat>(m_SpecularColor.redF());
	setArray[1]= static_cast<GLfloat>(m_SpecularColor.greenF());
	setArray[2]= static_cast<GLfloat>(m_SpecularColor.blueF());
	setArray[3]= static_cast<GLfloat>(m_SpecularColor.alphaF());
	glLightfv(m_LightID, GL_SPECULAR, setArray);	// Setup The specular Light

	// Position
	setArray[0]= static_cast<GLfloat>(m_Position.getX());
	setArray[1]= static_cast<GLfloat>(m_Position.getY());
	setArray[2]= static_cast<GLfloat>(m_Position.getZ());
	setArray[3]= static_cast<GLfloat>(m_Position.getW());
	glLightfv(m_LightID, GL_POSITION, setArray);	// Position The Light

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::GlDraw ", error);
		throw(OpenGlException);
	}

}

//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////

// Delete OpenGL Display list
void GLC_Light::deleteList(void)
{
	//! if the list is valid, the list is deleted
	if (glIsList(m_ListID))
	{
		glDeleteLists(m_ListID, 1);
	}
}
<commit_msg>Removing qDebug lines.<commit_after>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 1.0.0, packaged on August, 2008.

 http://glc-lib.sourceforge.net

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

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

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

//! \file glc_light.cpp implementation of the GLC_Light class.

#include "glc_light.h"
#include "glc_openglexception.h"

#include <QtDebug>

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light()
:GLC_Object("Light")
, m_LightID(GL_LIGHT1)	// Default Light ID
, m_ListID(0)			// By default display list ID= 0
, m_ListIsValid(false)	// By default display list is not valid
, m_AmbientColor(Qt::black)		// By default diffuse color is set to black
, m_DiffuseColor(Qt::white)		// By default diffuse color is set to white
, m_SpecularColor(Qt::white)	// By default specular color is set to white
, m_Position()
, m_TwoSided(false)
{
	//! \todo modify class to support multi light
}

GLC_Light::GLC_Light(const QColor& color)
:GLC_Object("Light")
, m_LightID(GL_LIGHT1)	// Default Light ID
, m_ListID(0)			// By default display list ID= 0
, m_ListIsValid(false)	// By default display list is not valid
, m_AmbientColor(Qt::black)		// By default diffuse color is set to black
, m_DiffuseColor(color)			// Diffuse color is set to color
, m_SpecularColor(Qt::white)	// By default specular color is set to white
, m_Position()
, m_TwoSided(false)
{
	//! \todo modify class to support multi light
}

GLC_Light::~GLC_Light(void)
{
	deleteList();
}

/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////

// Set the lihgt position by a 4D point
void GLC_Light::setPosition(const GLC_Point4d &pos)
{
	m_Position= pos;
	m_ListIsValid = false;
}

// Set the lihgt position by a 3 GLfloat
void GLC_Light::setPosition(GLfloat x, GLfloat y, GLfloat z)
{
	m_Position.setVect(static_cast<double>(x), static_cast<double>(y), static_cast<double>(z));
	m_ListIsValid = false;
}

// Set light's ambiant color by a QColor
void GLC_Light::setAmbientColor(const QColor& color)
{
	m_AmbientColor= color;
	m_ListIsValid = false;
}

// Set light's diffuse color by a QColor
void GLC_Light::setDiffuseColor(const QColor& color)
{
	m_DiffuseColor= color;
	m_ListIsValid = false;
}

// Set light's specular color by a QColor
void GLC_Light::setSpecularColor(const QColor& color)
{
	m_SpecularColor= color;
	m_ListIsValid = false;
}

//! Set Mode
void setMode(const GLenum);

//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////

// Create light's OpenGL list
void GLC_Light::creationList(GLenum Mode)
{
	if(!m_ListID)		// OpenGL list not created
	{
		m_ListID= glGenLists(1);

		if (!m_ListID)	// OpenGL List Id not get
		{
			glDraw();
			qDebug("GLC_Lumiere::CreationListe Display list not create");
		}
	}
	// OpenGL list creation and execution
	glNewList(m_ListID, Mode);

	// Light execution
	glDraw();

	glEndList();

	// Indicateur de la validit de la liste
	m_ListIsValid= true;

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::CreationList ", error);
		throw(OpenGlException);
	}
}

// Execute OpenGL light
void GLC_Light::glExecute(GLenum Mode)
{
	// Object Name
	glLoadName(getID());

	if (!m_ListIsValid)
	{
		// OpenGL list is not valid

		creationList(Mode);
	}
	else
	{
		glCallList(m_ListID);
	}

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::GlExecute ", error);
		throw(OpenGlException);
	}

}

// OpenGL light set up
void GLC_Light::glDraw(void)
{
	// Set the lighting model
	if (m_TwoSided)
	{
		glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
	}
	else
	{
		glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
	}

	// Color
	GLfloat setArray[4]= {static_cast<GLfloat>(m_AmbientColor.redF()),
									static_cast<GLfloat>(m_AmbientColor.greenF()),
									static_cast<GLfloat>(m_AmbientColor.blueF()),
									static_cast<GLfloat>(m_AmbientColor.alphaF())};
	glLightfv(m_LightID, GL_AMBIENT, setArray);		// Setup The Ambient Light

	setArray[0]= static_cast<GLfloat>(m_DiffuseColor.redF());
	setArray[1]= static_cast<GLfloat>(m_DiffuseColor.greenF());
	setArray[2]= static_cast<GLfloat>(m_DiffuseColor.blueF());
	setArray[3]= static_cast<GLfloat>(m_DiffuseColor.alphaF());
	glLightfv(m_LightID, GL_DIFFUSE, setArray);		// Setup The Diffuse Light

	setArray[0]= static_cast<GLfloat>(m_SpecularColor.redF());
	setArray[1]= static_cast<GLfloat>(m_SpecularColor.greenF());
	setArray[2]= static_cast<GLfloat>(m_SpecularColor.blueF());
	setArray[3]= static_cast<GLfloat>(m_SpecularColor.alphaF());
	glLightfv(m_LightID, GL_SPECULAR, setArray);	// Setup The specular Light

	// Position
	setArray[0]= static_cast<GLfloat>(m_Position.getX());
	setArray[1]= static_cast<GLfloat>(m_Position.getY());
	setArray[2]= static_cast<GLfloat>(m_Position.getZ());
	setArray[3]= static_cast<GLfloat>(m_Position.getW());
	glLightfv(m_LightID, GL_POSITION, setArray);	// Position The Light

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::GlDraw ", error);
		throw(OpenGlException);
	}

}

//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////

// Delete OpenGL Display list
void GLC_Light::deleteList(void)
{
	//! if the list is valid, the list is deleted
	if (glIsList(m_ListID))
	{
		glDeleteLists(m_ListID, 1);
	}
}
<|endoftext|>


<commit_before>#include "GenesisMakeDirWindow.h"
#include "GenesisPanelView.h"
#include "GenesisWindow.h"
#include <stdio.h>
#include <View.h>
#include <Window.h>
#include <Beep.h>
#include <Button.h>
#include <Directory.h>

////////////////////////////////////////////////////////////////////////
GenesisMakeDirWindow::GenesisMakeDirWindow(const char* dirpath, BLooper* looper, BWindow *mainwindow = NULL) :
	BWindow(BRect(0,0,320,100), "Create new folder", B_TITLED_WINDOW , B_WILL_DRAW)
////////////////////////////////////////////////////////////////////////
{
	BRect rect;

	m_DirPath.SetTo(dirpath);
	m_Looper = looper;

	SetType(B_FLOATING_WINDOW);
	SetFeel(B_MODAL_SUBSET_WINDOW_FEEL);
	SetFlags(B_NOT_RESIZABLE | B_NOT_ZOOMABLE);

	AddToSubset(mainwindow);

	m_View = new BView(Bounds(), "makedirview", B_FOLLOW_ALL, B_WILL_DRAW);
	m_View->SetViewColor(216, 216, 216, 0);
	AddChild(m_View);

	// Bottom View
	rect = Bounds();
	rect.top = rect.bottom-44;
	BView *BottomView = new BView(rect, "infobottomview", B_FOLLOW_ALL, B_WILL_DRAW);
	BottomView->SetViewColor(180, 190, 200, 0);	//
	m_View->AddChild(BottomView);

	// OK Button
	rect = BottomView->Bounds();
	rect.top = rect.bottom-34;
	rect.bottom = rect.bottom-14;
	rect.left = rect.right-80;
	rect.right = rect.right-20;
	m_OkButton = new BButton(rect,"ok","OK",new BMessage(BUTTON_MSG_CREATE_DIR),0,B_WILL_DRAW);
	BottomView->AddChild(m_OkButton);

	//Cancel Button
	rect = BottomView->Bounds();
	rect.top = rect.bottom-34;
	rect.bottom = rect.bottom-14;
	rect.left = rect.right-160;
	rect.right = rect.right-100;
	BButton *CancelButton = new BButton(rect,"cancel","Cancel",new BMessage(BUTTON_MSG_CANCEL),0,B_WILL_DRAW);
	BottomView->AddChild(CancelButton);

	SetDefaultButton(m_OkButton);

	// Edit field
	rect = BottomView->Bounds();
	rect.top = rect.top+20;
	rect.bottom = rect.top+32;
	rect.left += 20;
	rect.right -= 20;
	m_DirName = new BTextControl( rect, "dirname", "Name:", "New folder", NULL );
	m_DirName->SetDivider(m_View->StringWidth("Name:")+4);
	m_DirName->SetModificationMessage(new BMessage(DIRNAME_CHANGED));
	m_View->AddChild(m_DirName);

	m_DirName->MakeFocus(true);

	// Ctrl + Q closes the window...
	AddShortcut('Q', 0, new BMessage(BUTTON_MSG_CANCEL));

	AddCommonFilter(new EscapeFilter(this, new BMessage(BUTTON_MSG_CANCEL)));

	if (strlen(m_DirName->Text())==0)
		m_OkButton->SetEnabled(false);
	else
		m_OkButton->SetEnabled(true);

	// If there is a given window, let's align our window to its center...
	if (mainwindow)
	{
		BRect myrect = Bounds();

		rect = mainwindow->Frame();
		float w = rect.right - rect.left;
		float h = rect.bottom - rect.top;
		MoveTo(rect.left + w/2 - (myrect.right-myrect.left)/2, rect.top + h/2 - (myrect.bottom-myrect.top)/2);
	}
}

////////////////////////////////////////////////////////////////////////
GenesisMakeDirWindow::~GenesisMakeDirWindow()
////////////////////////////////////////////////////////////////////////
{

}

////////////////////////////////////////////////////////////////////////
void GenesisMakeDirWindow::MessageReceived(BMessage* message)
////////////////////////////////////////////////////////////////////////
{
	switch(message->what)
	{
		case DIRNAME_CHANGED:
			if (strlen(m_DirName->Text())>0)
				m_OkButton->SetEnabled(true);
			else
				m_OkButton->SetEnabled(false);
			break;
		case BUTTON_MSG_CANCEL:
			Close();
			break;
		case BUTTON_MSG_CREATE_DIR:
			if (strlen(m_DirName->Text())>0)
			{
				if ( CreateFolder(m_DirPath.String(), m_DirName->Text()) )
				{
					BMessage *msg = new BMessage(MSG_RELOAD);
					msg->AddString("ItemName",m_DirName->Text());
					if (m_Looper) m_Looper->PostMessage(msg, NULL);
					Close();
				}
			}
			break;
		default:
			BWindow::MessageReceived(message);
	}
}

////////////////////////////////////////////////////////////////////////
bool GenesisMakeDirWindow::CreateFolder(const char *dirpath, const char *dirname)
////////////////////////////////////////////////////////////////////////
{
	BString dir;
	dir.SetTo(dirpath);
	dir+="/";
	dir+=dirname;

	if (create_directory(dir.String(), 0777)==B_OK)		// TODO: jo a 0777?
		return 1;
	else
		return 0;
}

////////////////////////////////////////////////////////////////////////
CustomTextControl::CustomTextControl(BRect rect, const char *name, const char *label, const char *text) :
	BTextControl(rect, name, label, text, NULL)
////////////////////////////////////////////////////////////////////////
{

}

////////////////////////////////////////////////////////////////////////
CustomTextControl::~CustomTextControl()
////////////////////////////////////////////////////////////////////////
{

}
/*
void CustomTextControl::KeyUp(const char *bytes, int32 numBytes)
{
	if (bytes[0]==B_ESCAPE)
	{
		beep();
	}
	else BTextControl::KeyDown(bytes, numBytes);
}
*/
////////////////////////////////////////////////////////////////////////
void CustomTextControl::MessageReceived(BMessage* message)
////////////////////////////////////////////////////////////////////////
{
	beep();
	switch(message->what)
	{
		default:
			BTextControl::MessageReceived(message);
	}
}

/*
void CustomTextControl::SetESCMessage(BMessage *msg)
{
	escmsg = msg;
}
*/
<commit_msg>Fix gcc4 build<commit_after>#include "GenesisMakeDirWindow.h"
#include "GenesisPanelView.h"
#include "GenesisWindow.h"
#include <stdio.h>
#include <View.h>
#include <Window.h>
#include <Beep.h>
#include <Button.h>
#include <Directory.h>

////////////////////////////////////////////////////////////////////////
GenesisMakeDirWindow::GenesisMakeDirWindow(const char* dirpath, BLooper* looper, BWindow *mainwindow) :
	BWindow(BRect(0,0,320,100), "Create new folder", B_TITLED_WINDOW , B_WILL_DRAW)
////////////////////////////////////////////////////////////////////////
{
	BRect rect;

	m_DirPath.SetTo(dirpath);
	m_Looper = looper;

	SetType(B_FLOATING_WINDOW);
	SetFeel(B_MODAL_SUBSET_WINDOW_FEEL);
	SetFlags(B_NOT_RESIZABLE | B_NOT_ZOOMABLE);

	AddToSubset(mainwindow);

	m_View = new BView(Bounds(), "makedirview", B_FOLLOW_ALL, B_WILL_DRAW);
	m_View->SetViewColor(216, 216, 216, 0);
	AddChild(m_View);

	// Bottom View
	rect = Bounds();
	rect.top = rect.bottom-44;
	BView *BottomView = new BView(rect, "infobottomview", B_FOLLOW_ALL, B_WILL_DRAW);
	BottomView->SetViewColor(180, 190, 200, 0);	//
	m_View->AddChild(BottomView);

	// OK Button
	rect = BottomView->Bounds();
	rect.top = rect.bottom-34;
	rect.bottom = rect.bottom-14;
	rect.left = rect.right-80;
	rect.right = rect.right-20;
	m_OkButton = new BButton(rect,"ok","OK",new BMessage(BUTTON_MSG_CREATE_DIR),0,B_WILL_DRAW);
	BottomView->AddChild(m_OkButton);

	//Cancel Button
	rect = BottomView->Bounds();
	rect.top = rect.bottom-34;
	rect.bottom = rect.bottom-14;
	rect.left = rect.right-160;
	rect.right = rect.right-100;
	BButton *CancelButton = new BButton(rect,"cancel","Cancel",new BMessage(BUTTON_MSG_CANCEL),0,B_WILL_DRAW);
	BottomView->AddChild(CancelButton);

	SetDefaultButton(m_OkButton);

	// Edit field
	rect = BottomView->Bounds();
	rect.top = rect.top+20;
	rect.bottom = rect.top+32;
	rect.left += 20;
	rect.right -= 20;
	m_DirName = new BTextControl( rect, "dirname", "Name:", "New folder", NULL );
	m_DirName->SetDivider(m_View->StringWidth("Name:")+4);
	m_DirName->SetModificationMessage(new BMessage(DIRNAME_CHANGED));
	m_View->AddChild(m_DirName);

	m_DirName->MakeFocus(true);

	// Ctrl + Q closes the window...
	AddShortcut('Q', 0, new BMessage(BUTTON_MSG_CANCEL));

	AddCommonFilter(new EscapeFilter(this, new BMessage(BUTTON_MSG_CANCEL)));

	if (strlen(m_DirName->Text())==0)
		m_OkButton->SetEnabled(false);
	else
		m_OkButton->SetEnabled(true);

	// If there is a given window, let's align our window to its center...
	if (mainwindow)
	{
		BRect myrect = Bounds();

		rect = mainwindow->Frame();
		float w = rect.right - rect.left;
		float h = rect.bottom - rect.top;
		MoveTo(rect.left + w/2 - (myrect.right-myrect.left)/2, rect.top + h/2 - (myrect.bottom-myrect.top)/2);
	}
}

////////////////////////////////////////////////////////////////////////
GenesisMakeDirWindow::~GenesisMakeDirWindow()
////////////////////////////////////////////////////////////////////////
{

}

////////////////////////////////////////////////////////////////////////
void GenesisMakeDirWindow::MessageReceived(BMessage* message)
////////////////////////////////////////////////////////////////////////
{
	switch(message->what)
	{
		case DIRNAME_CHANGED:
			if (strlen(m_DirName->Text())>0)
				m_OkButton->SetEnabled(true);
			else
				m_OkButton->SetEnabled(false);
			break;
		case BUTTON_MSG_CANCEL:
			Close();
			break;
		case BUTTON_MSG_CREATE_DIR:
			if (strlen(m_DirName->Text())>0)
			{
				if ( CreateFolder(m_DirPath.String(), m_DirName->Text()) )
				{
					BMessage *msg = new BMessage(MSG_RELOAD);
					msg->AddString("ItemName",m_DirName->Text());
					if (m_Looper) m_Looper->PostMessage(msg, NULL);
					Close();
				}
			}
			break;
		default:
			BWindow::MessageReceived(message);
	}
}

////////////////////////////////////////////////////////////////////////
bool GenesisMakeDirWindow::CreateFolder(const char *dirpath, const char *dirname)
////////////////////////////////////////////////////////////////////////
{
	BString dir;
	dir.SetTo(dirpath);
	dir+="/";
	dir+=dirname;

	if (create_directory(dir.String(), 0777)==B_OK)		// TODO: jo a 0777?
		return 1;
	else
		return 0;
}

////////////////////////////////////////////////////////////////////////
CustomTextControl::CustomTextControl(BRect rect, const char *name, const char *label, const char *text) :
	BTextControl(rect, name, label, text, NULL)
////////////////////////////////////////////////////////////////////////
{

}

////////////////////////////////////////////////////////////////////////
CustomTextControl::~CustomTextControl()
////////////////////////////////////////////////////////////////////////
{

}
/*
void CustomTextControl::KeyUp(const char *bytes, int32 numBytes)
{
	if (bytes[0]==B_ESCAPE)
	{
		beep();
	}
	else BTextControl::KeyDown(bytes, numBytes);
}
*/
////////////////////////////////////////////////////////////////////////
void CustomTextControl::MessageReceived(BMessage* message)
////////////////////////////////////////////////////////////////////////
{
	beep();
	switch(message->what)
	{
		default:
			BTextControl::MessageReceived(message);
	}
}

/*
void CustomTextControl::SetESCMessage(BMessage *msg)
{
	escmsg = msg;
}
*/
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tk_atag2.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: np $ $Date: 2002-05-14 09:02:21 $
 *
 *  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 DSAPI_TK_ATAG2_HXX
#define DSAPI_TK_ATAG2_HXX

// USED SERVICES
    // BASE CLASSES
#include <s2_dsapi/dsapitok.hxx>
    // COMPONENTS
    // PARAMETERS
#include <luxenum.hxx>

namespace csi
{
namespace dsapi
{

class Tok_AtTag : public Token
{
  public:
    // TYPE
    enum E_TokenId
    {
        e_none = 0,
        author =  1,
        see = 2,
        param = 3,
        e_return = 4,
        e_throw = 5,
        example = 6,
        deprecated = 7,
        suspicious = 8,
        missing = 9,
        incomplete = 10,
        version = 11,
        guarantees = 12,
        exception = 13
    };
    typedef lux::Enum<E_TokenId> EV_TokenId;

    // Spring and Fall
                        Tok_AtTag(
                            EV_TokenId          i_eTag )
                                                :   eTag(i_eTag) {}
    // OPERATIONS
    virtual void        Trigger(
                            TokenInterpreter &  io_rInterpreter ) const;
    // INQUIRY
    virtual const char* Text() const;
    E_TokenId           Id() const              { return eTag; }

  private:
    EV_TokenId          eTag;
};

}   // namespace dsapi
}   // namespace csi

#endif

<commit_msg>INTEGRATION: CWS sdk02 (1.2.46); FILE MERGED 2003/05/26 16:42:19 np 1.2.46.1: #108925# Enable tag @since and text for tag @deprecated.<commit_after>/*************************************************************************
 *
 *  $RCSfile: tk_atag2.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-06-10 11:35:43 $
 *
 *  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 DSAPI_TK_ATAG2_HXX
#define DSAPI_TK_ATAG2_HXX

// USED SERVICES
    // BASE CLASSES
#include <s2_dsapi/dsapitok.hxx>
    // COMPONENTS
    // PARAMETERS
#include <luxenum.hxx>

namespace csi
{
namespace dsapi
{

class Tok_AtTag : public Token
{
  public:
    // TYPE
    enum E_TokenId
    {
        e_none = 0,
        author =  1,
        see = 2,
        param = 3,
        e_return = 4,
        e_throw = 5,
        example = 6,
        deprecated = 7,
        suspicious = 8,
        missing = 9,
        incomplete = 10,
        version = 11,
        guarantees = 12,
        exception = 13,
        since = 14
    };
    typedef lux::Enum<E_TokenId> EV_TokenId;

    // Spring and Fall
                        Tok_AtTag(
                            EV_TokenId          i_eTag )
                                                :   eTag(i_eTag) {}
    // OPERATIONS
    virtual void        Trigger(
                            TokenInterpreter &  io_rInterpreter ) const;
    // INQUIRY
    virtual const char* Text() const;
    E_TokenId           Id() const              { return eTag; }

  private:
    EV_TokenId          eTag;
};

}   // namespace dsapi
}   // namespace csi

#endif

<|endoftext|>


<commit_before>/******************************************************************************
Module:  ConsoleAdapter.cpp
Author:
******************************************************************************/
#include "stdafx.h"
#include "ConsoleAdapter.h"
#include <fstream>
#include <tchar.h>

/////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

ConsoleAdapter::ConsoleAdapter( bool bAutoDestroy ):
                                //m_fOldStdIn(0),
                                m_fpCRTIn(0),
                                m_nCRTIn(0),
                                //m_fOldStdOut(0),
                                m_fpCRTOut(0),
                                m_nCRTOut(0),
                                m_eConsoleType( BOTH ),
                                m_bDestroyed( false ),
                                m_bAutoDestroy( bAutoDestroy ),
                                m_hDumpConsole( 0 )
{

}

ConsoleAdapter::~ConsoleAdapter()
{
    if( m_bAutoDestroy || !m_bDestroyed)
        DestroyConsole();
}

/******************************************************************************
Function: CreateConsole
Author  : Sudheesh.P.S
Param   : eConsoleType - Type of console(input/output or both)
Desc    : Allocates a new console and replaces the standard input/output streams
******************************************************************************/

bool ConsoleAdapter::CreateConsole( CONSOLETYPE_e eConsoleType )
{
    try
    {
        m_eConsoleType = eConsoleType;
        AllocConsole();
        return ReplaceHandles();
    }
    catch ( ... )
    {
        return false;
    }
}

/******************************************************************************
Function: ReplaceHandles
Author  : Sudheesh.P.S
Desc    : Replaces the standard input/output streams
******************************************************************************/

bool ConsoleAdapter::ReplaceHandles()
{
    try
    {
        if( ( INPUT_CONS == m_eConsoleType ) || ( BOTH == m_eConsoleType ) )
        {
            m_nCRTIn= _open_osfhandle(
                 (long) GetStdHandle(STD_INPUT_HANDLE),
                 _O_TEXT );
            if( -1 == m_nCRTIn )
            {
                return false;
            }
            m_fpCRTIn = _fdopen( m_nCRTIn, "r" );
            if( !m_fpCRTIn )
            {
                return false;
            }
            m_fOldStdIn = *stdin;
            *stdin = *m_fpCRTIn;
            // if clear is not done, any cout statement before AllocConsole
            // will cause, the cin after AllocConsole to fail, so very important
            std::cin.clear();
        }
        if( ( OUTPUT_CONS == m_eConsoleType ) || ( BOTH == m_eConsoleType ) )
        {
            m_nCRTOut= _open_osfhandle(
                 (long) GetStdHandle(STD_OUTPUT_HANDLE),
                 _O_TEXT );
            if( -1 == m_nCRTOut )
            {
                return false;
            }

            m_fpCRTOut = _fdopen( m_nCRTOut, "w" );
            if( !m_fpCRTOut )
            {
                return false;
            }
            m_fOldStdOut = *stdout;
            *stdout = *m_fpCRTOut;
            // if clear is not done, any cout statement before AllocConsole
            // will cause, the cout after AllocConsole to fail, so very important
            std::cout.clear();
        }
    }
    catch ( ... )
    {
        return false;
    }
    return true;
}

/******************************************************************************
Function: DestroyConsole
Author  : Sudheesh.P.S
Desc    : Destroys the attached console and restores the input/output handles
******************************************************************************/

void ConsoleAdapter::DestroyConsole()
{

    try
    {
        FreeConsole();
        if( 0 != m_hDumpConsole )
        {
            // Kill the DumpConsole when not needed
            TerminateProcess( m_hDumpConsole, 0 );
            CloseHandle( m_hDumpConsole );
            m_hDumpConsole = 0;
        }
        if( ( INPUT_CONS == m_eConsoleType ) || ( BOTH == m_eConsoleType ) )
        {
            if( 0 != m_fpCRTIn )
            {
                fclose( m_fpCRTIn );
            }
            _close( m_nCRTIn );
            *stdin = m_fOldStdIn;
        }

        if( ( OUTPUT_CONS == m_eConsoleType ) || ( BOTH == m_eConsoleType ) )
        {
            if( 0 != m_fpCRTOut )
            {
                fclose( m_fpCRTOut );
            }
            _close( m_nCRTOut );
            *stdout = m_fOldStdOut;
        }
        m_bDestroyed = true;
    }
    catch ( ... )
    {

    }
}
<commit_msg>Delete ConsoleAdapter.cpp<commit_after><|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>

#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
#include <File.h>

/*
* Runs a command in the terminal, given the string you'd type
*/
BString*
run_script(const char *cmd)
{
  char buf[BUFSIZ];
  FILE *ptr;
  BString *output = new BString;

  if ((ptr = popen(cmd, "r")) != NULL)
    while (fgets(buf, BUFSIZ, ptr) != NULL)
       output->Append(buf);

  (void) pclose(ptr);
  return output;
}
/*
enum {
  DELETE_EVERYTHING;
  CREATE_FOLDER;
  CREATE_FILE;
  DELETE_THIS;
}
*/

int
parse_command(const char* command)
{
  if(command[0] == 'R'
    && command[1] == 'E'
    && command[2] == 'S'
    && command[3] == 'E'
    && command[4] == 'T')
  {
    printf("Burn Everything. 8D\n");
  }
  else
  {
    printf("Something more specific.\n");
  }
  return 0;
}

int32
get_next_line(BString *src, BString *dest)
{
  int32 eol = src->FindFirst('\n');
  if(eol == B_ERROR)
    return B_ERROR;

  src->MoveInto(*dest,0,eol);
  return B_OK;
}

/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
  : BApplication("application/x-vnd.lh-MyDropboxClient")
{
  //ask Dropbox for deltas!
  BString *delta_commands = run_script("python db_delta.py");
  BString line;
  if(get_next_line(delta_commands,&line) == B_OK)
    (void) parse_command(line.String());

  //start watching ~/Dropbox folder contents (create, delete, move)
  BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
  node_ref nref;
  status_t err;
  if(dir.InitCheck() == B_OK){
    dir.GetNodeRef(&nref);
    err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
    if(err != B_OK)
      printf("Watch Node: Not OK\n");
  }

  // record each file in the folder so that we know the name on deletion
  BEntry *entry = new BEntry;
  status_t err2;
  err = dir.GetNextEntry(entry);
  BPath *path;
  BFile *file;
  while(err == B_OK) //loop over files
  {
    file = new BFile(entry, B_READ_ONLY);
    this->tracked_files.AddItem((void*)(file)); //add file to my list
    path = new BPath;
    entry->GetPath(path);
    printf("tracking: %s\n",path->Path());
    this->tracked_filepaths.AddItem((void*)path);
    err2 = entry->GetNodeRef(&nref);
    if(err2 == B_OK)
    {
      err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits
      if(err2 != B_OK)
        printf("Watch file Node: Not OK\n");
    }
    entry = new BEntry;
    err = dir.GetNextEntry(entry);
  }
  //delete that last BEntry...
}

/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
  printf("Telling Dropbox to Delete\n");
  BString s, dbfp;
  s = BString(filepath);
  s.RemoveFirst("/boot/home/Dropbox");
  dbfp << "python db_rm.py " << s;
  printf("%s\n",dbfp.String());
  run_script(dbfp);
}

/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
  BString s;
  s = BString(local_path);
  s.RemoveFirst("/boot/home/Dropbox/");
  return s;
}

/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
  BString s, dbfp;
  dbfp = local_to_db_filepath(filepath);
  s << "python db_put.py " << BString(filepath) << " " << dbfp;
  printf("local filepath:%s\n",filepath);
  printf("dropbox filepath:%s\n",dbfp.String());
  run_script(s.String());
}

/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
  BString s;
  s << "python db_mkdir.py " << local_to_db_filepath(filepath);
  printf("local filepath: %s\n", filepath);
  printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
  run_script(s.String());
}

/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
  //is this file being move into or out of ~/Dropbox?
  run_script("python db_ls.py");
}

/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
  printf("Putting %s to Dropbox.\n", filepath);
  add_file_to_dropbox(filepath); //just put it?
}

/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
  switch(msg->what)
  {
    case B_NODE_MONITOR:
    {
      printf("Received Node Monitor Alert\n");
      status_t err;
      int32 opcode;
      err = msg->FindInt32("opcode",&opcode);
      if(err == B_OK)
      {
        printf("what:%d\topcode:%d\n",msg->what, opcode);
        switch(opcode)
        {
          case B_ENTRY_CREATED:
          {
            printf("NEW FILE\n");
            entry_ref ref;
            BPath path;
            const char * name;

            // unpack the message
            msg->FindInt32("device",&ref.device);
            msg->FindInt64("directory",&ref.directory);
            msg->FindString("name",&name);
            printf("name:%s\n",name);
            ref.set_name(name);
            BEntry new_file = BEntry(&ref);

            // add the new file to Dropbox
            new_file.GetPath(&path);
            add_file_to_dropbox(path.Path());

            // add the new file to global tracking lists
            BFile *file = new BFile(&new_file, B_READ_ONLY);
            this->tracked_files.AddItem((void*)file);
            BPath *path2 = new BPath;
            new_file.GetPath(path2);
            this->tracked_filepaths.AddItem((void*)path2);

            // listen for EDIT alerts on the new file
            node_ref nref;
            err = new_file.GetNodeRef(&nref);
            if(err == B_OK)
            {
              err = watch_node(&nref, B_WATCH_STAT, be_app_messenger);
              if(err != B_OK)
                printf("Watch new file %s: Not Ok.\n", path2->Path());
            }

            break;
          }
          case B_ENTRY_MOVED:
          {
            printf("MOVED FILE\n");
            moved_file(msg);
            break;
          }
          case B_ENTRY_REMOVED:
          {
            printf("DELETED FILE\n");
            node_ref nref, cref;
            msg->FindInt32("device",&nref.device);
            msg->FindInt64("node",&nref.node);
            BFile *filePtr;
            int32 ktr = 0;
            int32 limit = this->tracked_files.CountItems();
            printf("About to loop %d times\n", limit);
            while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit))
            {
              printf("In loop.\n");
              filePtr->GetNodeRef(&cref);
              printf("GotNodeRef\n");
              if(nref == cref)
              {
                printf("Deleting it\n");
                BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr);
                printf("%s\n",path->Path());
                delete_file_on_dropbox(path->Path());

                this->tracked_files.RemoveItem(ktr);
                this->tracked_filepaths.RemoveItem(ktr);
                break; //break out of loop
              }
              ktr++;
            }
            break;
          }
          case B_STAT_CHANGED:
          {
            printf("EDITED FILE\n");
            node_ref nref1,nref2;
            msg->FindInt32("device",&nref1.device);
            msg->FindInt64("node",&nref1.node);
            BFile * filePtr;
            int32 ktr = 0;
            while((filePtr = (BFile *)this->tracked_files.ItemAt(ktr++)))
            {
              filePtr->GetNodeRef(&nref2);
              if(nref1 == nref2)
              {
                BPath *path;
                path = (BPath*)this->tracked_filepaths.ItemAt(ktr-1);
                update_file_in_dropbox(path->Path());
                break;
              }
            }
            break;
          }
          default:
          {
            printf("default case opcode...\n");
          }
        }
      }
      break;
    }
    default:
    {
      printf("default msg\n");
      BApplication::MessageReceived(msg);
      break;
    }
  }
}

int
main(void)
{
  //set up application (watch Dropbox folder & contents)
  App *app = new App();

  //start the application
  app->Run();

  //clean up now that we're shutting down
  delete app;
  return 0;
}
<commit_msg>do a basic parse of all the delta commands received from python.<commit_after>#include <stdio.h>
#include <stdlib.h>

#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
#include <File.h>

/*
* Runs a command in the terminal, given the string you'd type
*/
BString*
run_script(const char *cmd)
{
  char buf[BUFSIZ];
  FILE *ptr;
  BString *output = new BString;

  if ((ptr = popen(cmd, "r")) != NULL)
    while (fgets(buf, BUFSIZ, ptr) != NULL)
       output->Append(buf);

  (void) pclose(ptr);
  return output;
}
/*
enum {
  DELETE_EVERYTHING;
  CREATE_FOLDER;
  CREATE_FILE;
  DELETE_THIS;
}
*/

int
parse_command(const char* command)
{
  if(command[0] == 'R'
    && command[1] == 'E'
    && command[2] == 'S'
    && command[3] == 'E'
    && command[4] == 'T')
  {
    printf("Burn Everything. 8D\n");
  }
  else
  {
    printf("Something more specific.\n");
  }
  return 0;
}

int32
get_next_line(BString *src, BString *dest)
{
  int32 eol = src->FindFirst('\n');
  if(eol == B_ERROR)
    return B_ERROR;

  src->CopyInto(*dest,0,eol+1);
  src->Remove(0,eol+1);
  return B_OK;
}

/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
  : BApplication("application/x-vnd.lh-MyDropboxClient")
{
  //ask Dropbox for deltas!
  BString *delta_commands = run_script("python db_delta.py");
  BString line;
  while(get_next_line(delta_commands,&line) == B_OK)
  {
    (void) parse_command(line.String());
  }

  //start watching ~/Dropbox folder contents (create, delete, move)
  BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
  node_ref nref;
  status_t err;
  if(dir.InitCheck() == B_OK){
    dir.GetNodeRef(&nref);
    err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
    if(err != B_OK)
      printf("Watch Node: Not OK\n");
  }

  // record each file in the folder so that we know the name on deletion
  BEntry *entry = new BEntry;
  status_t err2;
  err = dir.GetNextEntry(entry);
  BPath *path;
  BFile *file;
  while(err == B_OK) //loop over files
  {
    file = new BFile(entry, B_READ_ONLY);
    this->tracked_files.AddItem((void*)(file)); //add file to my list
    path = new BPath;
    entry->GetPath(path);
    printf("tracking: %s\n",path->Path());
    this->tracked_filepaths.AddItem((void*)path);
    err2 = entry->GetNodeRef(&nref);
    if(err2 == B_OK)
    {
      err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits
      if(err2 != B_OK)
        printf("Watch file Node: Not OK\n");
    }
    entry = new BEntry;
    err = dir.GetNextEntry(entry);
  }
  //delete that last BEntry...
}

/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
  printf("Telling Dropbox to Delete\n");
  BString s, dbfp;
  s = BString(filepath);
  s.RemoveFirst("/boot/home/Dropbox");
  dbfp << "python db_rm.py " << s;
  printf("%s\n",dbfp.String());
  run_script(dbfp);
}

/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
  BString s;
  s = BString(local_path);
  s.RemoveFirst("/boot/home/Dropbox/");
  return s;
}

/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
  BString s, dbfp;
  dbfp = local_to_db_filepath(filepath);
  s << "python db_put.py " << BString(filepath) << " " << dbfp;
  printf("local filepath:%s\n",filepath);
  printf("dropbox filepath:%s\n",dbfp.String());
  run_script(s.String());
}

/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
  BString s;
  s << "python db_mkdir.py " << local_to_db_filepath(filepath);
  printf("local filepath: %s\n", filepath);
  printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
  run_script(s.String());
}

/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
  //is this file being move into or out of ~/Dropbox?
  run_script("python db_ls.py");
}

/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
  printf("Putting %s to Dropbox.\n", filepath);
  add_file_to_dropbox(filepath); //just put it?
}

/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
  switch(msg->what)
  {
    case B_NODE_MONITOR:
    {
      printf("Received Node Monitor Alert\n");
      status_t err;
      int32 opcode;
      err = msg->FindInt32("opcode",&opcode);
      if(err == B_OK)
      {
        printf("what:%d\topcode:%d\n",msg->what, opcode);
        switch(opcode)
        {
          case B_ENTRY_CREATED:
          {
            printf("NEW FILE\n");
            entry_ref ref;
            BPath path;
            const char * name;

            // unpack the message
            msg->FindInt32("device",&ref.device);
            msg->FindInt64("directory",&ref.directory);
            msg->FindString("name",&name);
            printf("name:%s\n",name);
            ref.set_name(name);
            BEntry new_file = BEntry(&ref);

            // add the new file to Dropbox
            new_file.GetPath(&path);
            add_file_to_dropbox(path.Path());

            // add the new file to global tracking lists
            BFile *file = new BFile(&new_file, B_READ_ONLY);
            this->tracked_files.AddItem((void*)file);
            BPath *path2 = new BPath;
            new_file.GetPath(path2);
            this->tracked_filepaths.AddItem((void*)path2);

            // listen for EDIT alerts on the new file
            node_ref nref;
            err = new_file.GetNodeRef(&nref);
            if(err == B_OK)
            {
              err = watch_node(&nref, B_WATCH_STAT, be_app_messenger);
              if(err != B_OK)
                printf("Watch new file %s: Not Ok.\n", path2->Path());
            }

            break;
          }
          case B_ENTRY_MOVED:
          {
            printf("MOVED FILE\n");
            moved_file(msg);
            break;
          }
          case B_ENTRY_REMOVED:
          {
            printf("DELETED FILE\n");
            node_ref nref, cref;
            msg->FindInt32("device",&nref.device);
            msg->FindInt64("node",&nref.node);
            BFile *filePtr;
            int32 ktr = 0;
            int32 limit = this->tracked_files.CountItems();
            printf("About to loop %d times\n", limit);
            while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit))
            {
              printf("In loop.\n");
              filePtr->GetNodeRef(&cref);
              printf("GotNodeRef\n");
              if(nref == cref)
              {
                printf("Deleting it\n");
                BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr);
                printf("%s\n",path->Path());
                delete_file_on_dropbox(path->Path());

                this->tracked_files.RemoveItem(ktr);
                this->tracked_filepaths.RemoveItem(ktr);
                break; //break out of loop
              }
              ktr++;
            }
            break;
          }
          case B_STAT_CHANGED:
          {
            printf("EDITED FILE\n");
            node_ref nref1,nref2;
            msg->FindInt32("device",&nref1.device);
            msg->FindInt64("node",&nref1.node);
            BFile * filePtr;
            int32 ktr = 0;
            while((filePtr = (BFile *)this->tracked_files.ItemAt(ktr++)))
            {
              filePtr->GetNodeRef(&nref2);
              if(nref1 == nref2)
              {
                BPath *path;
                path = (BPath*)this->tracked_filepaths.ItemAt(ktr-1);
                update_file_in_dropbox(path->Path());
                break;
              }
            }
            break;
          }
          default:
          {
            printf("default case opcode...\n");
          }
        }
      }
      break;
    }
    default:
    {
      printf("default msg\n");
      BApplication::MessageReceived(msg);
      break;
    }
  }
}

int
main(void)
{
  //set up application (watch Dropbox folder & contents)
  App *app = new App();

  //start the application
  app->Run();

  //clean up now that we're shutting down
  delete app;
  return 0;
}
<|endoftext|>


<commit_before>#include "DRMSetupWizard.h"
#include "AddGameWizard.h"
#include "SteamHelper.h"
#include "Library.h"

/** DRMSetupWizard constructor
 */
DRMSetupWizard::DRMSetupWizard(QWidget* parent, Qt::WindowFlags flags)
{
    addPage(new StartPage());
    addPage(new DRMsFoundPage());
    addPage(new GamesFoundPage());

    setWindowTitle(tr("DRM Setup Wizard"));
}

StartPage::StartPage(QWidget* parent)
{
    setTitle(tr("Welcome"));

    QVBoxLayout* layout = new QVBoxLayout(this);

    QLabel* label = new QLabel(tr("This wizard will help you add all of your games to Horizon."));
    label->setWordWrap(true);
    layout->addWidget(label);
}

DRMsFoundPage::DRMsFoundPage(QWidget* parent)
{
    setTitle(tr("DRMs Found"));

    QVBoxLayout* layout = new QVBoxLayout(this);

    QString steamFoundText;
    if (SteamHelper::doesExist())
    {
        steamFoundText = tr("Steam was found.");
    }
    else
    {
        steamFoundText = tr("Steam was not found.");
    }
    QLabel* label = new QLabel(steamFoundText);
    label->setWordWrap(true);
    layout->addWidget(label);
}

GamesFoundPage::GamesFoundPage(QWidget* parent)
{
    setTitle(tr("Games Found"));

    QVBoxLayout* layout = new QVBoxLayout(this);

    QLabel* infoLabel = new QLabel(tr("The following games will be added:"));
    infoLabel->setStyleSheet("font-size: 14px; font-weight: 600;");
    layout->addWidget(infoLabel);

    gamesLayout = new QVBoxLayout();
    layout->addLayout(gamesLayout);

    QScrollArea* scrollArea = new QScrollArea();
    layout->addWidget(scrollArea);
}

void GamesFoundPage::initializePage()
{
    QMap<QString, QString> gamesList = SteamHelper::getGames();

    for (QString game : gamesList.keys())
    {
        if (Library::db.isExistant(game).first) { continue; }
        addGames[game] = gamesList[game];
        gamesLayout->addWidget(new QLabel(game));
    }
}

bool GamesFoundPage::validatePage()
{
    for (QString game : addGames.keys())
    {
        #if defined(__linux__)
            QString openWith = "xdg-open";
        #elif defined(_WIN32) || defined(_WIN64)
            QString openWith = "explorer.exe";
        #elif defined(__APPLE__)
            QString openWith = "open";
        #endif
        Library::db.addGame(game, ".", openWith, "steam://run/" + addGames[game], 1);
    }
}
<commit_msg>Add a scrollview to the drm setup wizard<commit_after>#include "DRMSetupWizard.h"
#include "AddGameWizard.h"
#include "SteamHelper.h"
#include "Library.h"

/** DRMSetupWizard constructor
 */
DRMSetupWizard::DRMSetupWizard(QWidget* parent, Qt::WindowFlags flags)
{
    addPage(new StartPage());
    addPage(new DRMsFoundPage());
    addPage(new GamesFoundPage());

    setWindowTitle(tr("DRM Setup Wizard"));
}

StartPage::StartPage(QWidget* parent)
{
    setTitle(tr("Welcome"));

    QVBoxLayout* layout = new QVBoxLayout(this);

    QLabel* label = new QLabel(tr("This wizard will help you add all of your games to Horizon."));
    label->setWordWrap(true);
    layout->addWidget(label);
}

DRMsFoundPage::DRMsFoundPage(QWidget* parent)
{
    setTitle(tr("DRMs Found"));

    QVBoxLayout* layout = new QVBoxLayout(this);

    QString steamFoundText;
    if (SteamHelper::doesExist())
    {
        steamFoundText = tr("Steam was found.");
    }
    else
    {
        steamFoundText = tr("Steam was not found.");
    }
    QLabel* label = new QLabel(steamFoundText);
    label->setWordWrap(true);
    layout->addWidget(label);
}

GamesFoundPage::GamesFoundPage(QWidget* parent)
{
    setTitle(tr("Games Found"));

    QVBoxLayout* layout = new QVBoxLayout(this);

    QLabel* infoLabel = new QLabel(tr("The following games will be added:"));
    infoLabel->setStyleSheet("font-size: 14px; font-weight: 600;");
    layout->addWidget(infoLabel);

    QWidget* gamesWidget = new QWidget();
    gamesLayout = new QVBoxLayout(gamesWidget);

    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setFrameShape(QFrame::NoFrame);
    scrollArea->setWidgetResizable(true);
    scrollArea->setWidget(gamesWidget);
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    layout->addWidget(scrollArea);
}

void GamesFoundPage::initializePage()
{
    QMap<QString, QString> gamesList = SteamHelper::getGames();

    for (QString game : gamesList.keys())
    {
        if (Library::db.isExistant(game).first) { continue; }
        addGames[game] = gamesList[game];
        gamesLayout->addWidget(new QLabel(game));
    }
}

bool GamesFoundPage::validatePage()
{
    for (QString game : addGames.keys())
    {
        #if defined(__linux__)
            QString openWith = "xdg-open";
        #elif defined(_WIN32) || defined(_WIN64)
            QString openWith = "explorer.exe";
        #elif defined(__APPLE__)
            QString openWith = "open";
        #endif
        Library::db.addGame(game, ".", openWith, "steam://run/" + addGames[game], 1);
    }
}
<|endoftext|>