<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 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
 *
 *****************************************************************************/
#ifndef MAPNIK_PLACEMENT_FINDER_HPP
#define MAPNIK_PLACEMENT_FINDER_HPP

//mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/pixel_position.hpp>
#include <mapnik/text/text_layout.hpp>
#include <mapnik/text/glyph_positions.hpp>
#include <mapnik/text/rotation.hpp>
#include <mapnik/util/noncopyable.hpp>

namespace mapnik
{

class label_collision_detector4;
using DetectorType = label_collision_detector4;

class feature_impl;
class vertex_cache;
class text_placement_info;
struct glyph_info;

class placement_finder : util::noncopyable
{
public:
    placement_finder(feature_impl const& feature,
                     attributes const& attr,
                     DetectorType & detector,
                     box2d<double> const& extent,
                     text_placement_info const& placement_info,
                     face_manager_freetype & font_manager,
                     double scale_factor);

    // Try to place a single label at the given point.
    bool find_point_placement(pixel_position const& pos);
    // Iterate over the given path, placing line-following labels or point labels with respect to label_spacing.
    template <typename T>
    bool find_line_placements(T & path, bool points);
    // Try next position alternative from placement_info.
    bool next_position();

    placements_list const& placements() const { return placements_; }

    void set_marker(marker_info_ptr m, box2d<double> box, bool marker_unlocked, pixel_position const& marker_displacement);
private:
    bool single_line_placement(vertex_cache &pp, text_upright_e orientation);
    // Moves dx pixels but makes sure not to fall of the end.
    void path_move_dx(vertex_cache & pp, double dx);
    // Normalize angle in range [-pi, +pi].
    static double normalize_angle(double angle);
    // Adjusts user defined spacing to place an integer number of labels.
    double get_spacing(double path_length, double layout_width) const;
    // Checks for collision.
    bool collision(box2d<double> const& box, const value_unicode_string &repeat_key, bool line_placement) const;
    // Adds marker to glyph_positions and to collision detector. Returns false if there is a collision.
    bool add_marker(glyph_positions_ptr & glyphs, pixel_position const& pos, std::vector<box2d<double>> & bboxes) const;
    // Maps upright==auto, left-only and right-only to left,right to simplify processing.
    // angle = angle of at start of line (to estimate best option for upright==auto)
    text_upright_e simplify_upright(text_upright_e upright, double angle) const;
    feature_impl const& feature_;
    attributes const& attr_;
    DetectorType & detector_;
    box2d<double> const& extent_;
    text_placement_info const& info_;
    evaluated_text_properties_ptr text_props_;
    layout_container layouts_;

    double scale_factor_;
    face_manager_freetype &font_manager_;

    placements_list placements_;
    std::vector<text_layout_ptr> processed_layouts_;
    //ShieldSymbolizer
    bool has_marker_;
    marker_info_ptr marker_;
    box2d<double> marker_box_;
    bool marker_unlocked_;
    pixel_position marker_displacement_;
    double move_dx_;
    horizontal_alignment_e horizontal_alignment_;
};

}//ns mapnik

#endif // PLACEMENT_FINDER_HPP
<commit_msg>remove superfluous declaration<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 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
 *
 *****************************************************************************/
#ifndef MAPNIK_PLACEMENT_FINDER_HPP
#define MAPNIK_PLACEMENT_FINDER_HPP

//mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/pixel_position.hpp>
#include <mapnik/text/text_layout.hpp>
#include <mapnik/text/glyph_positions.hpp>
#include <mapnik/text/rotation.hpp>
#include <mapnik/util/noncopyable.hpp>

namespace mapnik
{

class label_collision_detector4;
using DetectorType = label_collision_detector4;

class feature_impl;
class vertex_cache;
class text_placement_info;
struct glyph_info;

class placement_finder : util::noncopyable
{
public:
    placement_finder(feature_impl const& feature,
                     attributes const& attr,
                     DetectorType & detector,
                     box2d<double> const& extent,
                     text_placement_info const& placement_info,
                     face_manager_freetype & font_manager,
                     double scale_factor);

    // Try to place a single label at the given point.
    bool find_point_placement(pixel_position const& pos);
    // Iterate over the given path, placing line-following labels or point labels with respect to label_spacing.
    template <typename T>
    bool find_line_placements(T & path, bool points);
    // Try next position alternative from placement_info.
    bool next_position();

    placements_list const& placements() const { return placements_; }

    void set_marker(marker_info_ptr m, box2d<double> box, bool marker_unlocked, pixel_position const& marker_displacement);
private:
    bool single_line_placement(vertex_cache &pp, text_upright_e orientation);
    // Moves dx pixels but makes sure not to fall of the end.
    void path_move_dx(vertex_cache & pp, double dx);
    // Adjusts user defined spacing to place an integer number of labels.
    double get_spacing(double path_length, double layout_width) const;
    // Checks for collision.
    bool collision(box2d<double> const& box, const value_unicode_string &repeat_key, bool line_placement) const;
    // Adds marker to glyph_positions and to collision detector. Returns false if there is a collision.
    bool add_marker(glyph_positions_ptr & glyphs, pixel_position const& pos, std::vector<box2d<double>> & bboxes) const;
    // Maps upright==auto, left-only and right-only to left,right to simplify processing.
    // angle = angle of at start of line (to estimate best option for upright==auto)
    text_upright_e simplify_upright(text_upright_e upright, double angle) const;
    feature_impl const& feature_;
    attributes const& attr_;
    DetectorType & detector_;
    box2d<double> const& extent_;
    text_placement_info const& info_;
    evaluated_text_properties_ptr text_props_;
    layout_container layouts_;

    double scale_factor_;
    face_manager_freetype &font_manager_;

    placements_list placements_;
    std::vector<text_layout_ptr> processed_layouts_;
    //ShieldSymbolizer
    bool has_marker_;
    marker_info_ptr marker_;
    box2d<double> marker_box_;
    bool marker_unlocked_;
    pixel_position marker_displacement_;
    double move_dx_;
    horizontal_alignment_e horizontal_alignment_;
};

}//ns mapnik

#endif // PLACEMENT_FINDER_HPP
<|endoftext|>


<commit_before>// This script converts the MNIST dataset to a lmdb (default) or
// leveldb (--backend=leveldb) format used by caffe to load data.
// Usage:
//    convert_mnist_data [FLAGS] input_image_file input_label_file
//                        output_db_file
// The MNIST dataset could be downloaded at
//    http://yann.lecun.com/exdb/mnist/

#include <gflags/gflags.h>
#include <glog/logging.h>
#include <google/protobuf/text_format.h>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <lmdb.h>
#include <stdint.h>
#include <sys/stat.h>

#include <fstream>  // NOLINT(readability/streams)
#include <string>

#include "caffe/proto/caffe.pb.h"

using namespace caffe;  // NOLINT(build/namespaces)
using std::string;

DEFINE_string(backend, "lmdb", "The backend for storing the result");

uint32_t swap_endian(uint32_t val) {
    val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
    return (val << 16) | (val >> 16);
}

void convert_dataset(const char* image_filename, const char* label_filename,
        const char* db_path, const string& db_backend) {
  // Open files
  std::ifstream image_file(image_filename, std::ios::in | std::ios::binary);
  std::ifstream label_file(label_filename, std::ios::in | std::ios::binary);
  CHECK(image_file) << "Unable to open file " << image_filename;
  CHECK(label_file) << "Unable to open file " << label_filename;
  // Read the magic and the meta data
  uint32_t magic;
  uint32_t num_items;
  uint32_t num_labels;
  uint32_t rows;
  uint32_t cols;

  image_file.read(reinterpret_cast<char*>(&magic), 4);
  magic = swap_endian(magic);
  CHECK_EQ(magic, 2051) << "Incorrect image file magic.";
  label_file.read(reinterpret_cast<char*>(&magic), 4);
  magic = swap_endian(magic);
  CHECK_EQ(magic, 2049) << "Incorrect label file magic.";
  image_file.read(reinterpret_cast<char*>(&num_items), 4);
  num_items = swap_endian(num_items);
  label_file.read(reinterpret_cast<char*>(&num_labels), 4);
  num_labels = swap_endian(num_labels);
  CHECK_EQ(num_items, num_labels);
  image_file.read(reinterpret_cast<char*>(&rows), 4);
  rows = swap_endian(rows);
  image_file.read(reinterpret_cast<char*>(&cols), 4);
  cols = swap_endian(cols);

  // lmdb
  MDB_env *mdb_env;
  MDB_dbi mdb_dbi;
  MDB_val mdb_key, mdb_data;
  MDB_txn *mdb_txn;
  // leveldb
  leveldb::DB* db;
  leveldb::Options options;
  options.error_if_exists = true;
  options.create_if_missing = true;
  options.write_buffer_size = 268435456;
  leveldb::WriteBatch* batch = NULL;

  // Open db
  if (db_backend == "leveldb") {  // leveldb
    LOG(INFO) << "Opening leveldb " << db_path;
    leveldb::Status status = leveldb::DB::Open(
        options, db_path, &db);
    CHECK(status.ok()) << "Failed to open leveldb " << db_path
        << ". Is it already existing?";
    batch = new leveldb::WriteBatch();
  } else if (db_backend == "lmdb") {  // lmdb
    LOG(INFO) << "Opening lmdb " << db_path;
    CHECK_EQ(mkdir(db_path, 0744), 0)
        << "mkdir " << db_path << "failed";
    CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << "mdb_env_create failed";
    CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS)  // 1TB
        << "mdb_env_set_mapsize failed";
    CHECK_EQ(mdb_env_open(mdb_env, db_path, 0, 0664), MDB_SUCCESS)
        << "mdb_env_open failed";
    CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)
        << "mdb_txn_begin failed";
    CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)
        << "mdb_open failed. Does the lmdb already exist? ";
  } else {
    LOG(FATAL) << "Unknown db backend " << db_backend;
  }

  // Storing to db
  char label;
  char* pixels = new char[rows * cols];
  int count = 0;
  const int kMaxKeyLength = 10;
  char key_cstr[kMaxKeyLength];
  string value;

  Datum datum;
  datum.set_channels(1);
  datum.set_height(rows);
  datum.set_width(cols);
  LOG(INFO) << "A total of " << num_items << " items.";
  LOG(INFO) << "Rows: " << rows << " Cols: " << cols;
  for (int item_id = 0; item_id < num_items; ++item_id) {
    image_file.read(pixels, rows * cols);
    label_file.read(&label, 1);
    datum.set_data(pixels, rows*cols);
    datum.set_label(label);
    snprintf(key_cstr, kMaxKeyLength, "%08d", item_id);
    datum.SerializeToString(&value);
    string keystr(key_cstr);

    // Put in db
    if (db_backend == "leveldb") {  // leveldb
      batch->Put(keystr, value);
    } else if (db_backend == "lmdb") {  // lmdb
      mdb_data.mv_size = value.size();
      mdb_data.mv_data = reinterpret_cast<void*>(&value[0]);
      mdb_key.mv_size = keystr.size();
      mdb_key.mv_data = reinterpret_cast<void*>(&keystr[0]);
      CHECK_EQ(mdb_put(mdb_txn, mdb_dbi, &mdb_key, &mdb_data, 0), MDB_SUCCESS)
          << "mdb_put failed";
    } else {
      LOG(FATAL) << "Unknown db backend " << db_backend;
    }

    if (++count % 1000 == 0) {
      // Commit txn
      if (db_backend == "leveldb") {  // leveldb
        db->Write(leveldb::WriteOptions(), batch);
        delete batch;
        batch = new leveldb::WriteBatch();
      } else if (db_backend == "lmdb") {  // lmdb
        CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS)
            << "mdb_txn_commit failed";
        CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)
            << "mdb_txn_begin failed";
      } else {
        LOG(FATAL) << "Unknown db backend " << db_backend;
      }
    }
  }
  // write the last batch
  if (count % 1000 != 0) {
    if (db_backend == "leveldb") {  // leveldb
      db->Write(leveldb::WriteOptions(), batch);
      delete batch;
      delete db;
    } else if (db_backend == "lmdb") {  // lmdb
      CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS) << "mdb_txn_commit failed";
      mdb_close(mdb_env, mdb_dbi);
      mdb_env_close(mdb_env);
    } else {
      LOG(FATAL) << "Unknown db backend " << db_backend;
    }
    LOG(ERROR) << "Processed " << count << " files.";
  }
  delete pixels;
}

int main(int argc, char** argv) {
#ifndef GFLAGS_GFLAGS_H_
  namespace gflags = google;
#endif

  gflags::SetUsageMessage("This script converts the MNIST dataset to\n"
        "the lmdb/leveldb format used by Caffe to load data.\n"
        "Usage:\n"
        "    convert_mnist_data [FLAGS] input_image_file input_label_file "
        "output_db_file\n"
        "The MNIST dataset could be downloaded at\n"
        "    http://yann.lecun.com/exdb/mnist/\n"
        "You should gunzip them after downloading,"
        "or directly use data/mnist/get_mnist.sh\n");
  gflags::ParseCommandLineFlags(&argc, &argv, true);

  const string& db_backend = FLAGS_backend;

  if (argc != 4) {
    gflags::ShowUsageWithFlagsRestrict(argv[0],
        "examples/mnist/convert_mnist_data");
  } else {
    google::InitGoogleLogging(argv[0]);
    convert_dataset(argv[1], argv[2], argv[3], db_backend);
  }
  return 0;
}
<commit_msg>add [] to "delete pixels".<commit_after>// This script converts the MNIST dataset to a lmdb (default) or
// leveldb (--backend=leveldb) format used by caffe to load data.
// Usage:
//    convert_mnist_data [FLAGS] input_image_file input_label_file
//                        output_db_file
// The MNIST dataset could be downloaded at
//    http://yann.lecun.com/exdb/mnist/

#include <gflags/gflags.h>
#include <glog/logging.h>
#include <google/protobuf/text_format.h>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <lmdb.h>
#include <stdint.h>
#include <sys/stat.h>

#include <fstream>  // NOLINT(readability/streams)
#include <string>

#include "caffe/proto/caffe.pb.h"

using namespace caffe;  // NOLINT(build/namespaces)
using std::string;

DEFINE_string(backend, "lmdb", "The backend for storing the result");

uint32_t swap_endian(uint32_t val) {
    val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
    return (val << 16) | (val >> 16);
}

void convert_dataset(const char* image_filename, const char* label_filename,
        const char* db_path, const string& db_backend) {
  // Open files
  std::ifstream image_file(image_filename, std::ios::in | std::ios::binary);
  std::ifstream label_file(label_filename, std::ios::in | std::ios::binary);
  CHECK(image_file) << "Unable to open file " << image_filename;
  CHECK(label_file) << "Unable to open file " << label_filename;
  // Read the magic and the meta data
  uint32_t magic;
  uint32_t num_items;
  uint32_t num_labels;
  uint32_t rows;
  uint32_t cols;

  image_file.read(reinterpret_cast<char*>(&magic), 4);
  magic = swap_endian(magic);
  CHECK_EQ(magic, 2051) << "Incorrect image file magic.";
  label_file.read(reinterpret_cast<char*>(&magic), 4);
  magic = swap_endian(magic);
  CHECK_EQ(magic, 2049) << "Incorrect label file magic.";
  image_file.read(reinterpret_cast<char*>(&num_items), 4);
  num_items = swap_endian(num_items);
  label_file.read(reinterpret_cast<char*>(&num_labels), 4);
  num_labels = swap_endian(num_labels);
  CHECK_EQ(num_items, num_labels);
  image_file.read(reinterpret_cast<char*>(&rows), 4);
  rows = swap_endian(rows);
  image_file.read(reinterpret_cast<char*>(&cols), 4);
  cols = swap_endian(cols);

  // lmdb
  MDB_env *mdb_env;
  MDB_dbi mdb_dbi;
  MDB_val mdb_key, mdb_data;
  MDB_txn *mdb_txn;
  // leveldb
  leveldb::DB* db;
  leveldb::Options options;
  options.error_if_exists = true;
  options.create_if_missing = true;
  options.write_buffer_size = 268435456;
  leveldb::WriteBatch* batch = NULL;

  // Open db
  if (db_backend == "leveldb") {  // leveldb
    LOG(INFO) << "Opening leveldb " << db_path;
    leveldb::Status status = leveldb::DB::Open(
        options, db_path, &db);
    CHECK(status.ok()) << "Failed to open leveldb " << db_path
        << ". Is it already existing?";
    batch = new leveldb::WriteBatch();
  } else if (db_backend == "lmdb") {  // lmdb
    LOG(INFO) << "Opening lmdb " << db_path;
    CHECK_EQ(mkdir(db_path, 0744), 0)
        << "mkdir " << db_path << "failed";
    CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << "mdb_env_create failed";
    CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS)  // 1TB
        << "mdb_env_set_mapsize failed";
    CHECK_EQ(mdb_env_open(mdb_env, db_path, 0, 0664), MDB_SUCCESS)
        << "mdb_env_open failed";
    CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)
        << "mdb_txn_begin failed";
    CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)
        << "mdb_open failed. Does the lmdb already exist? ";
  } else {
    LOG(FATAL) << "Unknown db backend " << db_backend;
  }

  // Storing to db
  char label;
  char* pixels = new char[rows * cols];
  int count = 0;
  const int kMaxKeyLength = 10;
  char key_cstr[kMaxKeyLength];
  string value;

  Datum datum;
  datum.set_channels(1);
  datum.set_height(rows);
  datum.set_width(cols);
  LOG(INFO) << "A total of " << num_items << " items.";
  LOG(INFO) << "Rows: " << rows << " Cols: " << cols;
  for (int item_id = 0; item_id < num_items; ++item_id) {
    image_file.read(pixels, rows * cols);
    label_file.read(&label, 1);
    datum.set_data(pixels, rows*cols);
    datum.set_label(label);
    snprintf(key_cstr, kMaxKeyLength, "%08d", item_id);
    datum.SerializeToString(&value);
    string keystr(key_cstr);

    // Put in db
    if (db_backend == "leveldb") {  // leveldb
      batch->Put(keystr, value);
    } else if (db_backend == "lmdb") {  // lmdb
      mdb_data.mv_size = value.size();
      mdb_data.mv_data = reinterpret_cast<void*>(&value[0]);
      mdb_key.mv_size = keystr.size();
      mdb_key.mv_data = reinterpret_cast<void*>(&keystr[0]);
      CHECK_EQ(mdb_put(mdb_txn, mdb_dbi, &mdb_key, &mdb_data, 0), MDB_SUCCESS)
          << "mdb_put failed";
    } else {
      LOG(FATAL) << "Unknown db backend " << db_backend;
    }

    if (++count % 1000 == 0) {
      // Commit txn
      if (db_backend == "leveldb") {  // leveldb
        db->Write(leveldb::WriteOptions(), batch);
        delete batch;
        batch = new leveldb::WriteBatch();
      } else if (db_backend == "lmdb") {  // lmdb
        CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS)
            << "mdb_txn_commit failed";
        CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)
            << "mdb_txn_begin failed";
      } else {
        LOG(FATAL) << "Unknown db backend " << db_backend;
      }
    }
  }
  // write the last batch
  if (count % 1000 != 0) {
    if (db_backend == "leveldb") {  // leveldb
      db->Write(leveldb::WriteOptions(), batch);
      delete batch;
      delete db;
    } else if (db_backend == "lmdb") {  // lmdb
      CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS) << "mdb_txn_commit failed";
      mdb_close(mdb_env, mdb_dbi);
      mdb_env_close(mdb_env);
    } else {
      LOG(FATAL) << "Unknown db backend " << db_backend;
    }
    LOG(ERROR) << "Processed " << count << " files.";
  }
  delete[] pixels;
}

int main(int argc, char** argv) {
#ifndef GFLAGS_GFLAGS_H_
  namespace gflags = google;
#endif

  gflags::SetUsageMessage("This script converts the MNIST dataset to\n"
        "the lmdb/leveldb format used by Caffe to load data.\n"
        "Usage:\n"
        "    convert_mnist_data [FLAGS] input_image_file input_label_file "
        "output_db_file\n"
        "The MNIST dataset could be downloaded at\n"
        "    http://yann.lecun.com/exdb/mnist/\n"
        "You should gunzip them after downloading,"
        "or directly use data/mnist/get_mnist.sh\n");
  gflags::ParseCommandLineFlags(&argc, &argv, true);

  const string& db_backend = FLAGS_backend;

  if (argc != 4) {
    gflags::ShowUsageWithFlagsRestrict(argv[0],
        "examples/mnist/convert_mnist_data");
  } else {
    google::InitGoogleLogging(argv[0]);
    convert_dataset(argv[1], argv[2], argv[3], db_backend);
  }
  return 0;
}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2009 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 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "common.h"

/* interface header */
#include "SDLWindow.h"
#include <iostream>

int SDLWindow::mx = 0;
int SDLWindow::my = 0;

SDLWindow::SDLWindow(const SDLDisplay* _display, SDLVisual*)
  : BzfWindow(_display), width(-1), height(-1), hasGamma(true), iconified(false)
{
}

void SDLWindow::setTitle(const char * title) {
  SDL_WM_SetCaption(title, title);
}

void SDLWindow::setFullscreen(bool on) {
  ((SDLDisplay *)getDisplay())->setFullscreen(on);
}

bool SDLWindow::getFullscreen() const {
  return ((SDLDisplay *)getDisplay())->getFullscreen();
}

void SDLWindow::deiconify() {
  std::cout << "deiconifying" << std::endl;
  iconified = false;

  create();

  if (width != -1 && height != -1) {
    std::cout << "setting the size to " << width << "x" << height << " with fullscreen set to " << getFullscreen() << std::endl;
    setSize(width, height);
    callResizeCallbacks();
  }

  callExposeCallbacks();
}

void SDLWindow::iconify() {
  int x, y;
  std::cout << "iconify toggle" << std::endl;

  if (iconified) {
    deiconify();
    return;
  }

  /* get out of fullscreen so we can unmap */
  if (getFullscreen()) {
    setFullscreen(false);
    callResizeCallbacks();
  }

  getSize(width, height);
  std::cout << "got size " << width << "x" << height << " with fullscreen set to " << getFullscreen() << std::endl;

  setSize(32, 32);
  getSize(x, y);
  std::cout << "after 32 set, got size " << x << "x" << y << " with fullscreen set to " << getFullscreen() << std::endl;

  SDL_WM_IconifyWindow();
  iconified = true;
}

void SDLWindow::warpMouse(int x, int y) {
  SDL_WarpMouse(x, y);
  SDL_PumpEvents();
#if HAVE_SDL_1_3
  int index = 0;
  SDL_GetMouseState(index, &mx, &my);
#else
  SDL_GetMouseState(&mx, &my);
#endif
}

void SDLWindow::getMouse(int& x, int& y) const {
  x = mx;
  y = my;
}

void SDLWindow::getPosition(int& x, int& y) {

// NOTE: the ifdef pattern is taken from SDL_syswm.h
// Mac OS X supports several ways of hardware accelerated rendering, including X11 and Quartz (default)

// FIXME: It is probably better to define what renderer should be used at configure time than to guess at compile time
#if defined(SDL_VIDEO_DRIVER_QUARTZ)
  x = 0;
  y = 0;
#elif defined(SDL_VIDEO_DRIVER_X11)
  SDL_SysWMinfo info;
  SDL_VERSION(&info.version);
  if (!SDL_GetWMInfo(&info)) {
    x = 0;
    y = 0;
    return;
  }
  info.info.x11.lock_func();
  Display* dpy = info.info.x11.display;
  Window   wnd = info.info.x11.window;
  Window dummy;
  XWindowAttributes attrs;
  XSync(dpy, false);
  XGetWindowAttributes(dpy, wnd, &attrs);
  XTranslateCoordinates(dpy, wnd, attrs.root, 0, 0, &x, &y, &dummy);
  info.info.x11.unlock_func();
#elif defined(SDL_VIDEO_DRIVER_NANOX)
  x = 0;
  y = 0;
#elif defined(SDL_VIDEO_DRIVER_WINDIB) || defined(SDL_VIDEO_DRIVER_DDRAW) || defined(SDL_VIDEO_DRIVER_GAPI)
  SDL_SysWMinfo pInfo;
  SDL_VERSION(&pInfo.version);
  SDL_GetWMInfo(&pInfo);
  RECT r;
  GetWindowRect(pInfo.window, &r);
  x = r.left;
  y = r.bottom;
#elif defined(SDL_VIDEO_DRIVER_RISCOS)
  x = 0;
  y = 0;
#elif defined(SDL_VIDEO_DRIVER_PHOTON)
  x = 0;
  y = 0;
#else // UNKNOWN
  x = 0;
  y = 0;
#endif // video driver type
}

void SDLWindow::setSize(int _width, int _height) {
  ((SDLDisplay *)getDisplay())->setWindowSize(_width, _height);
}

void SDLWindow::getSize(int& _width, int& _height) const {
  ((SDLDisplay *)getDisplay())->getWindowSize(_width, _height);
}

void SDLWindow::showMouse() {
  SDL_ShowCursor(1);
}

void SDLWindow::hideMouse() {
  SDL_ShowCursor(0);
}

void SDLWindow::setGamma(float gamma) {
  int result = SDL_SetGamma(gamma, gamma, gamma);
  if (result == -1) {
    printf("Could not set Gamma: %s.\n", SDL_GetError());
    hasGamma = false;
  }
}

// Code taken from SDL (not available through the headers)
static float CalculateGammaFromRamp(Uint16 ramp[256]) {
  /* The following is adapted from a post by Garrett Bass on OpenGL
     Gamedev list, March 4, 2000.
  */
  float sum = 0.0;
  int count = 0;

  float gamma = 1.0;
  for (int i = 1; i < 256; ++i) {
    if ((ramp[i] != 0) && (ramp[i] != 65535)) {
      double B = (double)i / 256.0;
      double A = ramp[i] / 65535.0;
      sum += (float) (log(A) / log(B));
      count++;
    }
  }
  if ( count && sum ) {
    gamma = 1.0f / (sum / count);
  }
  return gamma;
}

float SDLWindow::getGamma() const {
  Uint16 redRamp[256];
  Uint16 greenRamp[256];
  Uint16 blueRamp[256];
  float gamma = 1.0;
  int result = SDL_GetGammaRamp(redRamp, greenRamp, blueRamp);
  if (result == -1) {
    printf("Could not get Gamma: %s.\n", SDL_GetError());
  } else {
    float red   = CalculateGammaFromRamp(redRamp);
    float green = CalculateGammaFromRamp(greenRamp);
    float blue  = CalculateGammaFromRamp(blueRamp);
    gamma = (red + green + blue) / 3.0;
  }
  return gamma;
}

bool SDLWindow::hasGammaControl() const {
  return hasGamma;
}

void SDLWindow::swapBuffers() {
  SDL_GL_SwapBuffers();
}

bool SDLWindow::create(void) {
  if (!((SDLDisplay *)getDisplay())->createWindow()) {
    return false;
  }
  return true;
}

void SDLWindow::enableGrabMouse(bool on) {
  ((SDLDisplay *)getDisplay())->enableGrabMouse(on);
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>#ifdef not #if<commit_after>/* bzflag
 * Copyright (c) 1993 - 2009 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 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "common.h"

/* interface header */
#include "SDLWindow.h"
#include <iostream>

int SDLWindow::mx = 0;
int SDLWindow::my = 0;

SDLWindow::SDLWindow(const SDLDisplay* _display, SDLVisual*)
  : BzfWindow(_display), width(-1), height(-1), hasGamma(true), iconified(false)
{
}

void SDLWindow::setTitle(const char * title) {
  SDL_WM_SetCaption(title, title);
}

void SDLWindow::setFullscreen(bool on) {
  ((SDLDisplay *)getDisplay())->setFullscreen(on);
}

bool SDLWindow::getFullscreen() const {
  return ((SDLDisplay *)getDisplay())->getFullscreen();
}

void SDLWindow::deiconify() {
  std::cout << "deiconifying" << std::endl;
  iconified = false;

  create();

  if (width != -1 && height != -1) {
    std::cout << "setting the size to " << width << "x" << height << " with fullscreen set to " << getFullscreen() << std::endl;
    setSize(width, height);
    callResizeCallbacks();
  }

  callExposeCallbacks();
}

void SDLWindow::iconify() {
  int x, y;
  std::cout << "iconify toggle" << std::endl;

  if (iconified) {
    deiconify();
    return;
  }

  /* get out of fullscreen so we can unmap */
  if (getFullscreen()) {
    setFullscreen(false);
    callResizeCallbacks();
  }

  getSize(width, height);
  std::cout << "got size " << width << "x" << height << " with fullscreen set to " << getFullscreen() << std::endl;

  setSize(32, 32);
  getSize(x, y);
  std::cout << "after 32 set, got size " << x << "x" << y << " with fullscreen set to " << getFullscreen() << std::endl;

  SDL_WM_IconifyWindow();
  iconified = true;
}

void SDLWindow::warpMouse(int x, int y) {
  SDL_WarpMouse(x, y);
  SDL_PumpEvents();
#ifdef HAVE_SDL_1_3
  int index = 0;
  SDL_GetMouseState(index, &mx, &my);
#else
  SDL_GetMouseState(&mx, &my);
#endif
}

void SDLWindow::getMouse(int& x, int& y) const {
  x = mx;
  y = my;
}

void SDLWindow::getPosition(int& x, int& y) {

// NOTE: the ifdef pattern is taken from SDL_syswm.h
// Mac OS X supports several ways of hardware accelerated rendering, including X11 and Quartz (default)

// FIXME: It is probably better to define what renderer should be used at configure time than to guess at compile time
#if defined(SDL_VIDEO_DRIVER_QUARTZ)
  x = 0;
  y = 0;
#elif defined(SDL_VIDEO_DRIVER_X11)
  SDL_SysWMinfo info;
  SDL_VERSION(&info.version);
  if (!SDL_GetWMInfo(&info)) {
    x = 0;
    y = 0;
    return;
  }
  info.info.x11.lock_func();
  Display* dpy = info.info.x11.display;
  Window   wnd = info.info.x11.window;
  Window dummy;
  XWindowAttributes attrs;
  XSync(dpy, false);
  XGetWindowAttributes(dpy, wnd, &attrs);
  XTranslateCoordinates(dpy, wnd, attrs.root, 0, 0, &x, &y, &dummy);
  info.info.x11.unlock_func();
#elif defined(SDL_VIDEO_DRIVER_NANOX)
  x = 0;
  y = 0;
#elif defined(SDL_VIDEO_DRIVER_WINDIB) || defined(SDL_VIDEO_DRIVER_DDRAW) || defined(SDL_VIDEO_DRIVER_GAPI)
  SDL_SysWMinfo pInfo;
  SDL_VERSION(&pInfo.version);
  SDL_GetWMInfo(&pInfo);
  RECT r;
  GetWindowRect(pInfo.window, &r);
  x = r.left;
  y = r.bottom;
#elif defined(SDL_VIDEO_DRIVER_RISCOS)
  x = 0;
  y = 0;
#elif defined(SDL_VIDEO_DRIVER_PHOTON)
  x = 0;
  y = 0;
#else // UNKNOWN
  x = 0;
  y = 0;
#endif // video driver type
}

void SDLWindow::setSize(int _width, int _height) {
  ((SDLDisplay *)getDisplay())->setWindowSize(_width, _height);
}

void SDLWindow::getSize(int& _width, int& _height) const {
  ((SDLDisplay *)getDisplay())->getWindowSize(_width, _height);
}

void SDLWindow::showMouse() {
  SDL_ShowCursor(1);
}

void SDLWindow::hideMouse() {
  SDL_ShowCursor(0);
}

void SDLWindow::setGamma(float gamma) {
  int result = SDL_SetGamma(gamma, gamma, gamma);
  if (result == -1) {
    printf("Could not set Gamma: %s.\n", SDL_GetError());
    hasGamma = false;
  }
}

// Code taken from SDL (not available through the headers)
static float CalculateGammaFromRamp(Uint16 ramp[256]) {
  /* The following is adapted from a post by Garrett Bass on OpenGL
     Gamedev list, March 4, 2000.
  */
  float sum = 0.0;
  int count = 0;

  float gamma = 1.0;
  for (int i = 1; i < 256; ++i) {
    if ((ramp[i] != 0) && (ramp[i] != 65535)) {
      double B = (double)i / 256.0;
      double A = ramp[i] / 65535.0;
      sum += (float) (log(A) / log(B));
      count++;
    }
  }
  if ( count && sum ) {
    gamma = 1.0f / (sum / count);
  }
  return gamma;
}

float SDLWindow::getGamma() const {
  Uint16 redRamp[256];
  Uint16 greenRamp[256];
  Uint16 blueRamp[256];
  float gamma = 1.0;
  int result = SDL_GetGammaRamp(redRamp, greenRamp, blueRamp);
  if (result == -1) {
    printf("Could not get Gamma: %s.\n", SDL_GetError());
  } else {
    float red   = CalculateGammaFromRamp(redRamp);
    float green = CalculateGammaFromRamp(greenRamp);
    float blue  = CalculateGammaFromRamp(blueRamp);
    gamma = (red + green + blue) / 3.0;
  }
  return gamma;
}

bool SDLWindow::hasGammaControl() const {
  return hasGamma;
}

void SDLWindow::swapBuffers() {
  SDL_GL_SwapBuffers();
}

bool SDLWindow::create(void) {
  if (!((SDLDisplay *)getDisplay())->createWindow()) {
    return false;
  }
  return true;
}

void SDLWindow::enableGrabMouse(bool on) {
  ((SDLDisplay *)getDisplay())->enableGrabMouse(on);
}

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


<commit_before><commit_msg>:bug: fix(chunk): fixed instruction offset bug of disassemble instruction<commit_after><|endoftext|>


<commit_before>//#include <core/PluginHandler.h>

namespace prodbg
{

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static int main(int argc, char** argv)
{
	(void)argc;
	(void)argv;
	return 0;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main(int argc, char** argv)
{
	return prodbg::main(argc, argv);
}
<commit_msg>Made Win64 build<commit_after>#ifdef PRODBG_WIN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

namespace prodbg
{

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static int main(int argc, char** argv)
{
	(void)argc;
	(void)argv;
	return 0;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#ifdef PRODBG_WIN

int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
	return prodbg::main(0, 0);
}

#else

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main(int argc, char** argv)
{
	return prodbg::main(argc, argv);
}

#endif
<|endoftext|>


<commit_before>/**
 *  Copyright (C) 2015, 2016 Topology LP
 *  All rights reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to
 *  deal in the Software without restriction, including without limitation the
 *  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 *  sell copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 *  IN THE SOFTWARE.
 */

#ifndef CPPCODEC_BASE32_HEX
#define CPPCODEC_BASE32_HEX

#include "detail/codec.hpp"
#include "detail/base32.hpp"

namespace cppcodec {

namespace detail {

// RFC 4648 uses a simple alphabet: A-Z starting at index 0, then 2-7 starting at index 26.
static constexpr const char base32_hex_alphabet[] = {
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
    'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'
};

class base32_hex
{
public:
    template <typename Codec> using codec_impl = stream_codec<Codec, base32_hex>;

    static CPPCODEC_ALWAYS_INLINE constexpr size_t alphabet_size() {
        static_assert(sizeof(base32_hex_alphabet) == 32, "base32 alphabet must have 32 values");
        return sizeof(base32_hex_alphabet);
    }
    static CPPCODEC_ALWAYS_INLINE constexpr char symbol(alphabet_index_t idx)
    {
        return base32_hex_alphabet[idx];
    }
    static CPPCODEC_ALWAYS_INLINE constexpr char normalized_symbol(char c)
    {
        // Lower-case letters are accepted, though not generally expected.
        return (c >= 'a' && c <= 'v') ? (c - 'a' + 'A') : c;
    }

    static CPPCODEC_ALWAYS_INLINE constexpr bool generates_padding() { return true; }
    static CPPCODEC_ALWAYS_INLINE constexpr bool requires_padding() { return true; }
    static CPPCODEC_ALWAYS_INLINE constexpr char padding_symbol() { return '='; }
    static CPPCODEC_ALWAYS_INLINE constexpr bool is_padding_symbol(char c) { return c == '='; }
    static CPPCODEC_ALWAYS_INLINE constexpr bool is_eof_symbol(char c) { return c == '\0'; }

    // RFC4648 does not specify any whitespace being allowed in base32 encodings.
    static CPPCODEC_ALWAYS_INLINE constexpr bool should_ignore(char) { return false; }
};

} // namespace detail

using base32_hex = detail::codec<detail::base32<detail::base32_hex>>;

} // namespace cppcodec

#endif // CPPCODEC_BASE32_HEX
<commit_msg>Fix comment referring to the wrong RFC encoding<commit_after>/**
 *  Copyright (C) 2015, 2016 Topology LP
 *  All rights reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to
 *  deal in the Software without restriction, including without limitation the
 *  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 *  sell copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 *  IN THE SOFTWARE.
 */

#ifndef CPPCODEC_BASE32_HEX
#define CPPCODEC_BASE32_HEX

#include "detail/codec.hpp"
#include "detail/base32.hpp"

namespace cppcodec {

namespace detail {

// RFC 4648 also specifies a hex encoding system which uses 0-9, then A-V.
static constexpr const char base32_hex_alphabet[] = {
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
    'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'
};

class base32_hex
{
public:
    template <typename Codec> using codec_impl = stream_codec<Codec, base32_hex>;

    static CPPCODEC_ALWAYS_INLINE constexpr size_t alphabet_size() {
        static_assert(sizeof(base32_hex_alphabet) == 32, "base32 alphabet must have 32 values");
        return sizeof(base32_hex_alphabet);
    }
    static CPPCODEC_ALWAYS_INLINE constexpr char symbol(alphabet_index_t idx)
    {
        return base32_hex_alphabet[idx];
    }
    static CPPCODEC_ALWAYS_INLINE constexpr char normalized_symbol(char c)
    {
        // Lower-case letters are accepted, though not generally expected.
        return (c >= 'a' && c <= 'v') ? (c - 'a' + 'A') : c;
    }

    static CPPCODEC_ALWAYS_INLINE constexpr bool generates_padding() { return true; }
    static CPPCODEC_ALWAYS_INLINE constexpr bool requires_padding() { return true; }
    static CPPCODEC_ALWAYS_INLINE constexpr char padding_symbol() { return '='; }
    static CPPCODEC_ALWAYS_INLINE constexpr bool is_padding_symbol(char c) { return c == '='; }
    static CPPCODEC_ALWAYS_INLINE constexpr bool is_eof_symbol(char c) { return c == '\0'; }

    // RFC4648 does not specify any whitespace being allowed in base32 encodings.
    static CPPCODEC_ALWAYS_INLINE constexpr bool should_ignore(char) { return false; }
};

} // namespace detail

using base32_hex = detail::codec<detail::base32<detail::base32_hex>>;

} // namespace cppcodec

#endif // CPPCODEC_BASE32_HEX
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "WrapHelper.h"

#include "../player/CameraNode.h"
#include "../player/Image.h"
#include "../player/Video.h"
#include "../player/Words.h"

using namespace boost::python;
using namespace avg;
using namespace std;

void export_raster()
{
    boost::python::to_python_converter<vector<DPoint>,
        to_list<vector<DPoint> > >();
    boost::python::to_python_converter<VertexGrid,
        to_list<VertexGrid> >();

    from_python_sequence<vector<DPoint>, variable_capacity_policy>();
    from_python_sequence<VertexGrid, variable_capacity_policy>();

    class_<RasterNode, bases<Node>, boost::noncopyable>("RasterNode",
            "Base class for all nodes that have a direct 2d raster representation.\n"
            "This includes Image, Word, Camera, and Video nodes. RasterNodes can\n"
            "be rotated. Warping of RasterNodes is implemented using a grid of\n"
            "reference points. The position of each of these points can be changed.\n",
            no_init)
        .def("getOrigVertexCoords", &RasterNode::getOrigVertexCoords,
                "getOrigVertexCoords()\n"
                "Returns the unwarped coordinate of all vertices as a list\n"
                "of lists.")
        .def("getWarpedVertexCoords", &RasterNode::getWarpedVertexCoords,
                "getWarpedVertexCoords()\n"
                "Returnes the current coordinate of all vertices as a list\n"
                "of lists.")
        .def("setWarpedVertexCoords", &RasterNode::setWarpedVertexCoords,
                "setWarpedVertexCoords(grid)\n"
                "Changes the current coordinates of all vertices.\n"
                "@param grid: list of lists of coordinate tuples.")
        .def("getBitmap", &RasterNode::getBitmap,
                return_value_policy<manage_new_object>(),
                "getBitmap() -> Bitmap\n\n"
                "Returns a copy of the bitmap that the node contains.")
        .add_property("maxtilewidth", &RasterNode::getMaxTileWidth,
                "The maximum width and height of the\n"
                "tiles used for warping. The effective tile size is also\n"
                "dependent on hardware and driver limits. (ro)\n")
        .add_property("maxtileheight", &RasterNode::getMaxTileHeight,
                "The maximum width and height of the\n"
                "tiles used for warping. The effective tile size is also\n"
                "dependent on hardware and driver limits. (ro)\n")
        .add_property("blendmode",
                make_function(&RasterNode::getBlendModeStr,
                        return_value_policy<copy_const_reference>()),
                &RasterNode::setBlendModeStr,
                "The method of compositing the node with the nodes under\n"
                "it. Valid values are 'blend', 'add', 'min' and 'max'.")
    ;

    class_<Image, bases<RasterNode> >("Image",
            "A static raster image on the screen. Images are loaded from files on\n"
            "program start. Alpha channels of the image files are used as\n"
            "transparency information.\n",
            no_init)
        .def("setBitmap", &Image::setBitmap,
                "setBitmap(bitmap)\n"
                "Sets the bitmap pixels of the image.\n"
                "@param bitmap: A libavg bitmap object to use.")
        .add_property("href",
                make_function(&Image::getHRef,
                        return_value_policy<copy_const_reference>()),
                make_function(&Image::setHRef,
                        return_value_policy<copy_const_reference>()),
                "The source filename of the image.\n")
        .add_property("hue", &Image::getHue,
                "A hue to color the image in (ro, deprecated).\n")
        .add_property("saturation", &Image::getSaturation,
                "The saturation the image should have (ro, deprecated).\n")
    ;

    class_<VideoBase, bases<RasterNode>, boost::noncopyable>("VideoBase",
            "Base class for video and camera image nodes.",
            no_init)
        .def("play", &VideoBase::play,
                "play()\n"
                "Starts video playback.")
        .def("stop", &VideoBase::stop,
                "stop()\n"
                "Stops video playback. Closes the object and 'rewinds' the playback\n"
                "cursor.")
        .def("pause", &VideoBase::pause,
                "pause()\n"
                "Stops video playback but doesn't close the object. The playback\n"
                "cursor stays at the same position.")
        .def("getFPS", &VideoBase::getFPS,
                "getFPS()\n"
                "Returns the nominal frames per second the object should display at.\n")
    ;

    class_<CameraNode, bases<VideoBase> >("Camera",
            "A node that displays the image of a camera. The properties are the same\n"
            "as the camera properties in .avgtrackerrc and are explained under\n"
            "U{https://www.libavg.de/wiki/index.php/Tracker_Setup}.",
            no_init)
        .add_property("device", make_function(&CameraNode::getDevice,
                return_value_policy<copy_const_reference>()))
        .add_property("drivername", make_function(&CameraNode::getDriverName,
                return_value_policy<copy_const_reference>()))
        .add_property("framerate", &CameraNode::getFrameRate)
        .add_property("framenum", &CameraNode::getFrameNum)
        .add_property("brightness", &CameraNode::getBrightness, &CameraNode::setBrightness)
        .add_property("exposure", &CameraNode::getExposure, &CameraNode::setExposure)
        .add_property("sharpness", &CameraNode::getSharpness, &CameraNode::setSharpness)
        .add_property("saturation", &CameraNode::getSaturation, &CameraNode::setSaturation)
        .add_property("gamma", &CameraNode::getGamma, &CameraNode::setGamma)
        .add_property("shutter", &CameraNode::getShutter, &CameraNode::setShutter)
        .add_property("gain", &CameraNode::getGain, &CameraNode::setGain)
        .add_property("whitebalance", &CameraNode::getWhiteBalance,
                &CameraNode::setWhiteBalance)
    ;

    class_<Video, bases<VideoBase> >("Video",
            "Video nodes display a video file. Video formats and codecs supported\n"
            "are all formats that ffmpeg/libavcodec supports.\n",
            no_init)
        .def("getNumFrames", &Video::getNumFrames,
                "getNumFrames()")
        .def("getCurFrame", &Video::getCurFrame,
                "getCurFrame()\n"
                "Returns the video frame currently playing.")
        .def("seekToFrame", &Video::seekToFrame,
                "seekToFrame(num)\n"
                "Moves the playback cursor to the frame given.")
        .def("setEOFCallback", &Video::setEOFCallback,
                "setEOFCallback(pyfunc)\n"
                "Sets a python callable to be invoked when the video reaches end of file.")
        .add_property("href",
                make_function(&Video::getHRef,
                        return_value_policy<copy_const_reference>()),
                make_function(&Video::setHRef,
                        return_value_policy<copy_const_reference>()),
                "The source filename of the video (ro).\n")
        .add_property("loop", &Video::getLoop,
                "Whether to start the video again when it has ended (ro).\n")
    ;

    class_<Words, bases<RasterNode> >("Words",
            "A words node displays formatted text. Rendering is done by pango. All\n"
            "properties are set in pixels. International and multi-byte character\n"
            "sets are fully supported. Words nodes should use UTF-8 to encode\n"
            "international characters.\n",
            no_init)
        .add_property("font",
                make_function(&Words::getFont,
                        return_value_policy<copy_const_reference>()),
                make_function(&Words::setFont,
                        return_value_policy<copy_const_reference>()),
                "The family name of the truetype font to use. This font must\n"
                "be installed in the system, for instance using the installfonts.sh\n"
                "script in the main libavg source directory.\n")
        .add_property("text",
                make_function(&Words::getText,
                        return_value_policy<copy_const_reference>()),
                make_function(&Words::setText,
                        return_value_policy<copy_const_reference>()),
                "The string to display. In the avg file, this is either the\n"
                "text attribute of the words node or the content of the words\n"
                "node itself. In the second case, the string can be formatted\n"
                "using the pango text attribute markup language described at\n"
                "U{http://developer.gnome.org/doc/API/2.0/pango/PangoMarkupFormat.html}.\n"
                "Markup can also be used if the text is set using python.\n")
        .add_property("color",
                make_function(&Words::getColor,
                        return_value_policy<copy_const_reference>()),
                make_function(&Words::setColor,
                        return_value_policy<copy_const_reference>()),
                "The color of the text in standard html color notation:\n"
                "FF0000 is red, 00FF00 green, etc.\n")
        .add_property("size", &Words::getSize, &Words::setSize,
                "The font size in pixels. Fractional sizes are supported.\n")
        .add_property("parawidth", &Words::getParaWidth, &Words::setParaWidth,
                "The width at which to word-wrap.\n")
        .add_property("indent", &Words::getIndent, &Words::setIndent,
                "The indentation of the first line of the paragraph.\n")
        .add_property("linespacing", &Words::getLineSpacing, &Words::setLineSpacing,
                "The number of pixels between different lines of a\n"
                "paragraph.\n")
        .add_property("alignment", &Words::getAlignment, &Words::setAlignment,
                "The paragraph alignment. Possible values are 'left',\n"
                "'center' and 'right'.\n")
        .add_property("weight", &Words::getWeight, &Words::setWeight,
                "Sets the character weight. Possible values are\n"
                "'ultralight', 'light', 'normal', 'semibold', 'bold', 'ultrabold'\n"
                "and 'heavy'. This value is mapped to the weights implemented\n"
                "in the font chosen. In most cases, working weights are limited\n"
                "to 'normal' and 'bold'.\n")
        .add_property("italic", &Words::getItalic, &Words::setItalic,
                "Boolean value that determines if the text is displayed in italic.\n")
        .add_property("stretch", &Words::getStretch,&Words::setStretch,
                "One of 'ultracondensed', 'extracondensed', 'condensed',\n"
                "'semicondensed', 'normal', 'semiexpanded', 'expanded',\n"
                "'extraexpanded' and 'ultraexpanded'. Not implemented in most\n"
                "fonts.\n")
        .add_property("smallcaps", &Words::getSmallCaps, &Words::setSmallCaps)
    ;
}
<commit_msg>Made VideoBase::fps into a readonly property since it is an xml attribute as well.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "WrapHelper.h"

#include "../player/CameraNode.h"
#include "../player/Image.h"
#include "../player/Video.h"
#include "../player/Words.h"

using namespace boost::python;
using namespace avg;
using namespace std;

void export_raster()
{
    boost::python::to_python_converter<vector<DPoint>,
        to_list<vector<DPoint> > >();
    boost::python::to_python_converter<VertexGrid,
        to_list<VertexGrid> >();

    from_python_sequence<vector<DPoint>, variable_capacity_policy>();
    from_python_sequence<VertexGrid, variable_capacity_policy>();

    class_<RasterNode, bases<Node>, boost::noncopyable>("RasterNode",
            "Base class for all nodes that have a direct 2d raster representation.\n"
            "This includes Image, Word, Camera, and Video nodes. RasterNodes can\n"
            "be rotated. Warping of RasterNodes is implemented using a grid of\n"
            "reference points. The position of each of these points can be changed.\n",
            no_init)
        .def("getOrigVertexCoords", &RasterNode::getOrigVertexCoords,
                "getOrigVertexCoords()\n"
                "Returns the unwarped coordinate of all vertices as a list\n"
                "of lists.")
        .def("getWarpedVertexCoords", &RasterNode::getWarpedVertexCoords,
                "getWarpedVertexCoords()\n"
                "Returnes the current coordinate of all vertices as a list\n"
                "of lists.")
        .def("setWarpedVertexCoords", &RasterNode::setWarpedVertexCoords,
                "setWarpedVertexCoords(grid)\n"
                "Changes the current coordinates of all vertices.\n"
                "@param grid: list of lists of coordinate tuples.")
        .def("getBitmap", &RasterNode::getBitmap,
                return_value_policy<manage_new_object>(),
                "getBitmap() -> Bitmap\n\n"
                "Returns a copy of the bitmap that the node contains.")
        .add_property("maxtilewidth", &RasterNode::getMaxTileWidth,
                "The maximum width and height of the\n"
                "tiles used for warping. The effective tile size is also\n"
                "dependent on hardware and driver limits. (ro)\n")
        .add_property("maxtileheight", &RasterNode::getMaxTileHeight,
                "The maximum width and height of the\n"
                "tiles used for warping. The effective tile size is also\n"
                "dependent on hardware and driver limits. (ro)\n")
        .add_property("blendmode",
                make_function(&RasterNode::getBlendModeStr,
                        return_value_policy<copy_const_reference>()),
                &RasterNode::setBlendModeStr,
                "The method of compositing the node with the nodes under\n"
                "it. Valid values are 'blend', 'add', 'min' and 'max'.")
    ;

    class_<Image, bases<RasterNode> >("Image",
            "A static raster image on the screen. Images are loaded from files on\n"
            "program start. Alpha channels of the image files are used as\n"
            "transparency information.\n",
            no_init)
        .def("setBitmap", &Image::setBitmap,
                "setBitmap(bitmap)\n"
                "Sets the bitmap pixels of the image.\n"
                "@param bitmap: A libavg bitmap object to use.")
        .add_property("href",
                make_function(&Image::getHRef,
                        return_value_policy<copy_const_reference>()),
                make_function(&Image::setHRef,
                        return_value_policy<copy_const_reference>()),
                "The source filename of the image.\n")
        .add_property("hue", &Image::getHue,
                "A hue to color the image in (ro, deprecated).\n")
        .add_property("saturation", &Image::getSaturation,
                "The saturation the image should have (ro, deprecated).\n")
    ;

    class_<VideoBase, bases<RasterNode>, boost::noncopyable>("VideoBase",
            "Base class for video and camera image nodes.",
            no_init)
        .def("play", &VideoBase::play,
                "play()\n"
                "Starts video playback.")
        .def("stop", &VideoBase::stop,
                "stop()\n"
                "Stops video playback. Closes the object and 'rewinds' the playback\n"
                "cursor.")
        .def("pause", &VideoBase::pause,
                "pause()\n"
                "Stops video playback but doesn't close the object. The playback\n"
                "cursor stays at the same position.")
        .add_property("fps", &VideoBase::getFPS,
                "Returns the nominal frames per second the object should display at.\n")
    ;

    class_<CameraNode, bases<VideoBase> >("Camera",
            "A node that displays the image of a camera. The properties are the same\n"
            "as the camera properties in .avgtrackerrc and are explained under\n"
            "U{https://www.libavg.de/wiki/index.php/Tracker_Setup}.",
            no_init)
        .add_property("device", make_function(&CameraNode::getDevice,
                return_value_policy<copy_const_reference>()))
        .add_property("drivername", make_function(&CameraNode::getDriverName,
                return_value_policy<copy_const_reference>()))
        .add_property("framerate", &CameraNode::getFrameRate)
        .add_property("framenum", &CameraNode::getFrameNum)
        .add_property("brightness", &CameraNode::getBrightness, &CameraNode::setBrightness)
        .add_property("exposure", &CameraNode::getExposure, &CameraNode::setExposure)
        .add_property("sharpness", &CameraNode::getSharpness, &CameraNode::setSharpness)
        .add_property("saturation", &CameraNode::getSaturation, &CameraNode::setSaturation)
        .add_property("gamma", &CameraNode::getGamma, &CameraNode::setGamma)
        .add_property("shutter", &CameraNode::getShutter, &CameraNode::setShutter)
        .add_property("gain", &CameraNode::getGain, &CameraNode::setGain)
        .add_property("whitebalance", &CameraNode::getWhiteBalance,
                &CameraNode::setWhiteBalance)
    ;

    class_<Video, bases<VideoBase> >("Video",
            "Video nodes display a video file. Video formats and codecs supported\n"
            "are all formats that ffmpeg/libavcodec supports.\n",
            no_init)
        .def("getNumFrames", &Video::getNumFrames,
                "getNumFrames()")
        .def("getCurFrame", &Video::getCurFrame,
                "getCurFrame()\n"
                "Returns the video frame currently playing.")
        .def("seekToFrame", &Video::seekToFrame,
                "seekToFrame(num)\n"
                "Moves the playback cursor to the frame given.")
        .def("setEOFCallback", &Video::setEOFCallback,
                "setEOFCallback(pyfunc)\n"
                "Sets a python callable to be invoked when the video reaches end of file.")
        .add_property("href",
                make_function(&Video::getHRef,
                        return_value_policy<copy_const_reference>()),
                make_function(&Video::setHRef,
                        return_value_policy<copy_const_reference>()),
                "The source filename of the video (ro).\n")
        .add_property("loop", &Video::getLoop,
                "Whether to start the video again when it has ended (ro).\n")
    ;

    class_<Words, bases<RasterNode> >("Words",
            "A words node displays formatted text. Rendering is done by pango. All\n"
            "properties are set in pixels. International and multi-byte character\n"
            "sets are fully supported. Words nodes should use UTF-8 to encode\n"
            "international characters.\n",
            no_init)
        .add_property("font",
                make_function(&Words::getFont,
                        return_value_policy<copy_const_reference>()),
                make_function(&Words::setFont,
                        return_value_policy<copy_const_reference>()),
                "The family name of the truetype font to use. This font must\n"
                "be installed in the system, for instance using the installfonts.sh\n"
                "script in the main libavg source directory.\n")
        .add_property("text",
                make_function(&Words::getText,
                        return_value_policy<copy_const_reference>()),
                make_function(&Words::setText,
                        return_value_policy<copy_const_reference>()),
                "The string to display. In the avg file, this is either the\n"
                "text attribute of the words node or the content of the words\n"
                "node itself. In the second case, the string can be formatted\n"
                "using the pango text attribute markup language described at\n"
                "U{http://developer.gnome.org/doc/API/2.0/pango/PangoMarkupFormat.html}.\n"
                "Markup can also be used if the text is set using python.\n")
        .add_property("color",
                make_function(&Words::getColor,
                        return_value_policy<copy_const_reference>()),
                make_function(&Words::setColor,
                        return_value_policy<copy_const_reference>()),
                "The color of the text in standard html color notation:\n"
                "FF0000 is red, 00FF00 green, etc.\n")
        .add_property("size", &Words::getSize, &Words::setSize,
                "The font size in pixels. Fractional sizes are supported.\n")
        .add_property("parawidth", &Words::getParaWidth, &Words::setParaWidth,
                "The width at which to word-wrap.\n")
        .add_property("indent", &Words::getIndent, &Words::setIndent,
                "The indentation of the first line of the paragraph.\n")
        .add_property("linespacing", &Words::getLineSpacing, &Words::setLineSpacing,
                "The number of pixels between different lines of a\n"
                "paragraph.\n")
        .add_property("alignment", &Words::getAlignment, &Words::setAlignment,
                "The paragraph alignment. Possible values are 'left',\n"
                "'center' and 'right'.\n")
        .add_property("weight", &Words::getWeight, &Words::setWeight,
                "Sets the character weight. Possible values are\n"
                "'ultralight', 'light', 'normal', 'semibold', 'bold', 'ultrabold'\n"
                "and 'heavy'. This value is mapped to the weights implemented\n"
                "in the font chosen. In most cases, working weights are limited\n"
                "to 'normal' and 'bold'.\n")
        .add_property("italic", &Words::getItalic, &Words::setItalic,
                "Boolean value that determines if the text is displayed in italic.\n")
        .add_property("stretch", &Words::getStretch,&Words::setStretch,
                "One of 'ultracondensed', 'extracondensed', 'condensed',\n"
                "'semicondensed', 'normal', 'semiexpanded', 'expanded',\n"
                "'extraexpanded' and 'ultraexpanded'. Not implemented in most\n"
                "fonts.\n")
        .add_property("smallcaps", &Words::getSmallCaps, &Words::setSmallCaps)
    ;
}
<|endoftext|>


<commit_before>#include "bvs/bvs.h"

BVS::BVS* bvs;
BVS::Logger logger("Daemon");

int testLogger();
int testConfig();

/** BVSD namespace, contains only the bvs daemon. */
namespace BVSD
{
/** BVS framework's command line daemon.
 * This is a simple command line daemon. It serves as a client to the BVS
 * framework. It is also intended as a sample client.
 *
 * It is interactive, you can use the following commands by just entering them
 * on the command line and then pressing enter (short versions are also
 * available, enter 'help<enter>' to see them):
 *
 * @li \c run run system until paused.
 * @li \c continue same as run
 * @li \c step advance system by one step.
 * @li \c pause pause(stop) system.
 * @li \c test call test functions.
 * @li \c quit shutdown system and quit.
 * @li \c help show help.
 */
	class BVSD
	{
	};
}

/** Main function, creates interactive loop. */
int main(int argc, char** argv)
{
	LOG(2, "starting!");
	bvs = new BVS::BVS(argc, argv);

	LOG(2, "loading modules!");
	bvs->loadModules();

	LOG(2, "connecting modules!");
	bvs->connectAllModules();

	LOG(2, "starting!");
	bvs->start();

	//bvs->run();

	std::string input;
	while (input != "q" && input != "quit")
	{
		std::getline(std::cin, input);

		if (input == "r" || input == "run" || input == "c" || input == "continue")
		{
			LOG(2, "RUN!!!");
			bvs->run();
		}
		else if (input.empty() || input == "s" || input == "step")
		{
			LOG(2, "STEP!!!");
			bvs->step();
		}
		else if (input == "p" || input == "pause")
		{
			LOG(2, "PAUSING!!!");
			bvs->pause();
		}
		else if (input == "t" || input == "test")
		{
			testLogger();
			testConfig();
		}
		else if (input.substr(0,2) == "hs" || input.substr(0, 7) == "hotswap")
		{
			size_t delimiter = input.find_first_of(" ");
			input.erase(0, delimiter+1);
			if (input.empty() || delimiter==std::string::npos) std::cout << "ERROR: no module ID given!" << std::endl;
			else bvs->hotSwap(input);
		}
		else if (input == "q" || input == "quit")
		{
			LOG(2, "quitting...");
			bvs->quit();
			LOG(2, "finished!");
		}
		else if (input == "h" || input == "help")
		{
			std::cout << "usage:" << std::endl;
			std::cout << "   r|run            run system until paused" << std::endl;
			std::cout << "   c|continue       same as run" << std::endl;
			std::cout << "   s|step           advance system by one step" << std::endl;
			std::cout << "   p|pause          pause(stop) system" << std::endl;
			std::cout << "   hs|hotswap <arg> HotSwap(TM) <moduleID>" << std::endl;
			std::cout << "   t|test           call test functions" << std::endl;
			std::cout << "   q|quit           shutdown system and quit" << std::endl;
			std::cout << "   h|help           show help" << std::endl;
		}
	}

	delete bvs;

	return 0;
}

/** Performs some logger tests.
 * This functions performs some tests on the logger system. Nothing fancy, can
 * be studied to gain some insight into using the logger system.
 */
int testLogger()
{
	LOG(0, "to CLI FILE");
	bvs->disableLogConsole();
	LOG(0, "to FILE only");

	BVS::Logger file("FILE LOG", 3, BVS::Logger::TO_FILE);
	file.out(0) << "FILE ONLY" << std::endl;

	bvs->enableLogConsole();
	BVS::Logger cli("CLI LOG", 3, BVS::Logger::TO_CLI);
	cli.out(0) << "CLI ONLY" << std::endl;

	bvs->disableLogConsole();
	bvs->disableLogFile();
	LOG(0, "NOOP");

	bvs->enableLogConsole();
	LOG(0, "to CLI");

	bvs->disableLogConsole();
	bvs->enableLogFile("BVSLog.txt", true);
	LOG(0, "to FILE AGAIN");

	bvs->enableLogConsole();
	BVS::Logger both("to BOTH", 0, BVS::Logger::TO_CLI_AND_FILE);
	both.out(0) << "to CLI AND FILE" << std::endl;

	return 0;
}

/** Performs some config tests.
 * This functions performs some tests on the config system. Nothing fancy, can
 * be studied to gain some insight into using the config system.
 */
int testConfig()
{
	LOG(0, "testing...");

	int i;
	std::string s;
	bool b;

	bvs->config.getValue("BVS.logVerbosity", i, 0)
		.getValue("BVS.logFile", s, std::string("default"))
		.getValue("BVS.logSystem", b, false);

	LOG(0, "Getting int: " << i);
	LOG(0, "Getting string: " << s);
	LOG(0, "Getting bool: " << b);

	i = bvs->config.getValue<int>("BVS.logVerbosity", 0);
	s = bvs->config.getValue<std::string>("BVS.logFile", std::string("default"));
	b = bvs->config.getValue<bool>("BVS.logSystem", false);

	LOG(0, "Getting int directly: " << i);
	LOG(0, "Getting string directly: " << s);
	LOG(0, "Getting bool directly: " << b);

	std::string empty;
	bvs->config.getValue("this.option.does.not.exist", empty, std::string("empty"));
	LOG(0, "This should be 'empty': " << empty);

	std::vector<std::string> list;
	bvs->config.getValue("BVS.modules", list);
	LOG(0, "List: BVS.modules");
	int count = 0;
	for (auto& it : list)
	{
		(void) it;
		(void) count;
		LOG(0, count++ << ": " << it);
	}

	return 0;
}

<commit_msg>daemon: set 'run' as default state and add help message for unknown commands<commit_after>#include "bvs/bvs.h"

BVS::BVS* bvs;
BVS::Logger logger("Daemon");

int testLogger();
int testConfig();

/** BVSD namespace, contains only the bvs daemon. */
namespace BVSD
{
/** BVS framework's command line daemon.
 * This is a simple command line daemon. It serves as a client to the BVS
 * framework. It is also intended as a sample client.
 *
 * It is interactive, you can use the following commands by just entering them
 * on the command line and then pressing enter (short versions are also
 * available, enter 'help<enter>' to see them):
 *
 * @li \c run run system until paused.
 * @li \c continue same as run
 * @li \c step advance system by one step.
 * @li \c pause pause(stop) system.
 * @li \c test call test functions.
 * @li \c quit shutdown system and quit.
 * @li \c help show help.
 */
	class BVSD
	{
	};
}

/** Main function, creates interactive loop. */
int main(int argc, char** argv)
{
	LOG(2, "starting!");
	bvs = new BVS::BVS(argc, argv);

	LOG(2, "loading modules!");
	bvs->loadModules();

	LOG(2, "connecting modules!");
	bvs->connectAllModules();

	LOG(2, "starting!");
	bvs->start();

	bvs->run();

	std::string input;
	while (input != "q" && input != "quit")
	{
		std::getline(std::cin, input);

		if (input == "r" || input == "run" || input == "c" || input == "continue")
		{
			LOG(2, "RUN!!!");
			bvs->run();
		}
		else if (input.empty() || input == "s" || input == "step")
		{
			LOG(2, "STEP!!!");
			bvs->step();
		}
		else if (input == "p" || input == "pause")
		{
			LOG(2, "PAUSING!!!");
			bvs->pause();
		}
		else if (input == "t" || input == "test")
		{
			testLogger();
			testConfig();
		}
		else if (input.substr(0,2) == "hs" || input.substr(0, 7) == "hotswap")
		{
			size_t delimiter = input.find_first_of(" ");
			input.erase(0, delimiter+1);
			if (input.empty() || delimiter==std::string::npos) std::cout << "ERROR: no module ID given!" << std::endl;
			else bvs->hotSwap(input);
		}
		else if (input == "q" || input == "quit")
		{
			LOG(2, "quitting...");
			bvs->quit();
			LOG(2, "finished!");
		}
		else if (input == "h" || input == "help")
		{
			std::cout << "usage:" << std::endl;
			std::cout << "   r|run            run system until paused" << std::endl;
			std::cout << "   c|continue       same as run" << std::endl;
			std::cout << "   s|step           advance system by one step" << std::endl;
			std::cout << "   p|pause          pause(stop) system" << std::endl;
			std::cout << "   hs|hotswap <arg> HotSwap(TM) <moduleID>" << std::endl;
			std::cout << "   t|test           call test functions" << std::endl;
			std::cout << "   q|quit           shutdown system and quit" << std::endl;
			std::cout << "   h|help           show help" << std::endl;
		}
		else
		{
			std::cout << ">>> unknown command: " << input << std::endl << ">>> for help press 'h<enter>'!" << std::endl;
		}
	}

	delete bvs;

	return 0;
}

/** Performs some logger tests.
 * This functions performs some tests on the logger system. Nothing fancy, can
 * be studied to gain some insight into using the logger system.
 */
int testLogger()
{
	LOG(0, "to CLI FILE");
	bvs->disableLogConsole();
	LOG(0, "to FILE only");

	BVS::Logger file("FILE LOG", 3, BVS::Logger::TO_FILE);
	file.out(0) << "FILE ONLY" << std::endl;

	bvs->enableLogConsole();
	BVS::Logger cli("CLI LOG", 3, BVS::Logger::TO_CLI);
	cli.out(0) << "CLI ONLY" << std::endl;

	bvs->disableLogConsole();
	bvs->disableLogFile();
	LOG(0, "NOOP");

	bvs->enableLogConsole();
	LOG(0, "to CLI");

	bvs->disableLogConsole();
	bvs->enableLogFile("BVSLog.txt", true);
	LOG(0, "to FILE AGAIN");

	bvs->enableLogConsole();
	BVS::Logger both("to BOTH", 0, BVS::Logger::TO_CLI_AND_FILE);
	both.out(0) << "to CLI AND FILE" << std::endl;

	return 0;
}

/** Performs some config tests.
 * This functions performs some tests on the config system. Nothing fancy, can
 * be studied to gain some insight into using the config system.
 */
int testConfig()
{
	LOG(0, "testing...");

	int i;
	std::string s;
	bool b;

	bvs->config.getValue("BVS.logVerbosity", i, 0)
		.getValue("BVS.logFile", s, std::string("default"))
		.getValue("BVS.logSystem", b, false);

	LOG(0, "Getting int: " << i);
	LOG(0, "Getting string: " << s);
	LOG(0, "Getting bool: " << b);

	i = bvs->config.getValue<int>("BVS.logVerbosity", 0);
	s = bvs->config.getValue<std::string>("BVS.logFile", std::string("default"));
	b = bvs->config.getValue<bool>("BVS.logSystem", false);

	LOG(0, "Getting int directly: " << i);
	LOG(0, "Getting string directly: " << s);
	LOG(0, "Getting bool directly: " << b);

	std::string empty;
	bvs->config.getValue("this.option.does.not.exist", empty, std::string("empty"));
	LOG(0, "This should be 'empty': " << empty);

	std::vector<std::string> list;
	bvs->config.getValue("BVS.modules", list);
	LOG(0, "List: BVS.modules");
	int count = 0;
	for (auto& it : list)
	{
		(void) it;
		(void) count;
		LOG(0, count++ << ": " << it);
	}

	return 0;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessage.h"
#include "qmessage_p.h"
#include "qmessageid_p.h"
#include "qmessageaccountid_p.h"
#include "qmessagestore.h"

//TODO: For the set* functions rather than updating shadowed MAPI structures,
//TODO: consider using an EntryId to update a MAPI object directly.
//TODO: Note, this will require keeping the MAPI message open which may not
//TODO: be appropriate for many messages (as it may exhaust system resources
//TODO: and crash the OS).

QMessage QMessagePrivate::from(const QMessageId &id)
{
    QMessage result;
    result.d_ptr->_id = id;
    result.d_ptr->_parentAccountId = QMessageAccountIdPrivate::from(QMessageIdPrivate::storeRecordKey(id));
    return result;
}

QString QMessagePrivate::senderName(const QMessage &message)
{
    return message.d_ptr->_senderName;
}

void QMessagePrivate::setSenderName(const QMessage &message, const QString &senderName)
{
    message.d_ptr->_senderName = senderName;
}

void QMessagePrivate::setSize(const QMessage &message, uint size)
{
    message.d_ptr->_size = size;
}

QMessage::QMessage()
    :d_ptr(new QMessagePrivate(this))
{
    d_ptr->_modified = false;
    d_ptr->_size = 0;
    setDerivedMessage(this);
}

QMessage::QMessage(const QMessageId& id)
    :d_ptr(new QMessagePrivate(this))
{
    *this = QMessageStore::instance()->message(id);
    setDerivedMessage(this);
}

QMessage::QMessage(const QMessage &other)
    :QMessageContentContainer(),
     d_ptr(new QMessagePrivate(this))
{
    this->operator=(other);
    setDerivedMessage(this);
}

const QMessage& QMessage::operator=(const QMessage& other)
{
    if (&other != this) {
        QMessageContentContainer::operator=(other);
        *d_ptr = *other.d_ptr;
        setDerivedMessage(this);
    }

    return *this;
}

QMessage::~QMessage()
{
    delete d_ptr;
    d_ptr = 0;
}

QMessage QMessage::fromTransmissionFormat(Type t, const QByteArray &ba)
{
    Q_UNUSED(t)
    Q_UNUSED(ba)
    return QMessage(); // stub
}

QMessage QMessage::fromTransmissionFormatFile(Type t, const QString& fileName)
{
    Q_UNUSED(t)
    Q_UNUSED(fileName)
    return QMessage(); // stub
}

QByteArray QMessage::toTransmissionFormat() const
{
    return QByteArray(); // stub
}

void QMessage::toTransmissionFormat(QDataStream& out) const
{
    Q_UNUSED(out)
}

QMessageId QMessage::id() const
{
    return d_ptr->_id;
}

QMessage::Type QMessage::type() const
{
    return d_ptr->_type;
}

void QMessage::setType(Type t)
{
    d_ptr->_modified = true;
    d_ptr->_type = t;
}

QMessageAccountId QMessage::parentAccountId() const
{
    return d_ptr->_parentAccountId;
}

void QMessage::setParentAccountId(const QMessageAccountId &accountId)
{
    d_ptr->_modified = true;
    d_ptr->_parentAccountId = accountId;
}

#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolderId QMessage::parentFolderId() const
{
    return d_ptr->_parentFolderId;
}
#endif

QMessage::StandardFolder QMessage::standardFolder() const
{
    return QMessage::InboxFolder; // stub
}

void QMessage::setStandardFolder(StandardFolder sf)
{
    Q_UNUSED(sf) // stub
}

QMessageAddress QMessage::from() const
{
    return d_ptr->_from;
}

void QMessage::setFrom(const QMessageAddress &address)
{
    d_ptr->_modified = true;
    d_ptr->_from = address;
}

QString QMessage::subject() const
{
    return d_ptr->_subject;
}

void QMessage::setSubject(const QString &s)
{
    d_ptr->_modified = true;
    d_ptr->_subject = s;
}

QDateTime QMessage::date() const
{
    return d_ptr->_date;
}

void QMessage::setDate(const QDateTime &d)
{
    d_ptr->_modified = true;
    d_ptr->_date = d;
}

QDateTime QMessage::receivedDate() const
{
    return d_ptr->_receivedDate;
}

void QMessage::setReceivedDate(const QDateTime &d)
{
    d_ptr->_modified = true;
    d_ptr->_receivedDate = d;
}

QMessageAddressList QMessage::to() const
{
    return d_ptr->_to;
}

void QMessage::setTo(const QMessageAddressList& toList)
{
    d_ptr->_modified = true;
    d_ptr->_to = toList;
}

void QMessage::setTo(const QMessageAddress& address)
{
    d_ptr->_modified = true;
    d_ptr->_to = QMessageAddressList() << address;
}

QMessageAddressList QMessage::cc() const
{
    return d_ptr->_cc;
}

void QMessage::setCc(const QMessageAddressList& ccList)
{
    d_ptr->_modified = true;
    d_ptr->_cc = ccList;
}

QMessageAddressList QMessage::bcc() const
{
    return d_ptr->_bcc;
}

void QMessage::setBcc(const QMessageAddressList& bccList)
{
    d_ptr->_modified = true;
    d_ptr->_bcc = bccList;
}

QMessage::StatusFlags QMessage::status() const
{
    return d_ptr->_status;
}

void QMessage::setStatus(QMessage::StatusFlags newStatus)
{
    d_ptr->_modified = true;
    d_ptr->_status = newStatus;
}

QMessage::Priority QMessage::priority() const
{
    return d_ptr->_priority;
}

void QMessage::setPriority(Priority newPriority)
{
    d_ptr->_modified = true;
    d_ptr->_priority = newPriority;
}

uint QMessage::size() const
{
    return d_ptr->_size;
}

QMessageContentContainerId QMessage::body() const
{
    return QMessageContentContainerId(QString::number(0));
}

void QMessage::setBody(const QString &body)
{
    setContent(body);
}

void QMessage::setBodyFromFile(const QString &fileName)
{
    setContentFileName(fileName.toAscii());
}

QMessageContentContainerIdList QMessage::attachments() const
{
    return contentIds();
}

void QMessage::appendAttachments(const QStringList &fileNames)
{
    d_ptr->_modified = true;

    foreach (const QString &filename, fileNames) {
        QMessageContentContainer content;
        content.setContentFileName(filename.toAscii());
        appendContent(content);
    }
}

void QMessage::clearAttachments()
{
    d_ptr->_modified = true;

    foreach (const QMessageContentContainerId &id, contentIds()) {
        removeContent(id);
    }
}

#ifdef QMESSAGING_OPTIONAL
void QMessage::setOriginatorPort(uint port)
{
    d_ptr->_modified = true;
    d_ptr->_originatorPort = port;
}

uint QMessage::originatorPort()
{
    return d_ptr->_originatorPort;
}

void QMessage::setDestinationPort(uint port)
{
    d_ptr->_modified = true;
    d_ptr->_destinationPort = port;
}

uint QMessage::destinationPort()
{
    return d_ptr->_destinationPort;
}

QString QMessage::customField(const QString &name) const
{
    return d_ptr->_customFields[name];
}

void QMessage::setCustomField(const QString &name, const QString &value)
{
    d_ptr->_modified = true;
    d_ptr->_customFields[name] = value;
}

QList<QString> QMessage::customFields() const
{
    return d_ptr->_customFields.keys();
}
#endif

bool QMessage::dataModified() const
{
    return d_ptr->_modified;
}

QMessage QMessage::replyTo() const
{
    return QMessage(); // stub
}

QMessage QMessage::replyToAll() const
{
    return QMessage(); // stub
}

QMessage QMessage::forward() const
{
    return QMessage(); // stub
}
<commit_msg>Remove bad TODO suggestion.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessage.h"
#include "qmessage_p.h"
#include "qmessageid_p.h"
#include "qmessageaccountid_p.h"
#include "qmessagestore.h"

QMessage QMessagePrivate::from(const QMessageId &id)
{
    QMessage result;
    result.d_ptr->_id = id;
    result.d_ptr->_parentAccountId = QMessageAccountIdPrivate::from(QMessageIdPrivate::storeRecordKey(id));
    return result;
}

QString QMessagePrivate::senderName(const QMessage &message)
{
    return message.d_ptr->_senderName;
}

void QMessagePrivate::setSenderName(const QMessage &message, const QString &senderName)
{
    message.d_ptr->_senderName = senderName;
}

void QMessagePrivate::setSize(const QMessage &message, uint size)
{
    message.d_ptr->_size = size;
}

QMessage::QMessage()
    :d_ptr(new QMessagePrivate(this))
{
    d_ptr->_modified = false;
    d_ptr->_size = 0;
    setDerivedMessage(this);
}

QMessage::QMessage(const QMessageId& id)
    :d_ptr(new QMessagePrivate(this))
{
    *this = QMessageStore::instance()->message(id);
    setDerivedMessage(this);
}

QMessage::QMessage(const QMessage &other)
    :QMessageContentContainer(),
     d_ptr(new QMessagePrivate(this))
{
    this->operator=(other);
    setDerivedMessage(this);
}

const QMessage& QMessage::operator=(const QMessage& other)
{
    if (&other != this) {
        QMessageContentContainer::operator=(other);
        *d_ptr = *other.d_ptr;
        setDerivedMessage(this);
    }

    return *this;
}

QMessage::~QMessage()
{
    delete d_ptr;
    d_ptr = 0;
}

QMessage QMessage::fromTransmissionFormat(Type t, const QByteArray &ba)
{
    Q_UNUSED(t)
    Q_UNUSED(ba)
    return QMessage(); // stub
}

QMessage QMessage::fromTransmissionFormatFile(Type t, const QString& fileName)
{
    Q_UNUSED(t)
    Q_UNUSED(fileName)
    return QMessage(); // stub
}

QByteArray QMessage::toTransmissionFormat() const
{
    return QByteArray(); // stub
}

void QMessage::toTransmissionFormat(QDataStream& out) const
{
    Q_UNUSED(out)
}

QMessageId QMessage::id() const
{
    return d_ptr->_id;
}

QMessage::Type QMessage::type() const
{
    return d_ptr->_type;
}

void QMessage::setType(Type t)
{
    d_ptr->_modified = true;
    d_ptr->_type = t;
}

QMessageAccountId QMessage::parentAccountId() const
{
    return d_ptr->_parentAccountId;
}

void QMessage::setParentAccountId(const QMessageAccountId &accountId)
{
    d_ptr->_modified = true;
    d_ptr->_parentAccountId = accountId;
}

#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolderId QMessage::parentFolderId() const
{
    return d_ptr->_parentFolderId;
}
#endif

QMessage::StandardFolder QMessage::standardFolder() const
{
    return QMessage::InboxFolder; // stub
}

void QMessage::setStandardFolder(StandardFolder sf)
{
    Q_UNUSED(sf) // stub
}

QMessageAddress QMessage::from() const
{
    return d_ptr->_from;
}

void QMessage::setFrom(const QMessageAddress &address)
{
    d_ptr->_modified = true;
    d_ptr->_from = address;
}

QString QMessage::subject() const
{
    return d_ptr->_subject;
}

void QMessage::setSubject(const QString &s)
{
    d_ptr->_modified = true;
    d_ptr->_subject = s;
}

QDateTime QMessage::date() const
{
    return d_ptr->_date;
}

void QMessage::setDate(const QDateTime &d)
{
    d_ptr->_modified = true;
    d_ptr->_date = d;
}

QDateTime QMessage::receivedDate() const
{
    return d_ptr->_receivedDate;
}

void QMessage::setReceivedDate(const QDateTime &d)
{
    d_ptr->_modified = true;
    d_ptr->_receivedDate = d;
}

QMessageAddressList QMessage::to() const
{
    return d_ptr->_to;
}

void QMessage::setTo(const QMessageAddressList& toList)
{
    d_ptr->_modified = true;
    d_ptr->_to = toList;
}

void QMessage::setTo(const QMessageAddress& address)
{
    d_ptr->_modified = true;
    d_ptr->_to = QMessageAddressList() << address;
}

QMessageAddressList QMessage::cc() const
{
    return d_ptr->_cc;
}

void QMessage::setCc(const QMessageAddressList& ccList)
{
    d_ptr->_modified = true;
    d_ptr->_cc = ccList;
}

QMessageAddressList QMessage::bcc() const
{
    return d_ptr->_bcc;
}

void QMessage::setBcc(const QMessageAddressList& bccList)
{
    d_ptr->_modified = true;
    d_ptr->_bcc = bccList;
}

QMessage::StatusFlags QMessage::status() const
{
    return d_ptr->_status;
}

void QMessage::setStatus(QMessage::StatusFlags newStatus)
{
    d_ptr->_modified = true;
    d_ptr->_status = newStatus;
}

QMessage::Priority QMessage::priority() const
{
    return d_ptr->_priority;
}

void QMessage::setPriority(Priority newPriority)
{
    d_ptr->_modified = true;
    d_ptr->_priority = newPriority;
}

uint QMessage::size() const
{
    return d_ptr->_size;
}

QMessageContentContainerId QMessage::body() const
{
    return QMessageContentContainerId(QString::number(0));
}

void QMessage::setBody(const QString &body)
{
    setContent(body);
}

void QMessage::setBodyFromFile(const QString &fileName)
{
    setContentFileName(fileName.toAscii());
}

QMessageContentContainerIdList QMessage::attachments() const
{
    return contentIds();
}

void QMessage::appendAttachments(const QStringList &fileNames)
{
    d_ptr->_modified = true;

    foreach (const QString &filename, fileNames) {
        QMessageContentContainer content;
        content.setContentFileName(filename.toAscii());
        appendContent(content);
    }
}

void QMessage::clearAttachments()
{
    d_ptr->_modified = true;

    foreach (const QMessageContentContainerId &id, contentIds()) {
        removeContent(id);
    }
}

#ifdef QMESSAGING_OPTIONAL
void QMessage::setOriginatorPort(uint port)
{
    d_ptr->_modified = true;
    d_ptr->_originatorPort = port;
}

uint QMessage::originatorPort()
{
    return d_ptr->_originatorPort;
}

void QMessage::setDestinationPort(uint port)
{
    d_ptr->_modified = true;
    d_ptr->_destinationPort = port;
}

uint QMessage::destinationPort()
{
    return d_ptr->_destinationPort;
}

QString QMessage::customField(const QString &name) const
{
    return d_ptr->_customFields[name];
}

void QMessage::setCustomField(const QString &name, const QString &value)
{
    d_ptr->_modified = true;
    d_ptr->_customFields[name] = value;
}

QList<QString> QMessage::customFields() const
{
    return d_ptr->_customFields.keys();
}
#endif

bool QMessage::dataModified() const
{
    return d_ptr->_modified;
}

QMessage QMessage::replyTo() const
{
    return QMessage(); // stub
}

QMessage QMessage::replyToAll() const
{
    return QMessage(); // stub
}

QMessage QMessage::forward() const
{
    return QMessage(); // stub
}
<|endoftext|>