<commit_before>/*

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

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

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

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

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#include <stdlib.h> // for _TRUNCATE (windows)
#include <stdarg.h>

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

#if defined(__GNUC__) && __GNUC__ >= 4

#define TORRENT_DEPRECATED __attribute__ ((deprecated))

# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
#  define TORRENT_EXPORT
# endif

#elif defined(__GNUC__)

# define TORRENT_EXPORT

#elif defined(BOOST_MSVC)

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# else
#  define TORRENT_EXPORT
# endif

#else
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif

#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1

// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
	&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif

// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1

#ifdef TORRENT_WINDOWS
#include <stdarg.h>
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif

#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif

// determine what timer implementation we can use

#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif // TORRENT_CONFIG_HPP_INCLUDED

<commit_msg>enable floating point API by default<commit_after>/*

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

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

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

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

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#include <stdlib.h> // for _TRUNCATE (windows)
#include <stdarg.h>

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

#if defined(__GNUC__) && __GNUC__ >= 4

#define TORRENT_DEPRECATED __attribute__ ((deprecated))

# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
#  define TORRENT_EXPORT
# endif

#elif defined(__GNUC__)

# define TORRENT_EXPORT

#elif defined(BOOST_MSVC)

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# else
#  define TORRENT_EXPORT
# endif

#else
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif

#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1

// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
	&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif

// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 0

#ifdef TORRENT_WINDOWS
#include <stdarg.h>
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif

#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif

// determine what timer implementation we can use

#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif // TORRENT_CONFIG_HPP_INCLUDED

<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	pqxx/notification.hxx
 *
 *   DESCRIPTION
 *      definition of the pqxx::notification_receiver functor interface.
 *   pqxx::notification_receiver handles incoming notifications.
 *   DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/notification instead.
 *
 * Copyright (c) 2011, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#ifndef PQXX_H_NOTIFICATION
#define PQXX_H_NOTIFICATION

#include "pqxx/compiler-public.hxx"
#include "pqxx/compiler-internal-pre.hxx"

namespace pqxx
{
class connection_base;

/// "Observer" base class for notifications.
/** @addtogroup notification Notifications and Receivers
 *
 * To listen on a notification issued using the NOTIFY command, derive your own
 * class from notification_receiver and define its function-call operator to
 * perform whatever action you wish to take when the given notification arrives.
 * Then create an object of that class and pass it to your connection.  DO NOT
 * use raw SQL to listen for notifications, or your attempts to listen won't be
 * resumed when a connection fails--and you'll have no way to notice.
 *
 * Notifications never arrive inside a transaction, not even in a
 * nontransaction.  Therefore, you are free to open a transaction of your own
 * inside your receiver's function invocation operator.
 *
 * Notifications you are listening for may arrive anywhere within libpqxx code,
 * but be aware that @b PostgreSQL @b defers @b notifications @b occurring
 * @b inside @b transactions.  (This was done for excellent reasons; just think
 * about what happens if the transaction where you happen to handle an incoming
 * notification is later rolled back for other reasons).  So if you're keeping a
 * transaction open, don't expect any of your receivers on the same connection
 * to be notified.
 *
 * Multiple receivers on the same connection may listen on a notification of the
 * same name.  An incoming notification is processed by invoking all receivers
 * (zero or more) of the same name.
 */
class PQXX_LIBEXPORT PQXX_NOVTABLE notification_receiver :
  public PGSTD::binary_function<const PGSTD::string &, int, void>
{
public:
  /// Register the receiver with a connection.
  /**
   * @param c Connnection to operate on.
   * @param channel Name of the notification to listen for.
   */
  notification_receiver(connection_base &c, const PGSTD::string &channel);
  virtual ~notification_receiver();

  /// The channel that this receiver listens on.
  const PGSTD::string &channel() const { return m_channel; }

  /// Overridable: action to invoke when notification arrives.
  /**
   * @param payload On PostgreSQL 9.0 or later, an optional string that may have
   * been passed to the NOTIFY command.
   * @param backend_pid Process ID of the database backend process that served
   * our connection when the notification arrived.  The actual process ID behind
   * the connection may have changed by the time this method is called.
   */
  virtual void operator()(const PGSTD::string &payload, int backend_pid) =0;

protected:
  connection_base &conn() const throw () { return m_conn; }

private:
  // Not allowed.
  notification_receiver(const notification_receiver &);
  // Not allowed.
  notification_receiver &operator=(const notification_receiver &);

  connection_base &m_conn;
  PGSTD::string m_channel;
};
}

#include "pqxx/compiler-internal-pre.hxx"
#include "pqxx/compiler-internal-post.hxx"
#endif
<commit_msg>Documentation note.<commit_after>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	pqxx/notification.hxx
 *
 *   DESCRIPTION
 *      definition of the pqxx::notification_receiver functor interface.
 *   pqxx::notification_receiver handles incoming notifications.
 *   DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/notification instead.
 *
 * Copyright (c) 2011, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#ifndef PQXX_H_NOTIFICATION
#define PQXX_H_NOTIFICATION

#include "pqxx/compiler-public.hxx"
#include "pqxx/compiler-internal-pre.hxx"

namespace pqxx
{
class connection_base;

/// "Observer" base class for notifications.
/** @addtogroup notification Notifications and Receivers
 *
 * To listen on a notification issued using the NOTIFY command, derive your own
 * class from notification_receiver and define its function-call operator to
 * perform whatever action you wish to take when the given notification arrives.
 * Then create an object of that class and pass it to your connection.  DO NOT
 * use raw SQL to listen for notifications, or your attempts to listen won't be
 * resumed when a connection fails--and you'll have no way to notice.
 *
 * Notifications never arrive inside a transaction, not even in a
 * nontransaction.  Therefore, you are free to open a transaction of your own
 * inside your receiver's function invocation operator.
 *
 * Notifications you are listening for may arrive anywhere within libpqxx code,
 * but be aware that @b PostgreSQL @b defers @b notifications @b occurring
 * @b inside @b transactions.  (This was done for excellent reasons; just think
 * about what happens if the transaction where you happen to handle an incoming
 * notification is later rolled back for other reasons).  So if you're keeping a
 * transaction open, don't expect any of your receivers on the same connection
 * to be notified.
 *
 * (For very similar reasons, outgoing notifications are also not sent until the
 * transaction that sends them commits.)
 *
 * Multiple receivers on the same connection may listen on a notification of the
 * same name.  An incoming notification is processed by invoking all receivers
 * (zero or more) of the same name.
 */
class PQXX_LIBEXPORT PQXX_NOVTABLE notification_receiver :
  public PGSTD::binary_function<const PGSTD::string &, int, void>
{
public:
  /// Register the receiver with a connection.
  /**
   * @param c Connnection to operate on.
   * @param channel Name of the notification to listen for.
   */
  notification_receiver(connection_base &c, const PGSTD::string &channel);
  virtual ~notification_receiver();

  /// The channel that this receiver listens on.
  const PGSTD::string &channel() const { return m_channel; }

  /// Overridable: action to invoke when notification arrives.
  /**
   * @param payload On PostgreSQL 9.0 or later, an optional string that may have
   * been passed to the NOTIFY command.
   * @param backend_pid Process ID of the database backend process that served
   * our connection when the notification arrived.  The actual process ID behind
   * the connection may have changed by the time this method is called.
   */
  virtual void operator()(const PGSTD::string &payload, int backend_pid) =0;

protected:
  connection_base &conn() const throw () { return m_conn; }

private:
  // Not allowed.
  notification_receiver(const notification_receiver &);
  // Not allowed.
  notification_receiver &operator=(const notification_receiver &);

  connection_base &m_conn;
  PGSTD::string m_channel;
};
}

#include "pqxx/compiler-internal-pre.hxx"
#include "pqxx/compiler-internal-post.hxx"
#endif
<|endoftext|>


<commit_before>#ifndef USER_THREAD_USER_THREAD_DEBUG_HPP_H
#define USER_THREAD_USER_THREAD_DEBUG_HPP_H

#include <cstdio>
#include <iostream>
#include <utility>
#include <thread>

#include "config.h"

namespace orks {
namespace userthread {

namespace detail {
namespace debug {

class Out {
public:
    template <typename Rhs>
    auto& operator<<(Rhs&& rhs) {

#ifdef ORKS_USERTHREAD_DEBUG_OUTBUT
        std::cerr << "thread at " << std::this_thread::get_id() << ": " << std::forward<Rhs>(rhs);
#endif

        return std::cerr;
    }
};

namespace {
Out out;
}

template <typename ... Args>
int printf(const char* fmt, Args&& ...args) {
#ifdef ORKS_USERTHREAD_DEBUG_OUTBUT
    out << "";
    return std::fprintf(stderr, fmt, std::forward<Args>(args)...);
#endif
}

// suppress gcc warning: -Wformat-security
inline
int printf(const char* str) {
    return printf("%s", str);
}
}

}
}
}
#endif //USER_THREAD_USER_THREAD_DEBUG_HPP_H
<commit_msg>Add comment<commit_after>#ifndef USER_THREAD_USER_THREAD_DEBUG_HPP_H
#define USER_THREAD_USER_THREAD_DEBUG_HPP_H

#include <cstdio>
#include <iostream>
#include <utility>
#include <thread>

#include "config.h"

namespace orks {
namespace userthread {

namespace detail {
namespace debug {

class Out {
public:

    /*
     * if ORKS_USERTHREAD_DEBUG_OUTBUT is define, output rhs to std::cerr
     * else, do nothing
     */
    template <typename Rhs>
    auto& operator<<(Rhs&& rhs) {

#ifdef ORKS_USERTHREAD_DEBUG_OUTBUT
        std::cerr << "thread at " << std::this_thread::get_id() << ": " << std::forward<Rhs>(rhs);
#endif

        return std::cerr;
    }
};

namespace {
Out out;
}

template <typename ... Args>
int printf(const char* fmt, Args&& ...args) {
#ifdef ORKS_USERTHREAD_DEBUG_OUTBUT
    out << "";
    return std::fprintf(stderr, fmt, std::forward<Args>(args)...);
#endif
}

// suppress gcc warning: -Wformat-security
inline
int printf(const char* str) {
    return printf("%s", str);
}
}

}
}
}
#endif //USER_THREAD_USER_THREAD_DEBUG_HPP_H
<|endoftext|>


<commit_before>#include "noisy/Billow.h"
#include <cmath>

namespace noisy
{
Billow::Billow(int seed)
: simplex(seed)
{
    m_seed = seed;
    m_octaves = 1;
    m_scale = 1.0;
    m_persistence = 0.5;
    m_gain = 2.0;
}
Billow::Billow(int seed, int oct, float scale, float pers, float gain)
: simplex(seed)
{
    m_seed = seed;
    m_octaves = oct;
    m_scale = scale;
    m_persistence = pers;
    m_gain = gain;
}

void Billow::setSeed(int s)
{
    m_seed = s;
    simplex.setSeed(m_seed);
}
void Billow::setOctaves(int o)
{
    m_octaves = o;
}
void Billow::setScale(float s)
{
    m_scale = s;
}
void Billow::setPersitence(float p)
{
    m_persistence = p;
}
void Billow::setGain(float g)
{
    m_gain = g;
}

float Billow::getValue(float x, float y)
{
    x *= m_scale;
    y *= m_scale;

    float n = 0.0;
    float signal = 0.0;
    float f = 1.0;
    float amp = 1.0;

    for(int i = 0; i < m_octaves; i++)
    {
        signal = simplex.getValue(x*f, y*f);
        signal = 2.0 * fabs(signal) - 1.0;
        n += signal * amp;
        f *= m_gain;
        amp *= m_persistence;
    }
    return n + 0.5f;
}
float Billow::getValue(float x, float y, float z)
{
    x *= m_scale;
    y *= m_scale;
    z *= m_scale;

    float n = 0.0;
    float signal = 0.0;
    float f = 1.0;
    float amp = 1.0;

    for(int i = 0; i < m_octaves; i++)
    {
        signal = simplex.getValue(x*f, y*f, z*f);
        signal = 2.0 * fabs(signal) - 1.0;
        n += signal * amp;
        f *= m_gain;
        amp *= m_persistence;
    }
    return n + 0.5f;
}

} // namespace noisy<commit_msg>Fixed Billow bounds<commit_after>#include "noisy/Billow.h"
#include <cmath>

namespace noisy
{
Billow::Billow(int seed)
: simplex(seed)
{
    m_seed = seed;
    m_octaves = 1;
    m_scale = 1.0;
    m_persistence = 0.5;
    m_gain = 2.0;
}
Billow::Billow(int seed, int oct, float scale, float pers, float gain)
: simplex(seed)
{
    m_seed = seed;
    m_octaves = oct;
    m_scale = scale;
    m_persistence = pers;
    m_gain = gain;
}

void Billow::setSeed(int s)
{
    m_seed = s;
    simplex.setSeed(m_seed);
}
void Billow::setOctaves(int o)
{
    m_octaves = o;
}
void Billow::setScale(float s)
{
    m_scale = s;
}
void Billow::setPersitence(float p)
{
    m_persistence = p;
}
void Billow::setGain(float g)
{
    m_gain = g;
}

float Billow::getValue(float x, float y)
{
    x *= m_scale;
    y *= m_scale;

    float n = 0.0;
    float signal = 0.0;
    float f = 1.0;
    float amp = 1.0;

    for(int i = 0; i < m_octaves; i++)
    {
        signal = simplex.getValue(x*f, y*f);
        signal = 2.0 * fabs(signal) - 1.0;
        n += signal * amp;
        f *= m_gain;
        amp *= m_persistence;
    }
    return n;
}
float Billow::getValue(float x, float y, float z)
{
    x *= m_scale;
    y *= m_scale;
    z *= m_scale;

    float n = 0.0;
    float signal = 0.0;
    float f = 1.0;
    float amp = 1.0;

    for(int i = 0; i < m_octaves; i++)
    {
        signal = simplex.getValue(x*f, y*f, z*f);
        signal = 2.0 * fabs(signal) - 1.0;
        n += signal * amp;
        f *= m_gain;
        amp *= m_persistence;
    }
    return n;
}

} // namespace noisy<|endoftext|>


<commit_before>#include <cassert>
#include <iostream>
#include "ClassFile.h"

string getString(ClassFile const& class_, int index)
{
  auto& constant = class_.const_pool[index];
  assert(constant.tag == CONSTANT::Utf8);
  return constant.utf8;
}

string getClass(ClassFile const& class_, int index)
{
  auto& constant = class_.const_pool[index];
  assert(constant.tag == CONSTANT::Class);
  return getString(class_, constant.name_index);
}

const char* TagToString(CONSTANT tag)
{
  switch(tag)
  {
  case CONSTANT::Utf8:  return "Utf8";
  case CONSTANT::Integer:  return "Integer";
  case CONSTANT::Float:  return "Float";
  case CONSTANT::Long:  return "Long";
  case CONSTANT::Double:  return "Double";
  case CONSTANT::Class:  return "Class";
  case CONSTANT::String:  return "String";
  case CONSTANT::Fieldref:  return "Fieldref";
  case CONSTANT::Methodref:  return "Methodref";
  case CONSTANT::InterfaceMethodref:  return "InterfaceMethodref";
  case CONSTANT::NameAndType:  return "NameAndType";
  case CONSTANT::MethodHandle:  return "MethodHandle";
  case CONSTANT::MethodType:  return "MethodType";
  case CONSTANT::InvokeDynamic:  return "InvokeDynamic";
  default: return "?";
  }
}

void dumpClass(ClassFile const& class_)
{
  int i = 0;
  cout << "Constants:" << endl;

  for(auto& constant : class_.const_pool)
  {
    cout << " * " << i;
    cout << " [" << TagToString(constant.tag) << "] ";
    switch(constant.tag)
    {
    case CONSTANT::Utf8:
      cout << constant.utf8;
      break;
    case CONSTANT::Class:
      cout << "name_index=" << constant.name_index << " ";
      break;
    case CONSTANT::NameAndType:
      cout << "name_index=" << constant.name_index << " ";
      cout << "descriptor_index=" << constant.descriptor_index << " ";
      break;
    case CONSTANT::Fieldref:
    case CONSTANT::Methodref:
    case CONSTANT::InterfaceMethodref:
      cout << "class=" << constant.class_index << " ";
      cout << "name_and_type=" << constant.name_and_type_index << " ";
      break;
    default:
      cout << "...";
      break;
    }

    cout << endl;

    ++i;
  }

  cout << "Class: " << getClass(class_, class_.this_class);
  if(class_.super_class > 0)
    cout << " (extends " << getClass(class_, class_.super_class) << ")";
  cout << endl;

  for(auto& method : class_.methods)
  {
    cout << " * method: " << getString(class_, method.name_index) << " (" << method.name_index << ")";
    cout << " <" << getString(class_, method.descriptor_index) << "> (" << method.descriptor_index << ")";
    cout << endl;
  }

  for(auto& field : class_.fields)
  {
    cout << " * field: ";
    cout << getString(class_, field.name_index) << " (" << field.name_index << ") ";
    cout << " <" << getString(class_, field.descriptor_index) << "> (" << field.descriptor_index << ")";
    cout << endl;
  }

  cout << endl;
}

<commit_msg>Dumper: print implemented interfaces<commit_after>#include <cassert>
#include <iostream>
#include "ClassFile.h"

string getString(ClassFile const& class_, int index)
{
  auto& constant = class_.const_pool[index];
  assert(constant.tag == CONSTANT::Utf8);
  return constant.utf8;
}

string getClass(ClassFile const& class_, int index)
{
  auto& constant = class_.const_pool[index];
  assert(constant.tag == CONSTANT::Class);
  return getString(class_, constant.name_index);
}

const char* TagToString(CONSTANT tag)
{
  switch(tag)
  {
  case CONSTANT::Utf8:  return "Utf8";
  case CONSTANT::Integer:  return "Integer";
  case CONSTANT::Float:  return "Float";
  case CONSTANT::Long:  return "Long";
  case CONSTANT::Double:  return "Double";
  case CONSTANT::Class:  return "Class";
  case CONSTANT::String:  return "String";
  case CONSTANT::Fieldref:  return "Fieldref";
  case CONSTANT::Methodref:  return "Methodref";
  case CONSTANT::InterfaceMethodref:  return "InterfaceMethodref";
  case CONSTANT::NameAndType:  return "NameAndType";
  case CONSTANT::MethodHandle:  return "MethodHandle";
  case CONSTANT::MethodType:  return "MethodType";
  case CONSTANT::InvokeDynamic:  return "InvokeDynamic";
  default: return "?";
  }
}

void dumpClass(ClassFile const& class_)
{
  int i = 0;
  cout << "Constants:" << endl;

  for(auto& constant : class_.const_pool)
  {
    cout << " * " << i;
    cout << " [" << TagToString(constant.tag) << "] ";
    switch(constant.tag)
    {
    case CONSTANT::Utf8:
      cout << constant.utf8;
      break;
    case CONSTANT::Class:
      cout << "name_index=" << constant.name_index << " ";
      break;
    case CONSTANT::NameAndType:
      cout << "name_index=" << constant.name_index << " ";
      cout << "descriptor_index=" << constant.descriptor_index << " ";
      break;
    case CONSTANT::Fieldref:
    case CONSTANT::Methodref:
    case CONSTANT::InterfaceMethodref:
      cout << "class=" << constant.class_index << " ";
      cout << "name_and_type=" << constant.name_and_type_index << " ";
      break;
    default:
      cout << "...";
      break;
    }

    cout << endl;

    ++i;
  }

  cout << "Class: " << getClass(class_, class_.this_class);

  if(class_.super_class > 0)
    cout << " (extends " << getClass(class_, class_.super_class) << ")";

  cout << endl;

  for(auto& intf : class_.interfaces)
    cout << " * implements: " << getClass(class_, intf) << endl;

  for(auto& method : class_.methods)
  {
    cout << " * method: " << getString(class_, method.name_index) << " (" << method.name_index << ")";
    cout << " <" << getString(class_, method.descriptor_index) << "> (" << method.descriptor_index << ")";
    cout << endl;
  }

  for(auto& field : class_.fields)
  {
    cout << " * field: ";
    cout << getString(class_, field.name_index) << " (" << field.name_index << ") ";
    cout << " <" << getString(class_, field.descriptor_index) << "> (" << field.descriptor_index << ")";
    cout << endl;
  }

  cout << endl;
}

<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2013-2014 Igor Zinken - http://www.igorski.nl
 *
 * 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.
 */
#include "baseaudioevent.h"
#include "../global.h"
#include <instruments/baseinstrument.h>
#include <algorithm>

#include <utilities/utils.h> // QQQ

// constructors / destructor

BaseAudioEvent::BaseAudioEvent()
{
    construct();
}

BaseAudioEvent::BaseAudioEvent( BaseInstrument* instrument )
{
    construct();
    _instrument = instrument;
}

BaseAudioEvent::~BaseAudioEvent()
{
    removeFromSequencer();
    destroyBuffer();
}

/* public methods */

BaseInstrument* BaseAudioEvent::getInstrument()
{
    return _instrument;
}

void BaseAudioEvent::setInstrument( BaseInstrument* aInstrument )
{
    // swap instrument if new one is different to existing reference
    // additionally, if event was added to the sequencer, add it to the new
    // instruments sequenced events list

    if ( aInstrument != 0 &&
        _instrument  != aInstrument )
    {
        bool wasAddedToSequencer = _addedToSequencer;

        if ( wasAddedToSequencer )
            removeFromSequencer();

        _instrument = aInstrument;

        if ( wasAddedToSequencer )
            addToSequencer();
    }
}

void BaseAudioEvent::addToSequencer()
{
    if ( _addedToSequencer )
        return;

    // adds the event to the sequencer so it can be heard

    if ( isSequenced )
        _instrument->getEvents()->push_back( this );
    else
        _instrument->getLiveEvents()->push_back( this );

    _addedToSequencer = true;
}

void BaseAudioEvent::removeFromSequencer()
{
    if ( !_addedToSequencer )
        return;

    if ( !isSequenced )
    {
        std::vector<BaseAudioEvent*>* liveEvents = _instrument->getLiveEvents();
        std::vector<BaseAudioEvent*>::iterator position = std::find( liveEvents->begin(),
                                                                     liveEvents->end(), this );
        if ( position != liveEvents->end() )
            liveEvents->erase( position );
    }
    else
    {
        std::vector<BaseAudioEvent*>* events = _instrument->getEvents();
        std::vector<BaseAudioEvent*>::iterator position = std::find( events->begin(),
                                                                     events->end(), this );
        if ( position != events->end() )
            events->erase( position );
    }
    _addedToSequencer = false;
}

int BaseAudioEvent::getSampleLength()
{
    return _sampleLength;
}

void BaseAudioEvent::setSampleLength( int value )
{
    _sampleLength = value;

    // for non loopeable-events the existing sample end must not
    // be smaller than or equal to the sample start nor
    // exceed the range set by the sample start and sample length

    if ( !_loopeable )
    {
        if ( _sampleEnd <= _sampleStart ||
             _sampleEnd >= ( _sampleStart + _sampleLength )) {
            _sampleEnd = _sampleStart + ( _sampleLength - 1 );
        }
    }
}

int BaseAudioEvent::getSampleStart()
{
    return _sampleStart;
}

void BaseAudioEvent::setSampleStart( int value )
{
    _sampleStart = value;
}

int BaseAudioEvent::getSampleEnd()
{
    return _sampleEnd;
}

void BaseAudioEvent::setSampleEnd( int value )
{
    // for non loopeable-events the sample end cannot exceed
    // beyond the start and the total sample length (it can
    // be smaller though for a cut-off playback)

    if ( !_loopeable && value >= ( _sampleStart + _sampleLength ))
        _sampleEnd = _sampleStart + ( _sampleLength - 1 );
    else
        _sampleEnd = value;
}

bool BaseAudioEvent::isLoopeable()
{
    return _loopeable;
}

void BaseAudioEvent::setLoopeable( bool value )
{
    _loopeable = value;

    if ( _buffer != 0 )
        _buffer->loopeable = _loopeable;
}

bool BaseAudioEvent::isDeletable()
{
    return _deleteMe;
}

void BaseAudioEvent::setDeletable( bool value )
{
    _deleteMe = value;
}

bool BaseAudioEvent::isEnabled()
{
    return _enabled;
}

void BaseAudioEvent::setEnabled( bool value )
{
    _enabled = value;
}

void BaseAudioEvent::lock()
{
    _locked = true;
}

void BaseAudioEvent::unlock()
{
    _locked = false;

    if ( _updateAfterUnlock )
    {
        // override in subclass for custom update-logic
    }
    _updateAfterUnlock = false;
}

bool BaseAudioEvent::isLocked()
{
    return _locked;
}

float BaseAudioEvent::getVolume()
{
    return _volume;
}

void BaseAudioEvent::setVolume( float value )
{
    _volume = value;
}

void BaseAudioEvent::mixBuffer( AudioBuffer* outputBuffer, int bufferPosition,
                                int minBufferPosition, int maxBufferPosition,
                                bool loopStarted, int loopOffset, bool useChannelRange )
{
    lock(); // prevents buffer mutations (from outside threads) during this read cycle

    // read from the pre-cached buffer for sequenced notes

    int bufferSize   = outputBuffer->bufferSize;

    // if the output channel amount differs from this events channel amount, we might
    // potentially have a bad time (e.g. engine has mono output while this event is stereo)
    // ideally events should never hold more channels than AudioEngineProps::OUTPUT_CHANNELS

    int outputChannels = std::min( _buffer->amountOfChannels, outputBuffer->amountOfChannels );
    int readPointer, c, ca;

     DebugTool::log("here we go for %d", bufferPosition);
    for ( int i = 0; i < bufferSize; ++i )
    {
        readPointer = i + bufferPosition;
        DebugTool::log("at iteration %d", i );
        DebugTool::log("the pointer is %d", readPointer );

        // over the max position ? read from the start ( implies that sequence has started loop )
        if ( readPointer > maxBufferPosition )
        {
        DebugTool::log("read %d above max", readPointer);
            if ( useChannelRange )  // TODO: channels use a min buffer position too ? (currently drummachine only)
                readPointer -= maxBufferPosition;

            else if ( !loopStarted )
                break;
        }

        if ( readPointer >= _sampleStart && readPointer <= _sampleEnd )
        {
            // mind the offset ! ( cached buffer starts at 0 while
            // the _sampleStart defines where the event is positioned in the sequencer )
            readPointer -= _sampleStart;
            DebugTool::log("yarrr for read %d", readPointer );

            for ( c = 0; c < outputChannels; ++c )
            {
                SAMPLE_TYPE* srcBuffer = _buffer->getBufferForChannel( c );
                SAMPLE_TYPE* tgtBuffer = outputBuffer->getBufferForChannel( c );

                tgtBuffer[ i ] += ( srcBuffer[ readPointer ] * _volume );
            }
        }
        else if ( loopStarted && i >= loopOffset )
        {
        DebugTool::log("here we go loopin for iterator %d",i);
            readPointer = minBufferPosition + ( i - loopOffset );
DebugTool::log("at read pointer %d",readPointer);
            if ( readPointer >= _sampleStart && readPointer <= _sampleEnd )
            {
                readPointer -= _sampleStart;

                for ( c = 0, ca = _buffer->amountOfChannels; c < ca; ++c )
                {
                    SAMPLE_TYPE* srcBuffer = _buffer->getBufferForChannel( c );
                    SAMPLE_TYPE* tgtBuffer = outputBuffer->getBufferForChannel( c );

                    tgtBuffer[ i ] += ( srcBuffer[ readPointer ] * _volume );
                }
            }
        }
        else {
        DebugTool::log("nope for %d", readPointer );
        }
    }
    unlock();   // release lock
}

AudioBuffer* BaseAudioEvent::getBuffer()
{
    return _buffer;
}

void BaseAudioEvent::setBuffer( AudioBuffer* buffer, bool destroyable )
{
    _destroyableBuffer = destroyable;
    destroyBuffer(); // clear existing buffer (if destroyable)
    _buffer = buffer;
}

AudioBuffer* BaseAudioEvent::synthesize( int aBufferLength )
{
    // override in subclass as this memory allocation requires cleanup
    // (and basically contains nothing but silence ;-) ... !

    return new AudioBuffer( AudioEngineProps::OUTPUT_CHANNELS, aBufferLength );
}

/* protected methods */

void BaseAudioEvent::construct()
{
    _buffer            = 0;
    _enabled           = true;
    _destroyableBuffer = true;
    _loopeable         = false;
    _locked            = false;
    _addedToSequencer  = false;
    _volume            = MAX_PHASE;
    _sampleStart       = 0;
    _sampleEnd         = 0;
    _sampleLength      = 0;
    _instrument        = 0;
    _deleteMe          = false;
    isSequenced        = true;
}

void BaseAudioEvent::destroyBuffer()
{
    if ( _destroyableBuffer && _buffer != 0 )
    {
        delete _buffer;
        _buffer = 0;
    }
}
<commit_msg>ongoing<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2013-2014 Igor Zinken - http://www.igorski.nl
 *
 * 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.
 */
#include "baseaudioevent.h"
#include "../global.h"
#include <instruments/baseinstrument.h>
#include <algorithm>

#include <utilities/utils.h> // QQQ

// constructors / destructor

BaseAudioEvent::BaseAudioEvent()
{
    construct();
}

BaseAudioEvent::BaseAudioEvent( BaseInstrument* instrument )
{
    construct();
    _instrument = instrument;
}

BaseAudioEvent::~BaseAudioEvent()
{
    removeFromSequencer();
    destroyBuffer();
}

/* public methods */

BaseInstrument* BaseAudioEvent::getInstrument()
{
    return _instrument;
}

void BaseAudioEvent::setInstrument( BaseInstrument* aInstrument )
{
    // swap instrument if new one is different to existing reference
    // additionally, if event was added to the sequencer, add it to the new
    // instruments sequenced events list

    if ( aInstrument != 0 &&
        _instrument  != aInstrument )
    {
        bool wasAddedToSequencer = _addedToSequencer;

        if ( wasAddedToSequencer )
            removeFromSequencer();

        _instrument = aInstrument;

        if ( wasAddedToSequencer )
            addToSequencer();
    }
}

void BaseAudioEvent::addToSequencer()
{
    if ( _addedToSequencer )
        return;

    // adds the event to the sequencer so it can be heard

    if ( isSequenced )
        _instrument->getEvents()->push_back( this );
    else
        _instrument->getLiveEvents()->push_back( this );

    _addedToSequencer = true;
}

void BaseAudioEvent::removeFromSequencer()
{
    if ( !_addedToSequencer )
        return;

    if ( !isSequenced )
    {
        std::vector<BaseAudioEvent*>* liveEvents = _instrument->getLiveEvents();
        std::vector<BaseAudioEvent*>::iterator position = std::find( liveEvents->begin(),
                                                                     liveEvents->end(), this );
        if ( position != liveEvents->end() )
            liveEvents->erase( position );
    }
    else
    {
        std::vector<BaseAudioEvent*>* events = _instrument->getEvents();
        std::vector<BaseAudioEvent*>::iterator position = std::find( events->begin(),
                                                                     events->end(), this );
        if ( position != events->end() )
            events->erase( position );
    }
    _addedToSequencer = false;
}

int BaseAudioEvent::getSampleLength()
{
    return _sampleLength;
}

void BaseAudioEvent::setSampleLength( int value )
{
    _sampleLength = value;

    // for non loopeable-events the existing sample end must not
    // be smaller than or equal to the sample start nor
    // exceed the range set by the sample start and sample length

    if ( !_loopeable )
    {
        if ( _sampleEnd <= _sampleStart ||
             _sampleEnd >= ( _sampleStart + _sampleLength )) {
            _sampleEnd = _sampleStart + ( _sampleLength - 1 );
        }
    }
}

int BaseAudioEvent::getSampleStart()
{
    return _sampleStart;
}

void BaseAudioEvent::setSampleStart( int value )
{
    _sampleStart = value;
}

int BaseAudioEvent::getSampleEnd()
{
    return _sampleEnd;
}

void BaseAudioEvent::setSampleEnd( int value )
{
    // for non loopeable-events the sample end cannot exceed
    // beyond the start and the total sample length (it can
    // be smaller though for a cut-off playback)

    if ( !_loopeable && value >= ( _sampleStart + _sampleLength ))
        _sampleEnd = _sampleStart + ( _sampleLength - 1 );
    else
        _sampleEnd = value;
}

bool BaseAudioEvent::isLoopeable()
{
    return _loopeable;
}

void BaseAudioEvent::setLoopeable( bool value )
{
    _loopeable = value;

    if ( _buffer != 0 )
        _buffer->loopeable = _loopeable;
}

bool BaseAudioEvent::isDeletable()
{
    return _deleteMe;
}

void BaseAudioEvent::setDeletable( bool value )
{
    _deleteMe = value;
}

bool BaseAudioEvent::isEnabled()
{
    return _enabled;
}

void BaseAudioEvent::setEnabled( bool value )
{
    _enabled = value;
}

void BaseAudioEvent::lock()
{
    _locked = true;
}

void BaseAudioEvent::unlock()
{
    _locked = false;

    if ( _updateAfterUnlock )
    {
        // override in subclass for custom update-logic
    }
    _updateAfterUnlock = false;
}

bool BaseAudioEvent::isLocked()
{
    return _locked;
}

float BaseAudioEvent::getVolume()
{
    return _volume;
}

void BaseAudioEvent::setVolume( float value )
{
    _volume = value;
}

void BaseAudioEvent::mixBuffer( AudioBuffer* outputBuffer, int bufferPosition,
                                int minBufferPosition, int maxBufferPosition,
                                bool loopStarted, int loopOffset, bool useChannelRange )
{
    lock(); // prevents buffer mutations (from outside threads) during this read cycle

    // read from the pre-cached buffer for sequenced notes

    int bufferSize = outputBuffer->bufferSize;

    // if the output channel amount differs from this events channel amount, we might
    // potentially have a bad time (e.g. engine has mono output while this event is stereo)
    // ideally events should never hold more channels than AudioEngineProps::OUTPUT_CHANNELS

    int outputChannels = std::min( _buffer->amountOfChannels, outputBuffer->amountOfChannels );
    int readPointer, c, ca;

     DebugTool::log("here we go for %d", bufferPosition);
    for ( int i = 0; i < bufferSize; ++i )
    {
        readPointer = i + bufferPosition;
        DebugTool::log("at iteration %d", i );
        DebugTool::log("the pointer is %d", readPointer );

        // over the max position ? read from the start ( implies that sequence has started loop )
        if ( readPointer > maxBufferPosition )
        {
        DebugTool::log("read %d above max", readPointer);
            if ( useChannelRange )  // TODO: channels use a min buffer position too ? (currently drummachine only)
                readPointer -= maxBufferPosition;

            else if ( !loopStarted )
                break;
        }

        if ( readPointer >= _sampleStart && readPointer <= _sampleEnd )
        {
            // mind the offset ! ( cached buffer starts at 0 while
            // the _sampleStart defines where the event is positioned in the sequencer )
            readPointer -= _sampleStart;
            DebugTool::log("yarrr for read %d", readPointer );

            for ( c = 0; c < outputChannels; ++c )
            {
                SAMPLE_TYPE* srcBuffer = _buffer->getBufferForChannel( c );
                SAMPLE_TYPE* tgtBuffer = outputBuffer->getBufferForChannel( c );

                tgtBuffer[ i ] += ( srcBuffer[ readPointer ] * _volume );
            }
        }
        else if ( loopStarted && i >= loopOffset )
        {
        DebugTool::log("here we go loopin for iterator %d",i);
            readPointer = minBufferPosition + ( i - loopOffset );
DebugTool::log("at read pointer %d",readPointer);
            if ( readPointer >= _sampleStart && readPointer <= _sampleEnd )
            {
                readPointer -= _sampleStart;

                for ( c = 0, ca = _buffer->amountOfChannels; c < ca; ++c )
                {
                    SAMPLE_TYPE* srcBuffer = _buffer->getBufferForChannel( c );
                    SAMPLE_TYPE* tgtBuffer = outputBuffer->getBufferForChannel( c );

                    tgtBuffer[ i ] += ( srcBuffer[ readPointer ] * _volume );
                }
            }
        }
        else {
        DebugTool::log("nope for %d", readPointer );
        }
    }
    unlock();   // release lock
}

AudioBuffer* BaseAudioEvent::getBuffer()
{
    return _buffer;
}

void BaseAudioEvent::setBuffer( AudioBuffer* buffer, bool destroyable )
{
    _destroyableBuffer = destroyable;
    destroyBuffer(); // clear existing buffer (if destroyable)
    _buffer = buffer;
}

AudioBuffer* BaseAudioEvent::synthesize( int aBufferLength )
{
    // override in subclass as this memory allocation requires cleanup
    // (and basically contains nothing but silence ;-) ... !

    return new AudioBuffer( AudioEngineProps::OUTPUT_CHANNELS, aBufferLength );
}

/* protected methods */

void BaseAudioEvent::construct()
{
    _buffer            = 0;
    _enabled           = true;
    _destroyableBuffer = true;
    _loopeable         = false;
    _locked            = false;
    _addedToSequencer  = false;
    _volume            = MAX_PHASE;
    _sampleStart       = 0;
    _sampleEnd         = 0;
    _sampleLength      = 0;
    _instrument        = 0;
    _deleteMe          = false;
    isSequenced        = true;
}

void BaseAudioEvent::destroyBuffer()
{
    if ( _destroyableBuffer && _buffer != 0 )
    {
        delete _buffer;
        _buffer = 0;
    }
}
<|endoftext|>


<commit_before>/*
 * File:  other_updates.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "sedna.h"

#include "updates.h"
#include "xptr_sequence.h"
#include "micro.h"
#include "auc.h"

void replace(PPOpIn arg)
{
	//1.seq-replaced nodes
	//2.replacements
	//3. persistent replacements+their position in 2 seq
	tuple t(arg.ts);
	descript_sequence arg3seq(2);
	xptr_sequence arg1seq;
	xptr_sequence arg1seq_tmp;
	xptr_sequence arg2seq;
	upd_ns_map* ins_swiz=NULL;
	bool is_node_updated=true;
	arg.op->next(t);
	while (!t.is_eos())
	{
		if (t.cells[0].is_node())
		{
			xptr node=t.cells[0].get_node();
			CHECKP(node);
			if ((!is_node_updated || is_node_persistent(node))&& !is_node_document(node))
			{
				xptr indir=((n_dsc*)XADDR(node))->indir;
				if (is_node_updated)
				{
					is_node_updated=false;
					arg1seq.add(indir);
					arg1seq_tmp.add(node);
				}
				else
				{

					if (is_node_persistent(node))
					{
						tuple tup(2);
						tup.copy(tuple_cell::node(node),tuple_cell(arg2seq.size()));
						arg3seq.add(tup);
					}
					arg2seq.add(indir);
				}
			}
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2020);
			}
#endif
		}
		else
		{
			if (t.cells[0].get_atomic_type()==se_separator)
			{
				arg2seq.add(XNULL);
				is_node_updated=true;
			}
#ifndef IGNORE_UPDATE_ERRORS
			else	throw USER_EXCEPTION(SE2021);
#endif
		}

		arg.op->next(t);
	}

	if (arg1seq.size()<=0) return;
	//merge 1'st and 3'rd sequences create copy of merged items
	// Checking authorization
	if (is_auth_check_needed(REPLACE_STATEMENT))
		auth_for_update(&arg1seq, REPLACE_STATEMENT, false);
	arg1seq_tmp.sort();
	arg3seq.sort();
	descript_sequence::iterator it3=arg3seq.begin();
	xptr_sequence::iterator it1=arg1seq_tmp.begin();
	while(it3!=arg3seq.end()&& it1!=arg1seq_tmp.end())
	{
		switch(nid_cmp_effective((*it3).cells[0].get_node(), *it1))
		{
		case 0:
			{
				xptr node=copy_to_temp((*it3).cells[0].get_node());
				arg2seq[(*it3).cells[1].get_xs_integer()]=((n_dsc*)XADDR(node))->indir;
				++it3;++it1;
			}
			break;
		case 1:
			++it1;
			break;
		case 2:
			++it1;
			break;
		case -1:
			++it3;
			break;
		case -2:
			{
				xptr node=copy_to_temp((*it3).cells[0].get_node());
				arg2seq.set(((n_dsc*)XADDR(node))->indir,(*it3).cells[1].get_xs_integer());
				++it3;
			}
			break;
		}
	}
#ifdef SE_ENABLE_FTSEARCH
	clear_ft_sequences();
#endif
	// inserting new nodes
	xptr_sequence::iterator sit=arg2seq.begin();
	xptr_sequence::iterator it=arg1seq.begin();
	do
	{
		xptr node=removeIndirection(*it);
		//1.insert
		while(*sit!=XNULL)
		{
			xptr node_child=*sit;
			if (is_node_persistent(node_child))
				node=deep_pers_copy(node, XNULL, XNULL, removeIndirection(node_child),true);
			else
				node=deep_temp_copy(node, XNULL, XNULL, removeIndirection(node_child),ins_swiz);

			sit++;
		}
		sit++;
		++it;
	}
	while (it!=arg1seq.end());
	//3.delete
	arg2seq.clear();
	it=arg1seq.begin();
	while (it!=arg1seq.end())
	{
		arg2seq.add(removeIndirection(*it));
		++it;
	}
	arg2seq.sort();
	it=arg2seq.end();
	do
	{
		--it;
		delete_node(*it);
		if (it==arg2seq.begin()) break;
	}
	while (true);
	if (ins_swiz!=NULL)
	{
//		checkSwiizleTab(ins_swiz);
		delete ins_swiz;
	}
	clear_temp();
#ifdef SE_ENABLE_FTSEARCH
	execute_modifications();
#endif

}<commit_msg>new replace<commit_after>/*
 * File:  other_updates.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "sedna.h"

#include "updates.h"
#include "xptr_sequence.h"
#include "micro.h"
#include "auc.h"

void replace(PPOpIn arg)
{
	//1.seq-replaced nodes
	//2.replacements
	//3. persistent replacements+their position in 2 seq
	tuple t(arg.ts);
	descript_sequence arg3seq(2);
	xptr_sequence arg1seq;
	xptr_sequence arg1seq_tmp;
	xptr_sequence arg2seq;
	upd_ns_map* ins_swiz=NULL;
	bool is_node_updated=true;
	arg.op->next(t);
	while (!t.is_eos())
	{
		if (t.cells[0].is_node())
		{
			xptr node=t.cells[0].get_node();
			CHECKP(node);
			if ((!is_node_updated || is_node_persistent(node))&& !is_node_document(node))
			{
				xptr indir=((n_dsc*)XADDR(node))->indir;
				if (is_node_updated)
				{
					is_node_updated=false;
					arg1seq.add(indir);
					arg1seq_tmp.add(node);
				}
				else
				{

					if (is_node_persistent(node))
					{
						tuple tup(2);
						tup.copy(tuple_cell::node(node),tuple_cell(arg2seq.size()));
						arg3seq.add(tup);
					}
					arg2seq.add(indir);
				}
			}
#ifndef IGNORE_UPDATE_ERRORS
			else
			{
				throw USER_EXCEPTION(SE2020);
			}
#endif
		}
		else
		{
			if (t.cells[0].get_atomic_type()==se_separator)
			{
				arg2seq.add(XNULL);
				is_node_updated=true;
			}
#ifndef IGNORE_UPDATE_ERRORS
			else	throw USER_EXCEPTION(SE2021);
#endif
		}

		arg.op->next(t);
	}

	if (arg1seq.size()<=0) return;
	//merge 1'st and 3'rd sequences create copy of merged items
	// Checking authorization
	if (is_auth_check_needed(REPLACE_STATEMENT))
		auth_for_update(&arg1seq, REPLACE_STATEMENT, false);
	arg1seq_tmp.sort();
	arg3seq.sort();
	descript_sequence::iterator it3=arg3seq.begin();
	xptr_sequence::iterator it1=arg1seq_tmp.begin();
	while(it3!=arg3seq.end()&& it1!=arg1seq_tmp.end())
	{
		switch(nid_cmp_effective((*it3).cells[0].get_node(), *it1))
		{
		case 0:
			{
				xptr node=copy_to_temp((*it3).cells[0].get_node());
				arg2seq[(*it3).cells[1].get_xs_integer()]=((n_dsc*)XADDR(node))->indir;
				++it3;++it1;
			}
			break;
		case 1:
			++it1;
			break;
		case 2:
			++it1;
			break;
		case -1:
			++it3;
			break;
		case -2:
			{
				xptr node=copy_to_temp((*it3).cells[0].get_node());
				arg2seq.set(((n_dsc*)XADDR(node))->indir,(*it3).cells[1].get_xs_integer());
				++it3;
			}
			break;
		}
	}
#ifdef SE_ENABLE_FTSEARCH
	clear_ft_sequences();
#endif
	//sorting arg1seq
	arg3seq.clear();
	xptr_sequence::iterator it=arg1seq.begin();
	xptr_sequence::iterator sit=arg2seq.begin();
	int ctr=0;
	do
	{
		tuple tup(2);
		tup.copy(tuple_cell::node(removeIndirection(*it)),tuple_cell(ctr));
		arg3seq.add(tup);
		while(*sit!=XNULL)
		{
			sit++;
			ctr++;
		}
		sit++;
		ctr++;
		it++;
	}
	while (it!=arg1seq.end());
	arg3seq.sort();
	it3=arg3seq.begin();
	descript_sequence arg4seq(2);
	do
	{
		xptr node=(*it3).cells[0].get_node();
		CHECKP(node);
		tuple t=(*it3);
		t.cells[0].set_node(((n_dsc*)XADDR(node))->indir);
		++it3;
		arg4seq.add(t);

	}
	while (it3!=arg3seq.end());
	// inserting new nodes
	it3=arg4seq.end();
	do
	{
		--it3;
		xptr node=removeIndirection((*it3).cells[0].get_node());

		//1.insert
		int pos=(*it3).cells[1].get_xs_integer();
		sit=arg2seq.begin()+pos;
		while(*sit!=XNULL)
		{
			xptr node_child=*sit;
			if (is_node_persistent(node_child))
				node=deep_pers_copy(node, XNULL, XNULL, removeIndirection(node_child),true);
			else
				node=deep_temp_copy(node, XNULL, XNULL, removeIndirection(node_child),ins_swiz);

			sit++;
		}
		//delete node
		delete_node(removeIndirection((*it3).cells[0].get_node()));
	}
	while (it3!=arg4seq.begin());
	//3.delete
/*	arg2seq.clear();
	it=arg1seq.begin();
	while (it!=arg1seq.end())
	{
		arg2seq.add(removeIndirection(*it));
		++it;
	}
	arg2seq.sort();
	it=arg2seq.end();
	do
	{
		--it;
		delete_node(*it);
		if (it==arg2seq.begin()) break;
	}
	while (true);
*/
	if (ins_swiz!=NULL)
	{
//		checkSwiizleTab(ins_swiz);
		delete ins_swiz;
	}
	clear_temp();
#ifdef SE_ENABLE_FTSEARCH
	execute_modifications();
#endif

}<|endoftext|>


<commit_before><commit_msg>start of surf<commit_after><|endoftext|>


<commit_before>//
//  Entity.cpp
//  labshooter
//
//  Created by Pawel Miniszewski on 07.12.2014.
//  Copyright (c) 2014 Pawel Miniszewski. All rights reserved.
//

#include "Entity.h"

Entity::Entity()
{

}

Entity::~Entity()
{
    delete sprite;
}

void Entity::Draw(sf::RenderWindow* window)
{
    if(window && sprite &&  sprite->getTexture())
    {

        window->draw(*sprite);
    }
}
void Entity::Update(float dt)
{

}

void Entity::Move(sf::Vector2f delta)
{
    //position += delta;
    sprite->move(delta);

    //if(sprite->getGlobalBounds().intersects(obstacle.getGlobalBounds()))
    //{
        //sprite->move(-delta);
    //}
}

void Entity::SetPosition(sf::Vector2f absolutePosition)
{
    if(sprite)
    {
        sprite->setPosition(absolutePosition);
    }

}
void Entity::SetTexture(sf::Texture* texture)
{
    if(!sprite)
    {
        sprite = new sf::Sprite();
    }
    if( texture)
    {
        sprite->setTexture(*texture);
    }
}

<commit_msg>- fixed null exception with unititialied pointer<commit_after>//
//  Entity.cpp
//  labshooter
//
//  Created by Pawel Miniszewski on 07.12.2014.
//  Copyright (c) 2014 Pawel Miniszewski. All rights reserved.
//

#include "Entity.h"

Entity::Entity() : sprite(nullptr)
{

}

Entity::~Entity()
{
    delete sprite;
}

void Entity::Draw(sf::RenderWindow* window)
{
    if(window && sprite &&  sprite->getTexture())
    {

        window->draw(*sprite);
    }
}
void Entity::Update(float dt)
{

}

void Entity::Move(sf::Vector2f delta)
{
    //position += delta;
    sprite->move(delta);

    //if(sprite->getGlobalBounds().intersects(obstacle.getGlobalBounds()))
    //{
        //sprite->move(-delta);
    //}
}

void Entity::SetPosition(sf::Vector2f absolutePosition)
{
    if(sprite)
    {
        sprite->setPosition(absolutePosition);
    }

}
void Entity::SetTexture(sf::Texture* texture)
{
    if(!sprite)
    {
        sprite = new sf::Sprite();
    }
    if( texture)
    {
        sprite->setTexture(*texture);
    }
}

<|endoftext|>


<commit_before>/* Kernel.cpp - stalkware(1) kernel implementation
 * stalkware - blah bleh - (C) 2013, Timo Buhrmester
 * See README for contact-, COPYING for license information.  */

#if HAVE_CONFIG_H
# include <config.h>
#endif

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>

#include <err.h>

#include "Kernel.h"

Kernel::Kernel()
: facmap_(facarr, facarr + (sizeof facarr / sizeof *facarr)),
  modmap_(),
  cfgmap_(),
  stmap_()
{
}

Kernel::~Kernel()
{
}

bool
Kernel::run()
{
	for(map<string, Module*>::const_iterator it = modmap_.begin();
			it != modmap_.end(); it++) {
		Module *mod = it->second;
		map<string, cfgent> *cfg = cfgmap_[mod];
		fprintf(stderr, "initializing module '%s'\n",
				it->first.c_str());
		mod->init(it->first, *cfg);
	}

	return true;
}

void
Kernel::init(string const& stalkrc)
{
	process_stalkrc(stalkrc);
}

void
Kernel::process_stalkrc(string const& path)
{
	char *line = NULL;
	size_t len = 0;
	ssize_t read;

	errno = 0;
	FILE *fp = fopen(path.c_str(), "r");
	if (!fp) {
		warn("couldn't fopen() '%s'", path.c_str());
		return;
	}

	while ((read = getline(&line, &len, fp)) != -1) {
		char *dup = strdup(line);
		char *ptr = strchr(dup, '#');
		if (ptr)
			*ptr = 0;

		ptr = dup + strlen(dup) - 1;
		while(ptr >= dup && isspace(*ptr))
			*ptr-- = '\0';

		ptr = dup;
		while(isspace(*ptr))
			ptr++;

		if (strlen(ptr) == 0)
			continue;

		process_cfgline(ptr);

		free(dup);
	}

	fclose(fp);
	free(line);
}

void
Kernel::process_cfgline(const char *line)
{
	char *ctx, *ctx2; //context pointers for strtok_r
	char *dup = strdup(line);

	char *tok = strtok_r(dup, "\t ", &ctx);
	if (strcmp(tok, "load") == 0) {
		tok = strtok_r(NULL, "\t ", &ctx);
		char *modclass = strdup(tok);
		tok = strtok_r(NULL, "\t ", &ctx);
		char *modname = strdup(tok);
		if (strtok_r(NULL, "\t ", &ctx))
			warnx("too many tokens (some ignored): '%s'", line);
		fprintf(stderr, "load: modclass '%s', modname '%s'\n",
				modclass, modname);

		load_mod(modname, modclass);

		free(modclass);
		free(modname);

	} else if (strcmp(tok, "stalk") == 0) {
		tok = strtok_r(NULL, "\t ", &ctx);
		char *modname = strdup(tok);
		tok = strtok_r(NULL, "\0", &ctx);
		char *remainder = strdup(tok);
		vector<char*> namevec;

		fprintf(stderr, "stalk: modname '%s', remainder '%s'\n",
				modname, remainder);

		char *start = remainder;
		char *tokstart, *tokend;
		while(nextqtok(start, &tokstart, &tokend)) {
			fprintf(stderr, "tok: '%*.*s'\n",
					(int)(tokend-tokstart),
					(int)(tokend-tokstart), tokstart);

			namevec.push_back(strndup(tok, (size_t)(tokend-tokstart)));

			start = tokend;
			if (*tokend)
				start++;
		}

		add_stalkee(modname, namevec);

		for(vector<char*>::const_iterator it = namevec.begin();
				it != namevec.end(); it++)
			free(*it);

		free(modname);
		free(remainder);

	} else {
		char *cmddup = strdup(tok);
		char *itok = strtok_r(cmddup, "_", &ctx2);
		char *mod = strdup(itok);
		itok = strtok_r(NULL, "\t ", &ctx2);
		char *sett = strdup(itok);
		itok = strtok_r(NULL, "\0", &ctx);
		while(isspace(*itok))
			itok++;

		char *val = strdup(itok);
		fprintf(stderr, "set: mod '%s', sett '%s', val '%s'\n",
				mod, sett, val);

		add_cfg(mod, sett, val);

		free(val);
		free(sett);
		free(mod);
		free(cmddup);
	}

	free(dup);
}

bool
Kernel::nextqtok(char *data, char **tokstart, char **tokend)
{
	char *start = data;

	while(isspace(*start))
		start++;

	if(!*start)
		return false;

	bool inq = false;
	bool quoted = false;
	char *end = start;
	while(*end) {
		if (*end == '"') {
			if (!(inq = !inq)) //leaving quotes
				break;
			else
				quoted = true;
		} else if (isspace(*end) && !inq)
			break;

		end++;
	}

	if (quoted)
		start++;

	*tokstart = start;
	*tokend = end;

	return true;
}

void
Kernel::add_stalkee(const char *mname, vector<char*> const& user)
{
	if (!modmap_.count(std::string(mname))) {
		warnx("unknown module: '%s'", mname);
		return;
	}

	Module *mod = modmap_[mname];
	vector<vector<string> > &stvec = stmap_[mod];

	stvec.push_back(vector<string>());

	for(vector<char*>::const_iterator it = user.begin();
			it != user.end(); it++) {
		stvec.back().push_back(string(*it));
	}
}

void
Kernel::add_cfg(const char *mname, const char *sett, const char *val)
{
	if (!modmap_.count(std::string(mname))) {
		warnx("unknown module: '%s'", mname);
		return;
	}

	Module *mod = modmap_[mname];
	map<string, cfgent> *cfg = cfgmap_[mod];

	if ((*val >= '0' && *val <= '9') || *val == '-' || *val == '.') {
		if (strchr(val, '.')||strchr(val, 'e')||strchr(val, 'E')) {
			//treat as double
			(*cfg)[sett].typ = cfgent::DBL;
			(*cfg)[sett].val.dbl_ = strtod(val, NULL);
		} else {
			//treat as long
			(*cfg)[sett].typ = cfgent::LNG;
			(*cfg)[sett].val.lng_ = strtol(val, NULL, 10);
		}
	} else {
		//treat as string
		(*cfg)[sett].typ = cfgent::STR;
		if (*val == '"') {
			bool endq = *(val+strlen(val)-1) == '"';
			(*cfg)[sett].val.str_ = strndup(val + 1,
					strlen(val) - endq?2:1);
		} else
			(*cfg)[sett].val.str_ = strdup(val);
	}
}

void
Kernel::load_mod(const char *mname, const char *mclass)
{
	if (!facmap_.count(std::string(mclass))) {
		warnx("no such class: '%s' (not registered in Kernel.h?)",
				mclass);
		return;
	}

	if (modmap_.count(std::string(mname))) {
		warnx("name already in use: '%s'", mname);
		return;
	}

	Module *mod = facmap_[mclass]();
	if (!mod) {
		warnx("failed to instantiate '%s'", mclass);
		return;
	}

	modmap_[mname] = mod;
	cfgmap_[mod] = new map<string, cfgent>;
	stmap_[mod] = vector<vector<string> >();
}

<commit_msg>fix creating namevec<commit_after>/* Kernel.cpp - stalkware(1) kernel implementation
 * stalkware - blah bleh - (C) 2013, Timo Buhrmester
 * See README for contact-, COPYING for license information.  */

#if HAVE_CONFIG_H
# include <config.h>
#endif

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>

#include <err.h>

#include "Kernel.h"

Kernel::Kernel()
: facmap_(facarr, facarr + (sizeof facarr / sizeof *facarr)),
  modmap_(),
  cfgmap_(),
  stmap_()
{
}

Kernel::~Kernel()
{
}

bool
Kernel::run()
{
	for(map<string, Module*>::const_iterator it = modmap_.begin();
			it != modmap_.end(); it++) {
		Module *mod = it->second;
		map<string, cfgent> *cfg = cfgmap_[mod];
		fprintf(stderr, "initializing module '%s'\n",
				it->first.c_str());
		mod->init(it->first, *cfg);
	}

	return true;
}

void
Kernel::init(string const& stalkrc)
{
	process_stalkrc(stalkrc);
}

void
Kernel::process_stalkrc(string const& path)
{
	char *line = NULL;
	size_t len = 0;
	ssize_t read;

	errno = 0;
	FILE *fp = fopen(path.c_str(), "r");
	if (!fp) {
		warn("couldn't fopen() '%s'", path.c_str());
		return;
	}

	while ((read = getline(&line, &len, fp)) != -1) {
		char *dup = strdup(line);
		char *ptr = strchr(dup, '#');
		if (ptr)
			*ptr = 0;

		ptr = dup + strlen(dup) - 1;
		while(ptr >= dup && isspace(*ptr))
			*ptr-- = '\0';

		ptr = dup;
		while(isspace(*ptr))
			ptr++;

		if (strlen(ptr) == 0)
			continue;

		process_cfgline(ptr);

		free(dup);
	}

	fclose(fp);
	free(line);
}

void
Kernel::process_cfgline(const char *line)
{
	char *ctx, *ctx2; //context pointers for strtok_r
	char *dup = strdup(line);

	char *tok = strtok_r(dup, "\t ", &ctx);
	if (strcmp(tok, "load") == 0) {
		tok = strtok_r(NULL, "\t ", &ctx);
		char *modclass = strdup(tok);
		tok = strtok_r(NULL, "\t ", &ctx);
		char *modname = strdup(tok);
		if (strtok_r(NULL, "\t ", &ctx))
			warnx("too many tokens (some ignored): '%s'", line);
		fprintf(stderr, "load: modclass '%s', modname '%s'\n",
				modclass, modname);

		load_mod(modname, modclass);

		free(modclass);
		free(modname);

	} else if (strcmp(tok, "stalk") == 0) {
		tok = strtok_r(NULL, "\t ", &ctx);
		char *modname = strdup(tok);
		tok = strtok_r(NULL, "\0", &ctx);
		char *remainder = strdup(tok);
		vector<char*> namevec;

		fprintf(stderr, "stalk: modname '%s', remainder '%s'\n",
				modname, remainder);

		char *start = remainder;
		char *tokstart, *tokend;
		while(nextqtok(start, &tokstart, &tokend)) {
			fprintf(stderr, "tok: '%*.*s'\n",
					(int)(tokend-tokstart),
					(int)(tokend-tokstart), tokstart);

			namevec.push_back(strndup(tokstart, (size_t)(tokend-tokstart)));

			start = tokend;
			if (*tokend)
				start++;
		}

		add_stalkee(modname, namevec);

		for(vector<char*>::const_iterator it = namevec.begin();
				it != namevec.end(); it++)
			free(*it);

		free(modname);
		free(remainder);

	} else {
		char *cmddup = strdup(tok);
		char *itok = strtok_r(cmddup, "_", &ctx2);
		char *mod = strdup(itok);
		itok = strtok_r(NULL, "\t ", &ctx2);
		char *sett = strdup(itok);
		itok = strtok_r(NULL, "\0", &ctx);
		while(isspace(*itok))
			itok++;

		char *val = strdup(itok);
		fprintf(stderr, "set: mod '%s', sett '%s', val '%s'\n",
				mod, sett, val);

		add_cfg(mod, sett, val);

		free(val);
		free(sett);
		free(mod);
		free(cmddup);
	}

	free(dup);
}

bool
Kernel::nextqtok(char *data, char **tokstart, char **tokend)
{
	char *start = data;

	while(isspace(*start))
		start++;

	if(!*start)
		return false;

	bool inq = false;
	bool quoted = false;
	char *end = start;
	while(*end) {
		if (*end == '"') {
			if (!(inq = !inq)) //leaving quotes
				break;
			else
				quoted = true;
		} else if (isspace(*end) && !inq)
			break;

		end++;
	}

	if (quoted)
		start++;

	*tokstart = start;
	*tokend = end;

	return true;
}

void
Kernel::add_stalkee(const char *mname, vector<char*> const& user)
{
	if (!modmap_.count(std::string(mname))) {
		warnx("unknown module: '%s'", mname);
		return;
	}

	Module *mod = modmap_[mname];
	vector<vector<string> > &stvec = stmap_[mod];

	stvec.push_back(vector<string>());

	for(vector<char*>::const_iterator it = user.begin();
			it != user.end(); it++) {
		stvec.back().push_back(string(*it));
	}
}

void
Kernel::add_cfg(const char *mname, const char *sett, const char *val)
{
	if (!modmap_.count(std::string(mname))) {
		warnx("unknown module: '%s'", mname);
		return;
	}

	Module *mod = modmap_[mname];
	map<string, cfgent> *cfg = cfgmap_[mod];

	if ((*val >= '0' && *val <= '9') || *val == '-' || *val == '.') {
		if (strchr(val, '.')||strchr(val, 'e')||strchr(val, 'E')) {
			//treat as double
			(*cfg)[sett].typ = cfgent::DBL;
			(*cfg)[sett].val.dbl_ = strtod(val, NULL);
		} else {
			//treat as long
			(*cfg)[sett].typ = cfgent::LNG;
			(*cfg)[sett].val.lng_ = strtol(val, NULL, 10);
		}
	} else {
		//treat as string
		(*cfg)[sett].typ = cfgent::STR;
		if (*val == '"') {
			bool endq = *(val+strlen(val)-1) == '"';
			(*cfg)[sett].val.str_ = strndup(val + 1,
					strlen(val) - endq?2:1);
		} else
			(*cfg)[sett].val.str_ = strdup(val);
	}
}

void
Kernel::load_mod(const char *mname, const char *mclass)
{
	if (!facmap_.count(std::string(mclass))) {
		warnx("no such class: '%s' (not registered in Kernel.h?)",
				mclass);
		return;
	}

	if (modmap_.count(std::string(mname))) {
		warnx("name already in use: '%s'", mname);
		return;
	}

	Module *mod = facmap_[mclass]();
	if (!mod) {
		warnx("failed to instantiate '%s'", mclass);
		return;
	}

	modmap_[mname] = mod;
	cfgmap_[mod] = new map<string, cfgent>;
	stmap_[mod] = vector<vector<string> >();
}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "Parser.h"
#include "Instr.h"
#include "Seq.h"

// ===========
// Constructor
// ===========

Parser::Parser(const char* filename)
{
  if (filename[0] == '-')
    fp = stdin;
  else {
    fp = fopen(filename, "rt");
    if (fp == NULL) {
      fprintf(stderr, "Can't open trace file '%s'.\n", filename);
      exit(EXIT_FAILURE);
    }
  }
  nextId = 0;
  lineNumber = 1;
  done = interactive = false;
}

// =============
// Deconstructor
// =============

Parser::~Parser()
{
  if (fp != NULL) fclose(fp);
}

// ========================
// General parsing routines
// ========================

// Exit with an error message and a line number.

void Parser::parseError(const char* msg)
{
  fprintf(stderr, "Parse error on line %i:\n%s\n", lineNumber, msg);
  exit(EXIT_FAILURE);
}

// Get next character.

inline char Parser::getChar()
{
  int c = fgetc(fp);
  if (c == EOF) parseError("Unexpected EOF");
  if (c == '\n') lineNumber++;
  return (char) c;
}

// Un-get next character.

inline void Parser::ungetChar(char c)
{
  if (c == '\n') lineNumber--;
  ungetc((int) c, fp);
}

// Parse given character or fail hard.

void Parser::demand(char x)
{
  char c = getChar();
  if (c != x) parseError("Unexpected character");
}

// Parse given string or fail hard.

void Parser::demandString(const char* s)
{
  while (*s != '\0') {
    demand(*s);
    s++;
  }
}

// Parse given character or fail soft.

bool Parser::eat(char x)
{
  char c = getChar();
  if (c != x) {
    ungetChar(c);
    return false;
  }
  return true;
}

// Parse natural number or fail.

int Parser::parseNat()
{
  char nat[10];
  int i;
  for (i = 0; i < 10; i++) {
    char c = getChar();
    if (isdigit(c))
      nat[i] = c;
    else {
      nat[i] = '\0';
      ungetChar(c);
      break;
    }
  }
  if (i == 0) parseError("Expected number");
  if (i == 10) parseError("Number too long");
  return atoi(nat);
}

// Consume as many spaces as possible.

void Parser::spaces()
{
  bool comment = false;
  for (;;) {
    int c = fgetc(fp);
    if (c == EOF) return;
    if (c == '\n') { lineNumber++; comment = false; }
    if (c == '#') comment = true;
    if (!comment && !isspace(c)) {
      ungetChar((char) c);
      return;
    }
  }
}

// ==================
// Instruction parser
// ==================

Addr Parser::parseAddr()
{
  Addr addr;
  char c = getChar();
  if (c == 'M') {
    demand('[');
    spaces();
    addr = parseNat();
    spaces();
    demand(']');
  }
  else if (c == 'v') {
    addr = parseNat();
  }
  else
    parseError("Variable expected");
  return addr;
}

void Parser::parseTimestamp(Time* begin, Time* end)
{
  spaces();
  if (eat('@')) {
    spaces();
    if (! eat(':')) {
      *begin = parseNat();
      demand(':');
    }
    char c = getChar();
    ungetChar(c);
    if (isdigit(c))
      *end = parseNat();
  }
  spaces();
}

Instr Parser::parseInstr()
{
  Instr i;
  i.lineNumber = lineNumber;
  if (eat('c')) {
    demandString("heck");
    i.uid = -1;
    i.op = END;
    return i;
  }
  if (eat('f')) {
    demandString("inal");
    i.uid = -1;
    i.op = FINAL;
    spaces();
    i.addr = parseAddr();   spaces();
    demandString("==");     spaces();
    i.readVal = parseNat(); spaces();
    return i;
  }
  i.uid = nextId++;
  i.tid = parseNat();
  i.beginTime = i.endTime = -1;
  spaces();
  demand(':');
  spaces();
  if (eat('{')) {
    // Read-modify-write
    i.op = RMW;
    spaces();
    i.addr = parseAddr();
    spaces();
    demandString("==");
    spaces();
    i.readVal = parseNat();
    spaces();
    demand(';');
    spaces();
    if (parseAddr() != i.addr)
      parseError("Addresses in read-modify-write must be the same");
    spaces();
    demandString(":=");
    spaces();
    i.writeVal = parseNat();
    spaces();
    demand('}');
  }
  else {
    if (eat('s')) {
      // Barrier
      demandString("ync");
      i.op = SYNC;
    }
    else {
      i.addr = parseAddr();
      spaces();
      char c = getChar();
      if (c == '=' || c == ':') {
        // Load or store
        i.op = c == '=' ? LD : ST;
        demand('=');
        spaces();
        Data d = parseNat();
        if (i.op == LD) i.readVal = d; else i.writeVal = d;
      }
      else {
        parseError("Unexpected character");
      }
    }
  }
  spaces();
  if (!feof(fp)) parseTimestamp(&i.beginTime, &i.endTime);
  spaces();
  return i;
}

// ======================
// Top-level trace parser
// ======================

bool Parser::parseTrace(Seq<Instr>* instrs)
{
  if (done) return false;
  instrs->clear();
  nextId = 0;
  while (! feof(fp)) {
    spaces();
    Instr i = parseInstr();
    if (i.op == END) {
      interactive = true;
      return true;
    }
    else
      instrs->append(i);
  }
  if (interactive)
    return false;
  else {
    done = true;
    return true;
  }
}
<commit_msg>Parser tweak<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "Parser.h"
#include "Instr.h"
#include "Seq.h"

// ===========
// Constructor
// ===========

Parser::Parser(const char* filename)
{
  if (filename[0] == '-')
    fp = stdin;
  else {
    fp = fopen(filename, "rt");
    if (fp == NULL) {
      fprintf(stderr, "Can't open trace file '%s'.\n", filename);
      exit(EXIT_FAILURE);
    }
  }
  nextId = 0;
  lineNumber = 1;
  done = interactive = false;
}

// =============
// Deconstructor
// =============

Parser::~Parser()
{
  if (fp != NULL) fclose(fp);
}

// ========================
// General parsing routines
// ========================

// Exit with an error message and a line number.

void Parser::parseError(const char* msg)
{
  fprintf(stderr, "Parse error on line %i:\n%s\n", lineNumber, msg);
  exit(EXIT_FAILURE);
}

// Get next character.

inline char Parser::getChar()
{
  int c = fgetc(fp);
  if (c == EOF) parseError("Unexpected EOF");
  if (c == '\n') lineNumber++;
  return (char) c;
}

// Un-get next character.

inline void Parser::ungetChar(char c)
{
  if (c == '\n') lineNumber--;
  ungetc((int) c, fp);
}

// Parse given character or fail hard.

void Parser::demand(char x)
{
  char c = getChar();
  if (c != x) parseError("Unexpected character");
}

// Parse given string or fail hard.

void Parser::demandString(const char* s)
{
  while (*s != '\0') {
    demand(*s);
    s++;
  }
}

// Parse given character or fail soft.

bool Parser::eat(char x)
{
  char c = getChar();
  if (c != x) {
    ungetChar(c);
    return false;
  }
  return true;
}

// Parse natural number or fail.

int Parser::parseNat()
{
  char nat[10];
  int i;
  for (i = 0; i < 10; i++) {
    char c = getChar();
    if (isdigit(c))
      nat[i] = c;
    else {
      nat[i] = '\0';
      ungetChar(c);
      break;
    }
  }
  if (i == 0) parseError("Expected number");
  if (i == 10) parseError("Number too long");
  return atoi(nat);
}

// Consume as many spaces as possible.

void Parser::spaces()
{
  bool comment = false;
  for (;;) {
    int c = fgetc(fp);
    if (c == EOF) return;
    if (c == '\n') { lineNumber++; comment = false; }
    if (c == '#') comment = true;
    if (!comment && !isspace(c)) {
      ungetChar((char) c);
      return;
    }
  }
}

// ==================
// Instruction parser
// ==================

Addr Parser::parseAddr()
{
  Addr addr;
  char c = getChar();
  if (c == 'M') {
    demand('[');
    spaces();
    addr = parseNat();
    spaces();
    demand(']');
  }
  else if (c == 'v') {
    addr = parseNat();
  }
  else
    parseError("Variable expected");
  return addr;
}

void Parser::parseTimestamp(Time* begin, Time* end)
{
  spaces();
  if (eat('@')) {
    spaces();
    if (! eat(':')) {
      *begin = parseNat();
      demand(':');
    }
    char c = getChar();
    ungetChar(c);
    if (isdigit(c))
      *end = parseNat();
  }
  spaces();
}

Instr Parser::parseInstr()
{
  Instr i;
  i.lineNumber = lineNumber;
  if (eat('c')) {
    demandString("heck");
    i.uid = -1;
    i.op = END;
    return i;
  }
  if (eat('f')) {
    demandString("inal");
    i.uid = -1;
    i.op = FINAL;
    spaces();
    i.addr = parseAddr();   spaces();
    demandString("==");     spaces();
    i.readVal = parseNat(); spaces();
    return i;
  }
  i.uid = nextId++;
  i.tid = parseNat();
  i.beginTime = i.endTime = -1;
  spaces();
  demand(':');
  spaces();
  if (eat('{')) {
    // Read-modify-write
    i.op = RMW;
    spaces();
    i.addr = parseAddr();
    spaces();
    demandString("==");
    spaces();
    i.readVal = parseNat();
    spaces();
    demand(';');
    spaces();
    if (parseAddr() != i.addr)
      parseError("Addresses in read-modify-write must be the same");
    spaces();
    demandString(":=");
    spaces();
    i.writeVal = parseNat();
    spaces();
    demand('}');
  }
  else {
    if (eat('s')) {
      // Barrier
      demandString("ync");
      i.op = SYNC;
    }
    else {
      i.addr = parseAddr();
      spaces();
      char c = getChar();
      if (c == '=' || c == ':') {
        // Load or store
        i.op = c == '=' ? LD : ST;
        demand('=');
        spaces();
        Data d = parseNat();
        if (i.op == LD) i.readVal = d; else i.writeVal = d;
      }
      else {
        parseError("Unexpected character");
      }
    }
  }
  spaces();
  if (!feof(fp)) parseTimestamp(&i.beginTime, &i.endTime);
  spaces();
  return i;
}

// ======================
// Top-level trace parser
// ======================

bool Parser::parseTrace(Seq<Instr>* instrs)
{
  if (done) return false;
  instrs->clear();
  nextId = 0;
  spaces();
  while (! feof(fp)) {
    spaces();
    Instr i = parseInstr();
    if (i.op == END) {
      interactive = true;
      return true;
    }
    else
      instrs->append(i);
  }
  if (interactive)
    return false;
  else {
    done = true;
    return true;
  }
}
<|endoftext|>


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

#include "Printer.h"

#include "GlucoseWrapper.h"

extern Glucose::BoolOption option_print_model;

namespace zuccherino {

#define BUFFSIZE 1048576

Printer::Printer(GlucoseWrapper& solver_) : solver(solver_), models_unknown("s UNKNOWN\\n"), models_none("s UNSATISFIABLE\\n"), models_start("s SATISFIABLE\\n"), models_end(""), model_start("c Model #\\nv "), model_sep(""), model_end("\\n"), lit_start(""), lit_sep(" "), lit_end("") {
}

Printer::~Printer() {
    delete[] buff;
}

void Printer::parseAttach(Glucose::StreamBuffer& in) {
    assert(buff == NULL);
    Parser::parseAttach(in);
    buff = new char[BUFFSIZE];
}

void Printer::parse() {
    assert(buff != NULL);

    int count = readline();
    char* tmp = buff;

    if(startswith(tmp, "models unknown:")) models_unknown = string(tmp);
    else if(startswith(tmp, "models none:")) models_none = string(tmp);
    else if(startswith(tmp, "models start:")) models_start = string(tmp);
    else if(startswith(tmp, "models end:")) models_end = string(tmp);
    else if(startswith(tmp, "model start:")) model_start = string(tmp);
    else if(startswith(tmp, "model sep:")) model_sep = string(tmp);
    else if(startswith(tmp, "model end:")) model_end = string(tmp);
    else if(startswith(tmp, "lit start:")) lit_start = string(tmp);
    else if(startswith(tmp, "lit sep:")) lit_sep = string(tmp);
    else if(startswith(tmp, "lit end:")) lit_end = string(tmp);
    else {
        Lit lit = parseLit(tmp, solver);
        tmp++;
        addVisible(lit, tmp, count - (tmp - buff));
    }
}

void Printer::parseDetach() {
    assert(buff != NULL);
    delete[] buff;
    buff = NULL;
}

void Printer::addVisible(Lit lit, const char* str, int len) {
    assert(len >= 0);
    assert(static_cast<int>(strlen(str)) <= len);
    visible.push();
    visible.last().lit = lit;
    visible.last().value = new char[len+1];
    strcpy(visible.last().value, str);
}

void Printer::onStart() {
    modelCount = 0;
}

void Printer::onModel() {
    modelCount++;
    if(!option_print_model) return;

    if(modelCount == 1) pretty_print(models_start, modelCount);
    else pretty_print(model_sep, modelCount);
    pretty_print(model_start, modelCount);
    if(visible.size() == 0) {
        for(int i = 0; i < solver.model.size(); i++) {
            if(i > 0) pretty_print(lit_sep, i+1);
            pretty_print(lit_start, i+1);
            if(solver.model[i] == l_False) cout << '-';
            cout << (i+1);
            pretty_print(lit_end, i+1);
        }
    }
    else {
        for(int i = 0, lits = 1; i < visible.size(); i++) {
            assert(var(visible[i].lit) < solver.model.size());
            if(sign(visible[i].lit) ^ (solver.model[var(visible[i].lit)] != l_True)) continue;
            if(lits > 1) pretty_print(lit_sep, lits);
            pretty_print(lit_start, lits);
            cout << visible[i].value;
            pretty_print(lit_end, lits);
            lits++;
        }
    }
    pretty_print(model_end, modelCount);
    cout.flush();
}

void Printer::onDone() {
    if(modelCount > 0) pretty_print(models_end, modelCount);
    else if(solver.okay()) pretty_print(models_unknown, modelCount);
    else pretty_print(models_none, modelCount);
}

int Printer::readline() {
    int count = 0;
    while(*in() != EOF && *in() != '\n' && static_cast<unsigned>(count) < BUFFSIZE) { buff[count++] = *in(); ++in(); }
    if(static_cast<unsigned>(count) >= BUFFSIZE) cerr << "PARSE ERROR! String " << buff << " is too long!" << endl, exit(3);
    buff[count] = '\0';
    return count;
}

char* Printer::startswith(char*& str, const char* pre) {
    unsigned len = strlen(pre);
    if(strncmp(str, pre, len) != 0) return NULL;
    return str = str + len;
}

void Printer::pretty_print(const string& str, int count) {
    for(unsigned i = 0; i < str.size(); i++) {
        if(str[i] == '#') cout << count;
        else if(str[i] == '\\' && i+1 < str.size() && str[i+1] == 'n') { cout << '\n'; i++; }
        else cout << str[i];
    }
}

}
<commit_msg>Init buff to NULL.<commit_after>/*
 *  Copyright (C) 2017  Mario Alviano (mario@alviano.net)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

#include "Printer.h"

#include "GlucoseWrapper.h"

extern Glucose::BoolOption option_print_model;

namespace zuccherino {

#define BUFFSIZE 1048576

Printer::Printer(GlucoseWrapper& solver_) : solver(solver_), buff(NULL), models_unknown("s UNKNOWN\\n"), models_none("s UNSATISFIABLE\\n"), models_start("s SATISFIABLE\\n"), models_end(""), model_start("c Model #\\nv "), model_sep(""), model_end("\\n"), lit_start(""), lit_sep(" "), lit_end("") {
}

Printer::~Printer() {
    delete[] buff;
}

void Printer::parseAttach(Glucose::StreamBuffer& in) {
    assert(buff == NULL);
    Parser::parseAttach(in);
    buff = new char[BUFFSIZE];
}

void Printer::parse() {
    assert(buff != NULL);

    int count = readline();
    char* tmp = buff;

    if(startswith(tmp, "models unknown:")) models_unknown = string(tmp);
    else if(startswith(tmp, "models none:")) models_none = string(tmp);
    else if(startswith(tmp, "models start:")) models_start = string(tmp);
    else if(startswith(tmp, "models end:")) models_end = string(tmp);
    else if(startswith(tmp, "model start:")) model_start = string(tmp);
    else if(startswith(tmp, "model sep:")) model_sep = string(tmp);
    else if(startswith(tmp, "model end:")) model_end = string(tmp);
    else if(startswith(tmp, "lit start:")) lit_start = string(tmp);
    else if(startswith(tmp, "lit sep:")) lit_sep = string(tmp);
    else if(startswith(tmp, "lit end:")) lit_end = string(tmp);
    else {
        Lit lit = parseLit(tmp, solver);
        tmp++;
        addVisible(lit, tmp, count - (tmp - buff));
    }
}

void Printer::parseDetach() {
    assert(buff != NULL);
    delete[] buff;
    buff = NULL;
}

void Printer::addVisible(Lit lit, const char* str, int len) {
    assert(len >= 0);
    assert(static_cast<int>(strlen(str)) <= len);
    visible.push();
    visible.last().lit = lit;
    visible.last().value = new char[len+1];
    strcpy(visible.last().value, str);
}

void Printer::onStart() {
    modelCount = 0;
}

void Printer::onModel() {
    modelCount++;
    if(!option_print_model) return;

    if(modelCount == 1) pretty_print(models_start, modelCount);
    else pretty_print(model_sep, modelCount);
    pretty_print(model_start, modelCount);
    if(visible.size() == 0) {
        for(int i = 0; i < solver.model.size(); i++) {
            if(i > 0) pretty_print(lit_sep, i+1);
            pretty_print(lit_start, i+1);
            if(solver.model[i] == l_False) cout << '-';
            cout << (i+1);
            pretty_print(lit_end, i+1);
        }
    }
    else {
        for(int i = 0, lits = 1; i < visible.size(); i++) {
            assert(var(visible[i].lit) < solver.model.size());
            if(sign(visible[i].lit) ^ (solver.model[var(visible[i].lit)] != l_True)) continue;
            if(lits > 1) pretty_print(lit_sep, lits);
            pretty_print(lit_start, lits);
            cout << visible[i].value;
            pretty_print(lit_end, lits);
            lits++;
        }
    }
    pretty_print(model_end, modelCount);
    cout.flush();
}

void Printer::onDone() {
    if(modelCount > 0) pretty_print(models_end, modelCount);
    else if(solver.okay()) pretty_print(models_unknown, modelCount);
    else pretty_print(models_none, modelCount);
}

int Printer::readline() {
    int count = 0;
    while(*in() != EOF && *in() != '\n' && static_cast<unsigned>(count) < BUFFSIZE) { buff[count++] = *in(); ++in(); }
    if(static_cast<unsigned>(count) >= BUFFSIZE) cerr << "PARSE ERROR! String " << buff << " is too long!" << endl, exit(3);
    buff[count] = '\0';
    return count;
}

char* Printer::startswith(char*& str, const char* pre) {
    unsigned len = strlen(pre);
    if(strncmp(str, pre, len) != 0) return NULL;
    return str = str + len;
}

void Printer::pretty_print(const string& str, int count) {
    for(unsigned i = 0; i < str.size(); i++) {
        if(str[i] == '#') cout << count;
        else if(str[i] == '\\' && i+1 < str.size() && str[i+1] == 'n') { cout << '\n'; i++; }
        else cout << str[i];
    }
}

}
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2017 Kacper Kasper <kacperkasper@gmail.com>
 * All rights reserved. Distributed under the terms of the MIT license.
 */

#include "Styler.h"

#include <cstdlib>
#include <yaml.h>

#include <FindDirectory.h>
#include <Path.h>
#include <String.h>

#include "Editor.h"
#include "EditorWindow.h"

/* static */ void
Styler::ApplyGlobal(Editor* editor, const char* style)
{
	BPath dataPath;
	find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
	} catch (YAML::BadFile &) {
	}
}

/* static */ void
Styler::_ApplyGlobal(Editor* editor, const char* style, const BPath &path)
{
	BPath p(path);
	p.Append(gAppName);
	p.Append("styles");
	p.Append(style);
	const YAML::Node global = YAML::LoadFile(std::string(p.Path()) + ".yaml");

	int id, fg, bg, fs;
	if(global["Default"]) {
		_GetAttributesFromNode(global["Default"], &id, &fg, &bg, &fs);

		font_family fixed;
		be_fixed_font->GetFamilyAndStyle(&fixed, NULL);
		editor->SendMessage(SCI_STYLESETFONT, id, (sptr_t) fixed);
		editor->SendMessage(SCI_STYLESETSIZE, id, (sptr_t) be_fixed_font->Size());
		_SetAttributesInEditor(editor, id, fg, bg, fs);
		editor->SendMessage(SCI_STYLECLEARALL, 0, 0);
	}
	for(YAML::const_iterator it = global.begin(); it != global.end(); ++it) {
		std::string name = it->first.as<std::string>();
		_GetAttributesFromNode(global[name], &id, &fg, &bg, &fs);
		if(id != -1) {
			_SetAttributesInEditor(editor, id, fg, bg, fs);
		} else {
			if(name == "Current line") {
				editor->SendMessage(SCI_SETCARETLINEBACK, bg, 0);
				//editor->SendMessage(SCI_SETCARETLINEBACKALPHA, 128, 0);
			}
			else if(name == "Whitespace") {
				if(fg != -1) {
					editor->SendMessage(SCI_SETWHITESPACEFORE, true, fg);
				}
				if(bg != -1) {
					editor->SendMessage(SCI_SETWHITESPACEBACK, true, bg);
				}
			}
			else if(name == "Selected text") {
				if(fg != -1) {
					editor->SendMessage(SCI_SETSELFORE, true, fg);
				}
				if(bg != -1) {
					editor->SendMessage(SCI_SETSELBACK, true, bg);
				}
			}
			else if(name == "Caret") {
				editor->SendMessage(SCI_SETCARETFORE, fg, 0);
			}
			else if(name == "Edge") {
				editor->SendMessage(SCI_SETEDGECOLOUR, fg, 0);
			}
			else if(name == "Fold") {
				if(fg != -1) {
					editor->SendMessage(SCI_SETFOLDMARGINHICOLOUR, true, fg);
				}
				if(bg != -1) {
					editor->SendMessage(SCI_SETFOLDMARGINCOLOUR, true, bg);
				}
			}
		}
	}
}

/* static */ void
Styler::ApplyLanguage(Editor* editor, const char* style, const char* lang)
{
	BPath dataPath;
	find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyLanguage(editor, style, lang, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyLanguage(editor, style, lang, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyLanguage(editor, style, lang, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyLanguage(editor, style, lang, dataPath);
	} catch (YAML::BadFile &) {
	}
}

/* static */ void
Styler::_ApplyLanguage(Editor* editor, const char* style, const char* lang, const BPath &path)
{
	BPath p(path);
	p.Append(gAppName);
	p.Append("styles");
	p.Append(style);
	p.Append(lang);
	const YAML::Node language = YAML::LoadFile(std::string(p.Path()) + ".yaml");
	int id, fg, bg, fs;
	for(YAML::const_iterator it = language.begin(); it != language.end(); ++it) {
		std::string name = it->first.as<std::string>();
		_GetAttributesFromNode(language[name], &id, &fg, &bg, &fs);
		_SetAttributesInEditor(editor, id, fg, bg, fs);
	}
}

void
Styler::_GetAttributesFromNode(const YAML::Node &node, int* styleId, int* fgColor,
	int* bgColor, int* fontStyle)
{
	*styleId = -1;
	*fgColor = -1;
	*bgColor = -1;
	*fontStyle = -1;

	if(node["id"]) {
		*styleId = node["id"].as<int>();
	}
	if(node["foreground"]) {
		*fgColor = strtol(node["foreground"].as<std::string>().c_str(), NULL, 16);
	}
	if(node["background"]) {
		*bgColor = strtol(node["background"].as<std::string>().c_str(), NULL, 16);
	}
	if(node["style"]) {
		*fontStyle = 0;
		auto styles = node["style"].as<std::vector<std::string>>();
		for(auto style : styles) {
			if(style == "bold") *fontStyle |= 1;
			else if(style == "italic") *fontStyle |= 2;
			else if(style == "underline") *fontStyle |= 4;
		}
	}
}

void
Styler::_SetAttributesInEditor(Editor* editor, int styleId, int fgColor,
	int bgColor, int fontStyle)
{
	if(fgColor != -1) {
		editor->SendMessage(SCI_STYLESETFORE, styleId, fgColor);
	}
	if(bgColor != -1) {
		editor->SendMessage(SCI_STYLESETBACK, styleId, bgColor);
	}
	if(fontStyle != -1) {
		if(fontStyle & 1) {
			editor->SendMessage(SCI_STYLESETBOLD, styleId, true);
		}
		if(fontStyle & 2) {
			editor->SendMessage(SCI_STYLESETITALIC, styleId, true);
		}
		if(fontStyle & 4) {
			editor->SendMessage(SCI_STYLESETUNDERLINE, styleId, true);
		}
	}
}
<commit_msg>Adjust whitespace size.<commit_after>/*
 * Copyright 2014-2017 Kacper Kasper <kacperkasper@gmail.com>
 * All rights reserved. Distributed under the terms of the MIT license.
 */

#include "Styler.h"

#include <cstdlib>
#include <yaml.h>

#include <FindDirectory.h>
#include <Path.h>
#include <String.h>

#include "Editor.h"
#include "EditorWindow.h"

/* static */ void
Styler::ApplyGlobal(Editor* editor, const char* style)
{
	BPath dataPath;
	find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyGlobal(editor, style, dataPath);
	} catch (YAML::BadFile &) {
	}
}

/* static */ void
Styler::_ApplyGlobal(Editor* editor, const char* style, const BPath &path)
{
	BPath p(path);
	p.Append(gAppName);
	p.Append("styles");
	p.Append(style);
	const YAML::Node global = YAML::LoadFile(std::string(p.Path()) + ".yaml");

	int id, fg, bg, fs;
	if(global["Default"]) {
		_GetAttributesFromNode(global["Default"], &id, &fg, &bg, &fs);

		font_family fixed;
		be_fixed_font->GetFamilyAndStyle(&fixed, NULL);
		editor->SendMessage(SCI_STYLESETFONT, id, (sptr_t) fixed);
		editor->SendMessage(SCI_STYLESETSIZE, id, (sptr_t) be_fixed_font->Size());
		_SetAttributesInEditor(editor, id, fg, bg, fs);
		editor->SendMessage(SCI_STYLECLEARALL, 0, 0);
		editor->SendMessage(SCI_STYLESETFONT, 36, (sptr_t) fixed);
		editor->SendMessage(SCI_STYLESETSIZE, 36, (sptr_t) (be_fixed_font->Size() / 1.3));
		editor->SendMessage(SCI_SETWHITESPACESIZE, be_fixed_font->Size() / 6, 0);
	}
	for(YAML::const_iterator it = global.begin(); it != global.end(); ++it) {
		std::string name = it->first.as<std::string>();
		_GetAttributesFromNode(global[name], &id, &fg, &bg, &fs);
		if(id != -1) {
			_SetAttributesInEditor(editor, id, fg, bg, fs);
		} else {
			if(name == "Current line") {
				editor->SendMessage(SCI_SETCARETLINEBACK, bg, 0);
				//editor->SendMessage(SCI_SETCARETLINEBACKALPHA, 128, 0);
			}
			else if(name == "Whitespace") {
				if(fg != -1) {
					editor->SendMessage(SCI_SETWHITESPACEFORE, true, fg);
				}
				if(bg != -1) {
					editor->SendMessage(SCI_SETWHITESPACEBACK, true, bg);
				}
			}
			else if(name == "Selected text") {
				if(fg != -1) {
					editor->SendMessage(SCI_SETSELFORE, true, fg);
				}
				if(bg != -1) {
					editor->SendMessage(SCI_SETSELBACK, true, bg);
				}
			}
			else if(name == "Caret") {
				editor->SendMessage(SCI_SETCARETFORE, fg, 0);
			}
			else if(name == "Edge") {
				editor->SendMessage(SCI_SETEDGECOLOUR, fg, 0);
			}
			else if(name == "Fold") {
				if(fg != -1) {
					editor->SendMessage(SCI_SETFOLDMARGINHICOLOUR, true, fg);
				}
				if(bg != -1) {
					editor->SendMessage(SCI_SETFOLDMARGINCOLOUR, true, bg);
				}
			}
		}
	}
}

/* static */ void
Styler::ApplyLanguage(Editor* editor, const char* style, const char* lang)
{
	BPath dataPath;
	find_directory(B_SYSTEM_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyLanguage(editor, style, lang, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyLanguage(editor, style, lang, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_SYSTEM_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyLanguage(editor, style, lang, dataPath);
	} catch (YAML::BadFile &) {
	}
	find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY, &dataPath);
	try {
		_ApplyLanguage(editor, style, lang, dataPath);
	} catch (YAML::BadFile &) {
	}
}

/* static */ void
Styler::_ApplyLanguage(Editor* editor, const char* style, const char* lang, const BPath &path)
{
	BPath p(path);
	p.Append(gAppName);
	p.Append("styles");
	p.Append(style);
	p.Append(lang);
	const YAML::Node language = YAML::LoadFile(std::string(p.Path()) + ".yaml");
	int id, fg, bg, fs;
	for(YAML::const_iterator it = language.begin(); it != language.end(); ++it) {
		std::string name = it->first.as<std::string>();
		_GetAttributesFromNode(language[name], &id, &fg, &bg, &fs);
		_SetAttributesInEditor(editor, id, fg, bg, fs);
	}
}

void
Styler::_GetAttributesFromNode(const YAML::Node &node, int* styleId, int* fgColor,
	int* bgColor, int* fontStyle)
{
	*styleId = -1;
	*fgColor = -1;
	*bgColor = -1;
	*fontStyle = -1;

	if(node["id"]) {
		*styleId = node["id"].as<int>();
	}
	if(node["foreground"]) {
		*fgColor = strtol(node["foreground"].as<std::string>().c_str(), NULL, 16);
	}
	if(node["background"]) {
		*bgColor = strtol(node["background"].as<std::string>().c_str(), NULL, 16);
	}
	if(node["style"]) {
		*fontStyle = 0;
		auto styles = node["style"].as<std::vector<std::string>>();
		for(auto style : styles) {
			if(style == "bold") *fontStyle |= 1;
			else if(style == "italic") *fontStyle |= 2;
			else if(style == "underline") *fontStyle |= 4;
		}
	}
}

void
Styler::_SetAttributesInEditor(Editor* editor, int styleId, int fgColor,
	int bgColor, int fontStyle)
{
	if(fgColor != -1) {
		editor->SendMessage(SCI_STYLESETFORE, styleId, fgColor);
	}
	if(bgColor != -1) {
		editor->SendMessage(SCI_STYLESETBACK, styleId, bgColor);
	}
	if(fontStyle != -1) {
		if(fontStyle & 1) {
			editor->SendMessage(SCI_STYLESETBOLD, styleId, true);
		}
		if(fontStyle & 2) {
			editor->SendMessage(SCI_STYLESETITALIC, styleId, true);
		}
		if(fontStyle & 4) {
			editor->SendMessage(SCI_STYLESETUNDERLINE, styleId, true);
		}
	}
}
<|endoftext|>