<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/ssl_config_service_mac.h"

#include <CoreFoundation/CoreFoundation.h>

#include "base/scoped_cftyperef.h"

using base::TimeDelta;
using base::TimeTicks;

namespace net {

namespace {

static const int kConfigUpdateInterval = 10;  // seconds

static const bool kSSL2EnabledDefaultValue = false;
static const bool kSSL3EnabledDefaultValue = true;
static const bool kTLS1EnabledDefaultValue = true;

static CFStringRef kRevocationPreferencesIdentifier =
    CFSTR("com.apple.security.revocation");
static CFStringRef kOCSPStyleKey = CFSTR("OCSPStyle");
static CFStringRef kCRLStyleKey = CFSTR("CRLStyle");
static CFStringRef kNoneRevocationValue = CFSTR("None");
static CFStringRef kBestAttemptRevocationValue = CFSTR("BestAttempt");
static CFStringRef kSSL2EnabledKey = CFSTR("org.chromium.ssl.ssl2");
static CFStringRef kSSL3EnabledKey = CFSTR("org.chromium.ssl.ssl3");
static CFStringRef kTLS1EnabledKey = CFSTR("org.chromium.ssl.tls1");

bool RevocationStyleIsEnabled(CFStringRef key) {
  CFPropertyListRef plist_ref = CFPreferencesCopyValue(kOCSPStyleKey,
      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,
      kCFPreferencesAnyHost);
  if (plist_ref) {
    scoped_cftyperef<CFPropertyListRef> scoped_plist_ref(plist_ref);
    if (CFGetTypeID(plist_ref) == CFStringGetTypeID()) {
      CFStringRef style = reinterpret_cast<CFStringRef>(plist_ref);
      if (CFStringCompare(kNoneRevocationValue, style,
                          kCFCompareCaseInsensitive))
        return true;
    }
  }
  return false;
}

inline bool SSLVersionIsEnabled(CFStringRef key, bool default_value) {
  Boolean exists_and_valid;
  Boolean rv = CFPreferencesGetAppBooleanValue(key,
                                               kCFPreferencesCurrentApplication,
                                               &exists_and_valid);
  if (!exists_and_valid)
    return default_value;
  return rv;
}

}  // namespace

SSLConfigServiceMac::SSLConfigServiceMac() : ever_updated_(false) {
  // We defer retrieving the settings until the first call to GetSSLConfig, to
  // avoid an expensive call on the UI thread, which could affect startup time.
}

SSLConfigServiceMac::SSLConfigServiceMac(TimeTicks now) : ever_updated_(false) {
  UpdateConfig(now);
}

void SSLConfigServiceMac::GetSSLConfigAt(SSLConfig* config, TimeTicks now) {
  if (!ever_updated_ ||
      now - config_time_ > TimeDelta::FromSeconds(kConfigUpdateInterval))
    UpdateConfig(now);
  *config = config_info_;
}

// static
bool SSLConfigServiceMac::GetSSLConfigNow(SSLConfig* config) {
  // Our own revocation checking flag is a binary value, but Mac OS X uses
  // several shades of revocation checking:
  //   - None (i.e., disabled, the default)
  //   - BestAttempt
  //   - RequireIfPresent
  //   - RequireForall
  // Mac OS X also breaks down revocation check for both CRLs and OCSP. We
  // set our revocation flag if the system-wide settings for either OCSP
  // or CRLs is anything other than None.
  config->rev_checking_enabled = (RevocationStyleIsEnabled(kOCSPStyleKey) ||
                                  RevocationStyleIsEnabled(kCRLStyleKey));

  config->ssl2_enabled = SSLVersionIsEnabled(kSSL2EnabledKey,
                                             kSSL2EnabledDefaultValue);
  config->ssl3_enabled = SSLVersionIsEnabled(kSSL3EnabledKey,
                                             kSSL3EnabledDefaultValue);
  config->tls1_enabled = SSLVersionIsEnabled(kTLS1EnabledKey,
                                             kTLS1EnabledDefaultValue);

  return true;
}

// static
void SSLConfigServiceMac::SetSSL2Enabled(bool enabled) {
  CFPreferencesSetAppValue(kSSL2EnabledKey,
                           enabled ? kCFBooleanTrue : kCFBooleanFalse,
                           kCFPreferencesCurrentApplication);
  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
}

// static
void SSLConfigServiceMac::SetSSL3Enabled(bool enabled) {
  CFPreferencesSetAppValue(kSSL3EnabledKey,
                           enabled ? kCFBooleanTrue : kCFBooleanFalse,
                           kCFPreferencesCurrentApplication);
  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
}

// static
void SSLConfigServiceMac::SetTLS1Enabled(bool enabled) {
  CFPreferencesSetAppValue(kTLS1EnabledKey,
                           enabled ? kCFBooleanTrue : kCFBooleanFalse,
                           kCFPreferencesCurrentApplication);
  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
}

// static
void SSLConfigServiceMac::SetRevCheckingEnabled(bool enabled) {
  // This method is provided for use by the unit tests. These settings
  // are normally changed via the Keychain Access application's preferences
  // dialog.
  CFPreferencesSetValue(kOCSPStyleKey,
      enabled ? kBestAttemptRevocationValue : kNoneRevocationValue,
      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,
      kCFPreferencesAnyHost);
  CFPreferencesSetValue(kCRLStyleKey,
      enabled ? kBestAttemptRevocationValue : kNoneRevocationValue,
      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,
      kCFPreferencesAnyHost);
}

void SSLConfigServiceMac::UpdateConfig(TimeTicks now) {
  GetSSLConfigNow(&config_info_);
  config_time_ = now;
  ever_updated_ = true;
}

}  // namespace net
<commit_msg>Fix a bug that caused the Mac SSL config service only check the system OCSP setting, ignoring the CRL setting. Not a problem at the moment since revocation isn't hooked up at the lower level, but it would have been a problem in due time. BUG=none TEST=none Review URL: http://codereview.chromium.org/215014<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/ssl_config_service_mac.h"

#include <CoreFoundation/CoreFoundation.h>

#include "base/scoped_cftyperef.h"

using base::TimeDelta;
using base::TimeTicks;

namespace net {

namespace {

static const int kConfigUpdateInterval = 10;  // seconds

static const bool kSSL2EnabledDefaultValue = false;
static const bool kSSL3EnabledDefaultValue = true;
static const bool kTLS1EnabledDefaultValue = true;

static CFStringRef kRevocationPreferencesIdentifier =
    CFSTR("com.apple.security.revocation");
static CFStringRef kOCSPStyleKey = CFSTR("OCSPStyle");
static CFStringRef kCRLStyleKey = CFSTR("CRLStyle");
static CFStringRef kNoneRevocationValue = CFSTR("None");
static CFStringRef kBestAttemptRevocationValue = CFSTR("BestAttempt");
static CFStringRef kSSL2EnabledKey = CFSTR("org.chromium.ssl.ssl2");
static CFStringRef kSSL3EnabledKey = CFSTR("org.chromium.ssl.ssl3");
static CFStringRef kTLS1EnabledKey = CFSTR("org.chromium.ssl.tls1");

bool RevocationStyleIsEnabled(CFStringRef key) {
  CFPropertyListRef plist_ref = CFPreferencesCopyValue(key,
      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,
      kCFPreferencesAnyHost);
  if (plist_ref) {
    scoped_cftyperef<CFPropertyListRef> scoped_plist_ref(plist_ref);
    if (CFGetTypeID(plist_ref) == CFStringGetTypeID()) {
      CFStringRef style = reinterpret_cast<CFStringRef>(plist_ref);
      if (CFStringCompare(kNoneRevocationValue, style,
                          kCFCompareCaseInsensitive))
        return true;
    }
  }
  return false;
}

inline bool SSLVersionIsEnabled(CFStringRef key, bool default_value) {
  Boolean exists_and_valid;
  Boolean rv = CFPreferencesGetAppBooleanValue(key,
                                               kCFPreferencesCurrentApplication,
                                               &exists_and_valid);
  if (!exists_and_valid)
    return default_value;
  return rv;
}

}  // namespace

SSLConfigServiceMac::SSLConfigServiceMac() : ever_updated_(false) {
  // We defer retrieving the settings until the first call to GetSSLConfig, to
  // avoid an expensive call on the UI thread, which could affect startup time.
}

SSLConfigServiceMac::SSLConfigServiceMac(TimeTicks now) : ever_updated_(false) {
  UpdateConfig(now);
}

void SSLConfigServiceMac::GetSSLConfigAt(SSLConfig* config, TimeTicks now) {
  if (!ever_updated_ ||
      now - config_time_ > TimeDelta::FromSeconds(kConfigUpdateInterval))
    UpdateConfig(now);
  *config = config_info_;
}

// static
bool SSLConfigServiceMac::GetSSLConfigNow(SSLConfig* config) {
  // Our own revocation checking flag is a binary value, but Mac OS X uses
  // several shades of revocation checking:
  //   - None (i.e., disabled, the default)
  //   - BestAttempt
  //   - RequireIfPresent
  //   - RequireForall
  // Mac OS X also breaks down revocation check for both CRLs and OCSP. We
  // set our revocation flag if the system-wide settings for either OCSP
  // or CRLs is anything other than None.
  config->rev_checking_enabled = (RevocationStyleIsEnabled(kOCSPStyleKey) ||
                                  RevocationStyleIsEnabled(kCRLStyleKey));

  config->ssl2_enabled = SSLVersionIsEnabled(kSSL2EnabledKey,
                                             kSSL2EnabledDefaultValue);
  config->ssl3_enabled = SSLVersionIsEnabled(kSSL3EnabledKey,
                                             kSSL3EnabledDefaultValue);
  config->tls1_enabled = SSLVersionIsEnabled(kTLS1EnabledKey,
                                             kTLS1EnabledDefaultValue);

  return true;
}

// static
void SSLConfigServiceMac::SetSSL2Enabled(bool enabled) {
  CFPreferencesSetAppValue(kSSL2EnabledKey,
                           enabled ? kCFBooleanTrue : kCFBooleanFalse,
                           kCFPreferencesCurrentApplication);
  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
}

// static
void SSLConfigServiceMac::SetSSL3Enabled(bool enabled) {
  CFPreferencesSetAppValue(kSSL3EnabledKey,
                           enabled ? kCFBooleanTrue : kCFBooleanFalse,
                           kCFPreferencesCurrentApplication);
  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
}

// static
void SSLConfigServiceMac::SetTLS1Enabled(bool enabled) {
  CFPreferencesSetAppValue(kTLS1EnabledKey,
                           enabled ? kCFBooleanTrue : kCFBooleanFalse,
                           kCFPreferencesCurrentApplication);
  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
}

// static
void SSLConfigServiceMac::SetRevCheckingEnabled(bool enabled) {
  // This method is provided for use by the unit tests. These settings
  // are normally changed via the Keychain Access application's preferences
  // dialog.
  CFPreferencesSetValue(kOCSPStyleKey,
      enabled ? kBestAttemptRevocationValue : kNoneRevocationValue,
      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,
      kCFPreferencesAnyHost);
  CFPreferencesSetValue(kCRLStyleKey,
      enabled ? kBestAttemptRevocationValue : kNoneRevocationValue,
      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,
      kCFPreferencesAnyHost);
}

void SSLConfigServiceMac::UpdateConfig(TimeTicks now) {
  GetSSLConfigNow(&config_info_);
  config_time_ = now;
  ever_updated_ = true;
}

}  // namespace net
<|endoftext|>


<commit_before><commit_msg>リファクタリング<commit_after><|endoftext|>


<commit_before>#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QQmlContext>
#include "coverage.h"
#include "connectorinterface.h"
#include "resource.h"
#include "georeference.h"
#include "mastercatalog.h"
#include "catalogview.h"
#include "resourcemodel.h"
#include "catalogmodel.h"
#include "layermanager.h"

using namespace Ilwis;
//using namespace Desktopclient;

CatalogModel::CatalogModel()
{
    //_hasChilderen = false;
    _initNode = false;
    _level = 0;
    _isScanned = false;
}

CatalogModel::~CatalogModel()
{

}

CatalogModel::CatalogModel(const CatalogView &view, int lvl, QObject *parent) : ResourceModel(view.resource(), parent)
{
    _initNode = true;
    _level = lvl;
    _isScanned = true;
    newview(view);

}

void CatalogModel::newview(const CatalogView &view){
    _view = view;
    mastercatalog()->addContainer(view.resource().url());
    _displayName = view.resource().name();
    if ( _displayName == sUNDEF)
        _displayName = view.resource().url().toString();
}

bool CatalogModel::isScanned() const
{
    return _isScanned;
}

bool CatalogModel::initNode() const {
    return _initNode;
}

int CatalogModel::level() const
{
    return _level;
}

QQmlListProperty<ResourceModel> CatalogModel::resources() {

    try{
        gatherItems();

        return  QQmlListProperty<ResourceModel>(this, _currentItems);
    }
    catch(const ErrorObject& err){

    }
    return  QQmlListProperty<ResourceModel>();
}

QQmlListProperty<IlwisObjectModel> CatalogModel::selectedData()
{
    return  QQmlListProperty<IlwisObjectModel>(this, _selectedObjects);
}

QQmlListProperty<CatalogMapItem> CatalogModel::mapItems()
{
   return  QQmlListProperty<CatalogMapItem>(this, _catalogMapItems);
}

void CatalogModel::makeParent(QObject *obj)
{
    setParent(obj);
}

void CatalogModel::filterChanged(const QString& objectType, bool state){
    if ( objectType == "all"){
        _filterState["rastercoverage"] = state;
        _filterState["featurecoverage"] = state;
        _filterState["table"] = state;
        _filterState["coordinatesystem"] = state;
        _filterState["georeference"] = state;
        _filterState["domain"] = state;
        _filterState["representation"] = state;
        _filterState["projection"] = state;
        _filterState["ellipsoid"] = state;

    }else
        _filterState[objectType] = state;
    QString filterString;
    for(auto iter : _filterState){
        if ( !iter.second){
            if ( filterString != "")
                filterString += " and ";
            filterString += QString("type") + "& '" + iter.first + "' =0";
        }
    }
    _refresh = true;
    _view.filter(filterString);
    contentChanged();
}

void CatalogModel::refresh(bool yesno)
{
    _refresh = yesno;
}

void CatalogModel::setSelectedObjects(const QString &objects)
{
    try {
    QStringList parts = objects.split("|");
    _selectedObjects.clear();
    for(auto objectid : parts){
        Resource resource = mastercatalog()->id2Resource(objectid.toULongLong());
        IlwisObjectModel *ioModel = new IlwisObjectModel(resource, this);
        if ( ioModel->isValid()){
            _selectedObjects.append(ioModel);
            emit selectionChanged();
        }else
            delete ioModel;
    }
    }catch(const ErrorObject& err){

    }
}

void CatalogModel::nameFilter(const QString &filter)
{
    _nameFilter = filter;
    _currentItems.clear();
    emit contentChanged();
}

QString CatalogModel::nameFilter() const
{
    return _nameFilter;
}

void CatalogModel::prepareMapItems(LayerManager *manager)
{
    try{
        if ( _catalogMapItems.size() == 0){
            for (auto iter  = _currentItems.begin(); iter != _currentItems.end(); ++iter){
                if(hasType((*iter)->type(), itCOVERAGE)){
                    Ilwis::ICoverage cov(((*iter)->resource()));
                    if ( cov.isValid() && cov->coordinateSystem().isValid())    {
                        if ( cov->coordinateSystem()->isLatLon() || cov->coordinateSystem()->canConvertToLatLon()){
                            _catalogMapItems.push_back(new CatalogMapItem(cov,manager->screenGrf(),this));
                        }
                    }
                }
            }
        }
    } catch (const Ilwis::ErrorObject& ){

    } catch (std::exception& ex){
        Ilwis::kernel()->issues()->log(ex.what());
    }
}

void CatalogModel::gatherItems() {
    if ( _currentItems.isEmpty() || _refresh) {
        if ( !_view.isValid())
            return;

        _view.prepare();

        _currentItems.clear();
        _refresh = false;

        std::vector<Resource> items = _view.items();
        for(const Resource& resource : items){
            if ( _nameFilter != ""){
                if ( resource.name().indexOf(_nameFilter) == -1){
                    if ( resource["longname"].toString().indexOf(_nameFilter) == -1)
                        continue;
                }
            }
            _currentItems.push_back(new ResourceModel(resource));

        }
    }
}

<commit_msg>silenced the messages from reading a catalog as they are not helpfull atm<commit_after>#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QQmlContext>
#include "coverage.h"
#include "connectorinterface.h"
#include "resource.h"
#include "georeference.h"
#include "mastercatalog.h"
#include "catalogview.h"
#include "resourcemodel.h"
#include "catalogmodel.h"
#include "layermanager.h"

using namespace Ilwis;
//using namespace Desktopclient;

CatalogModel::CatalogModel()
{
    //_hasChilderen = false;
    _initNode = false;
    _level = 0;
    _isScanned = false;
}

CatalogModel::~CatalogModel()
{

}

CatalogModel::CatalogModel(const CatalogView &view, int lvl, QObject *parent) : ResourceModel(view.resource(), parent)
{
    _initNode = true;
    _level = lvl;
    _isScanned = true;
    newview(view);

}

void CatalogModel::newview(const CatalogView &view){
    _view = view;
    mastercatalog()->addContainer(view.resource().url());
    _displayName = view.resource().name();
    if ( _displayName == sUNDEF)
        _displayName = view.resource().url().toString();
}

bool CatalogModel::isScanned() const
{
    return _isScanned;
}

bool CatalogModel::initNode() const {
    return _initNode;
}

int CatalogModel::level() const
{
    return _level;
}

QQmlListProperty<ResourceModel> CatalogModel::resources() {

    try{
        gatherItems();

        return  QQmlListProperty<ResourceModel>(this, _currentItems);
    }
    catch(const ErrorObject& err){

    }
    return  QQmlListProperty<ResourceModel>();
}

QQmlListProperty<IlwisObjectModel> CatalogModel::selectedData()
{
    return  QQmlListProperty<IlwisObjectModel>(this, _selectedObjects);
}

QQmlListProperty<CatalogMapItem> CatalogModel::mapItems()
{
   return  QQmlListProperty<CatalogMapItem>(this, _catalogMapItems);
}

void CatalogModel::makeParent(QObject *obj)
{
    setParent(obj);
}

void CatalogModel::filterChanged(const QString& objectType, bool state){
    if ( objectType == "all"){
        _filterState["rastercoverage"] = state;
        _filterState["featurecoverage"] = state;
        _filterState["table"] = state;
        _filterState["coordinatesystem"] = state;
        _filterState["georeference"] = state;
        _filterState["domain"] = state;
        _filterState["representation"] = state;
        _filterState["projection"] = state;
        _filterState["ellipsoid"] = state;

    }else
        _filterState[objectType] = state;
    QString filterString;
    for(auto iter : _filterState){
        if ( !iter.second){
            if ( filterString != "")
                filterString += " and ";
            filterString += QString("type") + "& '" + iter.first + "' =0";
        }
    }
    _refresh = true;
    _view.filter(filterString);
    contentChanged();
}

void CatalogModel::refresh(bool yesno)
{
    _refresh = yesno;
}

void CatalogModel::setSelectedObjects(const QString &objects)
{
    try {
    QStringList parts = objects.split("|");
    _selectedObjects.clear();
    for(auto objectid : parts){
        Resource resource = mastercatalog()->id2Resource(objectid.toULongLong());
        IlwisObjectModel *ioModel = new IlwisObjectModel(resource, this);
        if ( ioModel->isValid()){
            _selectedObjects.append(ioModel);
            emit selectionChanged();
        }else
            delete ioModel;
    }
    }catch(const ErrorObject& err){

    }
}

void CatalogModel::nameFilter(const QString &filter)
{
    _nameFilter = filter;
    _currentItems.clear();
    emit contentChanged();
}

QString CatalogModel::nameFilter() const
{
    return _nameFilter;
}

void CatalogModel::prepareMapItems(LayerManager *manager)
{
    try{
        if ( _catalogMapItems.size() == 0){
            kernel()->issues()->silent(true);
            for (auto iter  = _currentItems.begin(); iter != _currentItems.end(); ++iter){
                if(hasType((*iter)->type(), itCOVERAGE)){
                    Ilwis::ICoverage cov(((*iter)->resource()));
                    if ( cov.isValid() && cov->coordinateSystem().isValid())    {
                        if ( cov->coordinateSystem()->isLatLon() || cov->coordinateSystem()->canConvertToLatLon()){
                            _catalogMapItems.push_back(new CatalogMapItem(cov,manager->screenGrf(),this));
                        }
                    }
                }
            }
            kernel()->issues()->silent(false);
        }
    } catch (const Ilwis::ErrorObject& ){

    } catch (std::exception& ex){
        Ilwis::kernel()->issues()->log(ex.what());
    }
    kernel()->issues()->silent(false);
}

void CatalogModel::gatherItems() {
    if ( _currentItems.isEmpty() || _refresh) {
        if ( !_view.isValid())
            return;

        _view.prepare();

        _currentItems.clear();
        _refresh = false;

        std::vector<Resource> items = _view.items();
        for(const Resource& resource : items){
            if ( _nameFilter != ""){
                if ( resource.name().indexOf(_nameFilter) == -1){
                    if ( resource["longname"].toString().indexOf(_nameFilter) == -1)
                        continue;
                }
            }
            _currentItems.push_back(new ResourceModel(resource));

        }
    }
}

<|endoftext|>


<commit_before>/*
* C S O U N D   V S T
*
* A VST plugin version of Csound, with Python scripting.
*
* L I C E N S E
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
#ifndef MIDIFILE_H
#define MIDIFILE_H
#include "Platform.hpp"
#ifdef SWIG
%module CsoundAC
%{
#include <algorithm>
#include <utility>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
%}
%include "std_string.i"
%template(MidiEventVector) std::vector<csound::MidiEvent>;
%template(MidiByteVector) std::vector<unsigned char>;
#else
#include <algorithm>
#include <utility>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#endif

namespace csound
{
    typedef unsigned char csound_u_char;
        class MidiFile;

        class SILENCE_PUBLIC Chunk
        {
        public:
                int id;
                int chunkSize;
                int chunkSizePosition;
                int chunkStart;
                int chunkEnd;
                Chunk(const char *_id);
                virtual ~Chunk(void);
                virtual void read(std::istream &stream);
                virtual void write(std::ostream &stream);
                virtual void markChunkSize(std::ostream &stream);
                virtual void markChunkStart(std::ostream &stream);
                virtual void markChunkEnd(std::ostream &stream);
        };

        class SILENCE_PUBLIC MidiHeader : public Chunk
        {
        public:
                short type;
                short trackCount;
                short timeFormat;
                MidiHeader(void);
                virtual ~MidiHeader(void);
                virtual void clear(void);
                virtual void read(std::istream &stream);
                virtual void write(std::ostream &stream);
        };

        /**
        * This class is used to store ALL Midi messages.
        */
        class SILENCE_PUBLIC MidiEvent : public std::vector<csound_u_char>
        {
        public:
                int ticks;
                double time;
                MidiEvent(void);
                virtual ~MidiEvent(void);
                virtual void read(std::istream &stream, MidiFile &midiFile);
                virtual void write(std::ostream &stream, MidiFile &midiFile, int lastTick);
                virtual int getStatus(void);
                virtual int getStatusNybble(void);
                virtual int getChannelNybble(void);
                virtual int getKey(void);
                virtual int getVelocity(void);
                virtual int getMetaType(void);
                virtual unsigned char getMetaData(int i);
                virtual size_t getMetaSize(void);
                virtual unsigned char read(std::istream &stream);
                virtual bool isChannelVoiceMessage();
                virtual bool isNoteOn(void);
                virtual bool isNoteOff(void);
                virtual bool isMatchingNoteOff(MidiEvent &offEvent);
                friend bool operator < (const MidiEvent &a, MidiEvent &b);
        };

        class SILENCE_PUBLIC MidiTrack : public Chunk, public std::vector<MidiEvent>
        {
        public:
                MidiTrack(void);
                virtual ~MidiTrack(void);
                virtual void read(std::istream &stream, MidiFile &midiFile);
                virtual void write(std::ostream &stream, MidiFile &midiFile);
                virtual void sort(void);
        };

        class SILENCE_PUBLIC TempoMap : public std::map<int, double>
        {
        public:
                double getCurrentSecondsPerTick(int tick);
        };

        /**
        * Reads and writes format 0 and format 1 standard MIDI files.
        */
        class SILENCE_PUBLIC MidiFile
        {
        public:
                typedef enum {
                        CHANNEL_NOTE_OFF = 0x80,
                        CHANNEL_NOTE_ON = 0x90,
                        CHANNEL_KEY_PRESSURE = 0xa0,
                        CHANNEL_CONTROL_CHANGE = 0xb0,
                        CHANNEL_PROGRAM_CHANGE = 0xc0,
                        CHANNEL_AFTER_TOUCH = 0xd0,
                        CHANNEL_PITCH_BEND = 0xe0,
                        SYSTEM_EXCLUSIVE = 0xf0,
                        SYSTEM_MIDI_TIME_CODE = 0xf1,
                        SYSTEM_SONG_POSITION_POINTER = 0xf2,
                        SYSTEM_SONG_SELECT = 0xf3,
                        SYSTEM_TUNE_REQUEST = 0xf6,
                        SYSTEM_END_OF_EXCLUSIVE = 0xf7,
                        SYSTEM_TIMING_CLOCK = 0xf8,
                        SYSTEM_START = 0xfa,
                        SYSTEM_CONTINUE = 0xfb,
                        SYSTEM_STOP = 0xfc,
                        SYSTEM_ACTIVE_SENSING = 0xfe,
                        META_EVENT = 0xff
                } MidiEventTypes;
                typedef enum {
                        META_SEQUENCE_NUMBER = 0x00,
                        META_TEXT_EVENT = 0x01,
                        META_COPYRIGHT_NOTICE = 0x02,
                        META_SEQUENCE_NAME = 0x03,
                        META_INSTRUMENT_NAME = 0x04,
                        META_LYRIC = 0x05,
                        META_MARKER = 0x06,
                        META_CUE_POINT = 0x07,
                        META_CHANNEL_PREFIX = 0x20,
                        META_END_OF_TRACK = 0x2f,
                        META_SET_TEMPO = 0x51,
                        META_SMPTE_OFFSET = 0x54,
                        META_TIME_SIGNATURE = 0x58,
                        META_KEY_SIGNATURE = 0x59,
                        META_SEQUENCER_SPECIFIC = 0x74
                } MetaEventTypes;
                typedef enum {
                        CONTROLLER_MOD_WHEEL = 1,
                        CONTROLLER_BREATH = 2,
                        CONTROLLER_FOOT = 4,
                        CONTROLLER_BALANCE = 8,
                        CONTROLLER_PAN = 10,
                        CONTROLLER_EXPRESSION = 11,
                        /* 7 bit controllers */
                        CONTROLLER_DAMPER_PEDAL = 0x40,
                        CONTROLLER_PORTAMENTO = 0x41,
                        CONTROLLER_SOSTENUTO = 0x42,
                        CONTROLLER_SOFT_PEDAL = 0x43,
                        CONTROLLER_GENERAL_4 = 0x44,
                        CONTROLLER_HOLD_2 = 0x45,
                        CONTROLLER_7GENERAL_5 = 0x50,
                        CONTROLLER_GENERAL_6 = 0x51,
                        CONTROLLER_GENERAL_7 = 0x52,
                        CONTROLLER_GENERAL_8 = 0x53,
                        CONTROLLER_TREMOLO_DEPTH = 0x5c,
                        CONTROLLER_CHORUS_DEPTH = 0x5d,
                        CONTROLLER_DETUNE = 0x5e,
                        CONTROLLER_PHASER_DEPTH = 0x5f,
                        /* parameter values */
                        CONTROLLER_DATA_INC = 0x60,
                        CONTROLLER_DATA_DEC = 0x61,
                        /* parameter selection */
                        CONTROLLER_NON_REG_LSB = 0x62,
                        CONTROLLER_NON_REG_MSB = 0x63,
                        CONTROLLER_REG_LSB = 0x64,
                        CONTROLLER_REG_MSG = 0x65,
                        CONTROLLER_CONTINUOUS_AFTERTOUCH = 128
                } MidiControllers;
                static int readVariableLength(std::istream &stream);
                static void writeVariableLength(std::ostream &stream, int value);
                static int toInt(int c1, int c2, int c3, int c4);
                static short toShort(int c1, int c2);
                static int readInt(std::istream &stream);
                static void writeInt(std::ostream &stream, int value);
                static short readShort(std::istream &stream);
                static void writeShort(std::ostream &stream, short value);
                static int chunkName(int a, int b, int c, int d);
                void computeTimes(void);
                int currentTick;
                double currentTime;
                double currentSecondsPerTick;
                double microsecondsPerQuarterNote;
                unsigned char lastStatus;
                MidiHeader midiHeader;
                TempoMap tempoMap;
                std::vector<MidiTrack> midiTracks;
                MidiFile(void);
                virtual ~MidiFile(void);
                virtual void clear(void);
                virtual void read(std::istream &stream);
                virtual void write(std::ostream &stream);
                virtual void load(std::string filename);
                virtual void save(std::string filename);
                virtual void dump(std::ostream &stream);
                virtual void sort(void);
        };

        bool SILENCE_PUBLIC operator < (const MidiEvent &a, MidiEvent &b);
}
#endif
<commit_msg>Consistent declaration of operator <.<commit_after>/*
 * C S O U N D   V S T
 *
 * A VST plugin version of Csound, with Python scripting.
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#ifndef MIDIFILE_H
#define MIDIFILE_H
#include "Platform.hpp"
#ifdef SWIG
%module CsoundAC
%{
#include <algorithm>
#include <utility>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
  %}
%include "std_string.i"
%template(MidiEventVector) std::vector<csound::MidiEvent>;
%template(MidiByteVector) std::vector<unsigned char>;
#else
#include <algorithm>
#include <utility>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#endif

namespace csound
{
  typedef unsigned char csound_u_char;
  class MidiFile;

  class SILENCE_PUBLIC Chunk
  {
  public:
    int id;
    int chunkSize;
    int chunkSizePosition;
    int chunkStart;
    int chunkEnd;
    Chunk(const char *_id);
    virtual ~Chunk(void);
    virtual void read(std::istream &stream);
    virtual void write(std::ostream &stream);
    virtual void markChunkSize(std::ostream &stream);
    virtual void markChunkStart(std::ostream &stream);
    virtual void markChunkEnd(std::ostream &stream);
  };

  class SILENCE_PUBLIC MidiHeader : public Chunk
  {
  public:
    short type;
    short trackCount;
    short timeFormat;
    MidiHeader(void);
    virtual ~MidiHeader(void);
    virtual void clear(void);
    virtual void read(std::istream &stream);
    virtual void write(std::ostream &stream);
  };

  /**
   * This class is used to store ALL Midi messages.
   */
  class SILENCE_PUBLIC MidiEvent : public std::vector<csound_u_char>
  {
  public:
    int ticks;
    double time;
    MidiEvent(void);
    virtual ~MidiEvent(void);
    virtual void read(std::istream &stream, MidiFile &midiFile);
    virtual void write(std::ostream &stream, MidiFile &midiFile, int lastTick);
    virtual int getStatus(void);
    virtual int getStatusNybble(void);
    virtual int getChannelNybble(void);
    virtual int getKey(void);
    virtual int getVelocity(void);
    virtual int getMetaType(void);
    virtual unsigned char getMetaData(int i);
    virtual size_t getMetaSize(void);
    virtual unsigned char read(std::istream &stream);
    virtual bool isChannelVoiceMessage();
    virtual bool isNoteOn(void);
    virtual bool isNoteOff(void);
    virtual bool isMatchingNoteOff(MidiEvent &offEvent);
    friend SILENCE_PUBLIC bool operator < (const MidiEvent &a, MidiEvent &b);
  };

  class SILENCE_PUBLIC MidiTrack : public Chunk, public std::vector<MidiEvent>
  {
  public:
    MidiTrack(void);
    virtual ~MidiTrack(void);
    virtual void read(std::istream &stream, MidiFile &midiFile);
    virtual void write(std::ostream &stream, MidiFile &midiFile);
    virtual void sort(void);
  };

  class SILENCE_PUBLIC TempoMap : public std::map<int, double>
  {
  public:
    double getCurrentSecondsPerTick(int tick);
  };

  /**
   * Reads and writes format 0 and format 1 standard MIDI files.
   */
  class SILENCE_PUBLIC MidiFile
  {
  public:
    typedef enum {
      CHANNEL_NOTE_OFF = 0x80,
      CHANNEL_NOTE_ON = 0x90,
      CHANNEL_KEY_PRESSURE = 0xa0,
      CHANNEL_CONTROL_CHANGE = 0xb0,
      CHANNEL_PROGRAM_CHANGE = 0xc0,
      CHANNEL_AFTER_TOUCH = 0xd0,
      CHANNEL_PITCH_BEND = 0xe0,
      SYSTEM_EXCLUSIVE = 0xf0,
      SYSTEM_MIDI_TIME_CODE = 0xf1,
      SYSTEM_SONG_POSITION_POINTER = 0xf2,
      SYSTEM_SONG_SELECT = 0xf3,
      SYSTEM_TUNE_REQUEST = 0xf6,
      SYSTEM_END_OF_EXCLUSIVE = 0xf7,
      SYSTEM_TIMING_CLOCK = 0xf8,
      SYSTEM_START = 0xfa,
      SYSTEM_CONTINUE = 0xfb,
      SYSTEM_STOP = 0xfc,
      SYSTEM_ACTIVE_SENSING = 0xfe,
      META_EVENT = 0xff
    } MidiEventTypes;
    typedef enum {
      META_SEQUENCE_NUMBER = 0x00,
      META_TEXT_EVENT = 0x01,
      META_COPYRIGHT_NOTICE = 0x02,
      META_SEQUENCE_NAME = 0x03,
      META_INSTRUMENT_NAME = 0x04,
      META_LYRIC = 0x05,
      META_MARKER = 0x06,
      META_CUE_POINT = 0x07,
      META_CHANNEL_PREFIX = 0x20,
      META_END_OF_TRACK = 0x2f,
      META_SET_TEMPO = 0x51,
      META_SMPTE_OFFSET = 0x54,
      META_TIME_SIGNATURE = 0x58,
      META_KEY_SIGNATURE = 0x59,
      META_SEQUENCER_SPECIFIC = 0x74
    } MetaEventTypes;
    typedef enum {
      CONTROLLER_MOD_WHEEL = 1,
      CONTROLLER_BREATH = 2,
      CONTROLLER_FOOT = 4,
      CONTROLLER_BALANCE = 8,
      CONTROLLER_PAN = 10,
      CONTROLLER_EXPRESSION = 11,
      /* 7 bit controllers */
      CONTROLLER_DAMPER_PEDAL = 0x40,
      CONTROLLER_PORTAMENTO = 0x41,
      CONTROLLER_SOSTENUTO = 0x42,
      CONTROLLER_SOFT_PEDAL = 0x43,
      CONTROLLER_GENERAL_4 = 0x44,
      CONTROLLER_HOLD_2 = 0x45,
      CONTROLLER_7GENERAL_5 = 0x50,
      CONTROLLER_GENERAL_6 = 0x51,
      CONTROLLER_GENERAL_7 = 0x52,
      CONTROLLER_GENERAL_8 = 0x53,
      CONTROLLER_TREMOLO_DEPTH = 0x5c,
      CONTROLLER_CHORUS_DEPTH = 0x5d,
      CONTROLLER_DETUNE = 0x5e,
      CONTROLLER_PHASER_DEPTH = 0x5f,
      /* parameter values */
      CONTROLLER_DATA_INC = 0x60,
      CONTROLLER_DATA_DEC = 0x61,
      /* parameter selection */
      CONTROLLER_NON_REG_LSB = 0x62,
      CONTROLLER_NON_REG_MSB = 0x63,
      CONTROLLER_REG_LSB = 0x64,
      CONTROLLER_REG_MSG = 0x65,
      CONTROLLER_CONTINUOUS_AFTERTOUCH = 128
    } MidiControllers;
    static int readVariableLength(std::istream &stream);
    static void writeVariableLength(std::ostream &stream, int value);
    static int toInt(int c1, int c2, int c3, int c4);
    static short toShort(int c1, int c2);
    static int readInt(std::istream &stream);
    static void writeInt(std::ostream &stream, int value);
    static short readShort(std::istream &stream);
    static void writeShort(std::ostream &stream, short value);
    static int chunkName(int a, int b, int c, int d);
    void computeTimes(void);
    int currentTick;
    double currentTime;
    double currentSecondsPerTick;
    double microsecondsPerQuarterNote;
    unsigned char lastStatus;
    MidiHeader midiHeader;
    TempoMap tempoMap;
    std::vector<MidiTrack> midiTracks;
    MidiFile(void);
    virtual ~MidiFile(void);
    virtual void clear(void);
    virtual void read(std::istream &stream);
    virtual void write(std::ostream &stream);
    virtual void load(std::string filename);
    virtual void save(std::string filename);
    virtual void dump(std::ostream &stream);
    virtual void sort(void);
  };

  bool SILENCE_PUBLIC operator < (const MidiEvent &a, MidiEvent &b);
}
#endif
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkImageClippingExtents.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to David G Gobbi who developed this class.

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 AUTHORS 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.

=========================================================================*/

#include <math.h>
#include "vtkImageClippingExtents.h"
#include "vtkImplicitFunction.h"
#include "vtkObjectFactory.h"

//----------------------------------------------------------------------------
vtkImageClippingExtents* vtkImageClippingExtents::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageClippingExtents");
  if(ret)
    {
    return (vtkImageClippingExtents*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkImageClippingExtents;
}

//----------------------------------------------------------------------------
vtkImageClippingExtents::vtkImageClippingExtents()
{
  this->ClippingObject = NULL;

  this->ClippingExtent[0] =  0;
  this->ClippingExtent[1] = -1;
  this->ClippingExtent[2] =  0;
  this->ClippingExtent[3] = -1;
  this->ClippingExtent[4] =  0;
  this->ClippingExtent[5] = -1;

  this->ClippingSpacing[0] = 1;
  this->ClippingSpacing[1] = 1;
  this->ClippingSpacing[2] = 1;

  this->ClippingOrigin[0] = 0;
  this->ClippingOrigin[1] = 0;
  this->ClippingOrigin[2] = 0;

  this->ClippingLists = NULL;
  this->ClippingListLengths = NULL;
}

//----------------------------------------------------------------------------
vtkImageClippingExtents::~vtkImageClippingExtents()
{
  if (this->ClippingObject)
    {
    this->ClippingObject->Delete();
    }

  if (this->ClippingLists)
    {
    int n = ((this->ClippingExtent[3] - this->ClippingExtent[2] + 1) *
             (this->ClippingExtent[5] - this->ClippingExtent[4] + 1));
    for (int i = 0; i < n; i++)
      {
      delete [] this->ClippingLists[i];
      }
    delete [] this->ClippingLists;
    }
  if (this->ClippingListLengths)
    {
    delete [] this->ClippingListLengths;
    }
}

//----------------------------------------------------------------------------
void vtkImageClippingExtents::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkObject::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
void vtkImageClippingExtents::BuildExtents(vtkImageData *output)
{
  // check to see whether the output information has changed
  int informationChanged = 0;
  int *extent = output->GetWholeExtent();
  float *spacing = output->GetSpacing();
  float *origin = output->GetOrigin();

  for (int j = 0; j < 3; j++)
    {
    if (extent[2*j] != this->ClippingExtent[2*j] ||
        extent[2*j+1] != this->ClippingExtent[2*j+1] ||
        spacing[j] != this->ClippingSpacing[j] ||
        origin[j] != this->ClippingOrigin[j])
      {
      informationChanged = 1;
      break;
      }
    }

  // check to see whether the clipping object has changed
  int clippingChanged = 0;
  if (this->ClippingObject->IsA("vtkDataObject"))
    {
    ((vtkDataObject *)this->ClippingObject)->Update();
    }

  if (this->GetMTime() > this->BuildTime.GetMTime() ||
      (this->ClippingObject &&
       this->ClippingObject->GetMTime() > this->BuildTime.GetMTime()))
    {
    clippingChanged = 1;
    }

  if (!(clippingChanged || informationChanged))
    {
    return;
    }

  // delete the old clipping information
  if (this->ClippingLists)
    {
    int n = ((this->ClippingExtent[3] - this->ClippingExtent[2] + 1) *
             (this->ClippingExtent[5] - this->ClippingExtent[4] + 1));
    for (int i = 0; i < n; i++)
      {
      delete [] this->ClippingLists[i];
      }
    delete [] this->ClippingLists;
    this->ClippingLists = NULL;
    }
  if (this->ClippingListLengths)
    {
    delete [] this->ClippingListLengths;
    this->ClippingListLengths = NULL;
    }

  // copy WholeExtent to ClippingExtent
  output->GetWholeExtent(this->ClippingExtent);
  output->GetSpacing(this->ClippingSpacing);
  output->GetOrigin(this->ClippingOrigin);

  if (!this->ClippingObject)
    {
    return;
    }

  this->PrepareForThreadedBuildExtents();
  // no multithreading yet...
  this->ThreadedBuildExtents(extent, 0);

  this->Modified();
  this->BuildTime.Modified();
}

void vtkImageClippingExtents::PrepareForThreadedBuildExtents()
{
}

void vtkImageClippingExtents::ThreadedBuildExtents(int extent[6],
                                                   int vtkNotUsed(ThreadId))
{
  float *spacing = this->ClippingSpacing;
  float *origin = this->ClippingOrigin;
  vtkObject *clipper = this->ClippingObject;

  if (clipper->IsA("vtkImplicitFunction"))
    {
    // allocate new clipping information
    int n = ((extent[3] - extent[2] + 1) *
             (extent[5] - extent[4] + 1));

    this->ClippingLists = new int *[n];
    this->ClippingListLengths = new int[n];

    // set up the clipping extents from an implicit function by brute force
    // (evaluate the function at each and every voxel)
    vtkImplicitFunction *function = (vtkImplicitFunction *)clipper;

    float point[3];
    int *clippingListLength = this->ClippingListLengths;
    int **clippingList = this->ClippingLists;

    for (int idZ = extent[4]; idZ <= extent[5]; idZ++)
      {
      point[2] = idZ*spacing[2] + origin[2];

      for (int idY = extent[2]; idY <= extent[3]; idY++)
        {
        point[1] = idY*spacing[1] + origin[1];
        int clistlen = 0;
        int clistmaxlen = 2;
        int *clist = new int[clistmaxlen];
        int state = 1; // inside or outside, start outside

        for (int idX = extent[0]; idX <= extent[1]; idX++)
          {
          point[0] = idX*spacing[0] + origin[0];
          int newstate = 1;
          if (function->FunctionValue(point) < 0)
            {
            newstate = -1;
            }
          if (newstate != state)
            {
            if (clistlen >= clistmaxlen)
              { // need to allocate more space
              clistmaxlen *= 2;
              int *newclist = new int[clistmaxlen];
              for (int k = 0; k < clistlen; k++)
                {
                newclist[k] = clist[k];
                }
              delete [] clist;
              clist = newclist;
              }

            clist[clistlen++] = idX;
            }

          state = newstate;
          } // for idX

        *clippingListLength++ = clistlen;
        *clippingList++ = clist;
        } // for idY

      } // for idZ
    }
  else
    {
    vtkErrorMacro("Update: unrecognized clipping object type " <<
                  clipper->GetClassName());
    }
}

//----------------------------------------------------------------------------
// Given the output x extent [rmin,rmax] and the current y, z indices,
// return the sub extents [r1,r2] for which transformation/interpolation
// are to be done.  The variable 'iter' should be initialized to zero
// before the first call.  The return value is zero if there are no
// extents remaining.
int vtkImageClippingExtents::GetNextExtent(int &r1, int &r2,
                                           int rmin, int rmax,
                                           int yIdx, int zIdx, int &iter)
{
  int yExt = this->ClippingExtent[3] - this->ClippingExtent[2] + 1;
  int zExt = this->ClippingExtent[5] - this->ClippingExtent[4] + 1;
  yIdx -= this->ClippingExtent[2];
  zIdx -= this->ClippingExtent[4];

  // initialize r1, r2 to defaults
  r1 = rmax + 1;
  r2 = rmax;

  if (yIdx < 0 || yIdx >= yExt || zIdx < 0 || zIdx >= zExt)
    { // out-of-bounds in y or z, use null extent
    return 0;
    }

  // if no clipping object is set, just use ClippingExtent
  if (this->ClippingLists == NULL)
    {
    if (iter++ == 0)
      {
      r1 = this->ClippingExtent[0];
      r2 = this->ClippingExtent[1];
      if (r1 < rmin)
        {
        r1 = rmin;
        }
      if (r1 > rmax)
        {
        r1 = rmax + 1;
        }
      if (r2 > rmax)
        {
        r2 = rmax;
        }
      return (r2 >= r1);
      }
    else
      {
      return 0;
      }
    }

  // get the ClippingList and ClippingListLength for this yIdx,zIdx
  int incr = zIdx*yExt + yIdx;
  int *clist = this->ClippingLists[incr];
  int clistlen = this->ClippingListLengths[incr];

  if (iter == 0)
    {
    int state = 1; // start outside
    for ( ; iter < clistlen; iter++)
      {
      r1 = rmin;
      state = -state;
      if (clist[iter] >= rmin)
        {
        if (state < 0)
          {
          r1 = clist[iter++];
          }
        break;
        }
      }
    }
  else
    {
    if (iter >= clistlen)
      {
      return 0;
      }
    r1 = clist[iter++];
    }

  if (r1 > rmax)
    {
    r1 = rmax + 1;
    return 0;
    }

  if (iter >= clistlen)
    {
    return 1;
    }

  r2 = clist[iter++] - 1;

  if (r2 > rmax)
    {
    r2 = rmax;
    }

  return 1;
}

<commit_msg>ERR: logistical error in GetNextExtent<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageClippingExtents.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to David G Gobbi who developed this class.

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 AUTHORS 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.

=========================================================================*/

#include <math.h>
#include "vtkImageClippingExtents.h"
#include "vtkImplicitFunction.h"
#include "vtkObjectFactory.h"

//----------------------------------------------------------------------------
vtkImageClippingExtents* vtkImageClippingExtents::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageClippingExtents");
  if(ret)
    {
    return (vtkImageClippingExtents*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkImageClippingExtents;
}

//----------------------------------------------------------------------------
vtkImageClippingExtents::vtkImageClippingExtents()
{
  this->ClippingObject = NULL;

  this->ClippingExtent[0] =  0;
  this->ClippingExtent[1] = -1;
  this->ClippingExtent[2] =  0;
  this->ClippingExtent[3] = -1;
  this->ClippingExtent[4] =  0;
  this->ClippingExtent[5] = -1;

  this->ClippingSpacing[0] = 1;
  this->ClippingSpacing[1] = 1;
  this->ClippingSpacing[2] = 1;

  this->ClippingOrigin[0] = 0;
  this->ClippingOrigin[1] = 0;
  this->ClippingOrigin[2] = 0;

  this->ClippingLists = NULL;
  this->ClippingListLengths = NULL;
}

//----------------------------------------------------------------------------
vtkImageClippingExtents::~vtkImageClippingExtents()
{
  if (this->ClippingObject)
    {
    this->ClippingObject->Delete();
    }

  if (this->ClippingLists)
    {
    int n = ((this->ClippingExtent[3] - this->ClippingExtent[2] + 1) *
             (this->ClippingExtent[5] - this->ClippingExtent[4] + 1));
    for (int i = 0; i < n; i++)
      {
      delete [] this->ClippingLists[i];
      }
    delete [] this->ClippingLists;
    }
  if (this->ClippingListLengths)
    {
    delete [] this->ClippingListLengths;
    }
}

//----------------------------------------------------------------------------
void vtkImageClippingExtents::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkObject::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
void vtkImageClippingExtents::BuildExtents(vtkImageData *output)
{
  // check to see whether the output information has changed
  int informationChanged = 0;
  int *extent = output->GetWholeExtent();
  float *spacing = output->GetSpacing();
  float *origin = output->GetOrigin();

  for (int j = 0; j < 3; j++)
    {
    if (extent[2*j] != this->ClippingExtent[2*j] ||
        extent[2*j+1] != this->ClippingExtent[2*j+1] ||
        spacing[j] != this->ClippingSpacing[j] ||
        origin[j] != this->ClippingOrigin[j])
      {
      informationChanged = 1;
      break;
      }
    }

  // check to see whether the clipping object has changed
  int clippingChanged = 0;
  if (this->ClippingObject->IsA("vtkDataObject"))
    {
    ((vtkDataObject *)this->ClippingObject)->Update();
    }

  if (this->GetMTime() > this->BuildTime.GetMTime() ||
      (this->ClippingObject &&
       this->ClippingObject->GetMTime() > this->BuildTime.GetMTime()))
    {
    clippingChanged = 1;
    }

  if (!(clippingChanged || informationChanged))
    {
    return;
    }

  // delete the old clipping information
  if (this->ClippingLists)
    {
    int n = ((this->ClippingExtent[3] - this->ClippingExtent[2] + 1) *
             (this->ClippingExtent[5] - this->ClippingExtent[4] + 1));
    for (int i = 0; i < n; i++)
      {
      delete [] this->ClippingLists[i];
      }
    delete [] this->ClippingLists;
    this->ClippingLists = NULL;
    }
  if (this->ClippingListLengths)
    {
    delete [] this->ClippingListLengths;
    this->ClippingListLengths = NULL;
    }

  // copy WholeExtent to ClippingExtent
  output->GetWholeExtent(this->ClippingExtent);
  output->GetSpacing(this->ClippingSpacing);
  output->GetOrigin(this->ClippingOrigin);

  if (!this->ClippingObject)
    {
    return;
    }

  this->PrepareForThreadedBuildExtents();
  // no multithreading yet...
  this->ThreadedBuildExtents(extent, 0);

  this->Modified();
  this->BuildTime.Modified();
}

void vtkImageClippingExtents::PrepareForThreadedBuildExtents()
{
}

void vtkImageClippingExtents::ThreadedBuildExtents(int extent[6],
                                                   int vtkNotUsed(ThreadId))
{
  float *spacing = this->ClippingSpacing;
  float *origin = this->ClippingOrigin;
  vtkObject *clipper = this->ClippingObject;

  if (clipper->IsA("vtkImplicitFunction"))
    {
    // allocate new clipping information
    int n = ((extent[3] - extent[2] + 1) *
             (extent[5] - extent[4] + 1));

    this->ClippingLists = new int *[n];
    this->ClippingListLengths = new int[n];

    // set up the clipping extents from an implicit function by brute force
    // (evaluate the function at each and every voxel)
    vtkImplicitFunction *function = (vtkImplicitFunction *)clipper;

    float point[3];
    int *clippingListLength = this->ClippingListLengths;
    int **clippingList = this->ClippingLists;

    for (int idZ = extent[4]; idZ <= extent[5]; idZ++)
      {
      point[2] = idZ*spacing[2] + origin[2];

      for (int idY = extent[2]; idY <= extent[3]; idY++)
        {
        point[1] = idY*spacing[1] + origin[1];
        int clistlen = 0;
        int clistmaxlen = 2;
        int *clist = new int[clistmaxlen];
        int state = 1; // inside or outside, start outside

        for (int idX = extent[0]; idX <= extent[1]; idX++)
          {
          point[0] = idX*spacing[0] + origin[0];
          int newstate = 1;
          if (function->FunctionValue(point) < 0)
            {
            newstate = -1;
            }
          if (newstate != state)
            {
            if (clistlen >= clistmaxlen)
              { // need to allocate more space
              clistmaxlen *= 2;
              int *newclist = new int[clistmaxlen];
              for (int k = 0; k < clistlen; k++)
                {
                newclist[k] = clist[k];
                }
              delete [] clist;
              clist = newclist;
              }

            clist[clistlen++] = idX;
            }

          state = newstate;
          } // for idX

        *clippingListLength++ = clistlen;
        *clippingList++ = clist;
        } // for idY

      } // for idZ
    }
  else
    {
    vtkErrorMacro("Update: unrecognized clipping object type " <<
                  clipper->GetClassName());
    }
}

//----------------------------------------------------------------------------
// Given the output x extent [rmin,rmax] and the current y, z indices,
// return the sub extents [r1,r2] for which transformation/interpolation
// are to be done.  The variable 'iter' should be initialized to zero
// before the first call.  The return value is zero if there are no
// extents remaining.
int vtkImageClippingExtents::GetNextExtent(int &r1, int &r2,
                                           int rmin, int rmax,
                                           int yIdx, int zIdx, int &iter)
{
  int yExt = this->ClippingExtent[3] - this->ClippingExtent[2] + 1;
  int zExt = this->ClippingExtent[5] - this->ClippingExtent[4] + 1;
  yIdx -= this->ClippingExtent[2];
  zIdx -= this->ClippingExtent[4];

  // initialize r1, r2 to defaults
  r1 = rmax + 1;
  r2 = rmax;

  if (yIdx < 0 || yIdx >= yExt || zIdx < 0 || zIdx >= zExt)
    { // out-of-bounds in y or z, use null extent
    return 0;
    }

  // if no clipping object is set, just use ClippingExtent
  if (this->ClippingLists == NULL)
    {
    if (iter++ == 0)
      {
      r1 = this->ClippingExtent[0];
      r2 = this->ClippingExtent[1];
      if (r1 < rmin)
        {
        r1 = rmin;
        }
      if (r1 > rmax)
        {
        r1 = rmax + 1;
        }
      if (r2 > rmax)
        {
        r2 = rmax;
        }
      return (r2 >= r1);
      }
    else
      {
      return 0;
      }
    }

  // get the ClippingList and ClippingListLength for this yIdx,zIdx
  int incr = zIdx*yExt + yIdx;
  int *clist = this->ClippingLists[incr];
  int clistlen = this->ClippingListLengths[incr];

  if (iter == 0)
    {
    int state = 1; // start outside
    r1 = VTK_INT_MIN;
    for ( ; iter < clistlen; iter++)
      {
      if (clist[iter] >= rmin)
        {
        if (state > 0)
          {
          r1 = clist[iter++];
          }
        break;
        }
      state = -state;
      }
    if (r1 == VTK_INT_MIN)
      {
      r1 = rmin;
      if (state > 0)
	{
	r1 = rmax + 1;
	}
      }
    }
  else
    {
    if (iter >= clistlen)
      {
      return 0;
      }
    r1 = clist[iter++];
    }

  if (r1 > rmax)
    {
    r1 = rmax + 1;
    return 0;
    }

  if (iter >= clistlen)
    {
    return 1;
    }

  r2 = clist[iter++] - 1;

  if (r2 > rmax)
    {
    r2 = rmax;
    }

  return 1;
}

<|endoftext|>


<commit_before>// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Mathematics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/StringStream.hpp>
#include <Nazara/Math/Basic.hpp>
#include <Nazara/Math/Config.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <cstring>
#include <Nazara/Core/Debug.hpp>

#define F(a) static_cast<T>(a)

template<typename T>
NzEulerAngles<T>::NzEulerAngles(T P, T Y, T R)
{
	Set(P, Y, R);
}

template<typename T>
NzEulerAngles<T>::NzEulerAngles(const T angles[3])
{
	Set(angles);
}

template<typename T>
NzEulerAngles<T>::NzEulerAngles(const NzQuaternion<T>& quat)
{
	Set(quat);
}

template<typename T>
template<typename U>
NzEulerAngles<T>::NzEulerAngles(const NzEulerAngles<U>& angles)
{
	Set(angles);
}

template<typename T>
void NzEulerAngles<T>::MakeZero()
{
	Set(F(0.0), F(0.0), F(0.0));
}

template<typename T>
void NzEulerAngles<T>::Normalize()
{
	pitch = NzNormalizeAngle(pitch);
	yaw = NzNormalizeAngle(yaw);
	roll = NzNormalizeAngle(roll);
}

template<typename T>
void NzEulerAngles<T>::Set(T P, T Y, T R)
{
	pitch = P;
	yaw = Y;
	roll = R;
}

template<typename T>
void NzEulerAngles<T>::Set(const T angles[3])
{
	pitch = angles[0];
	yaw = angles[1];
	roll = angles[2];
}

template<typename T>
void NzEulerAngles<T>::Set(const NzEulerAngles& angles)
{
	std::memcpy(this, &angles, sizeof(NzEulerAngles));
}

template<typename T>
void NzEulerAngles<T>::Set(const NzQuaternion<T>& quat)
{
	Set(quat.ToEulerAngles());
}

template<typename T>
template<typename U>
void NzEulerAngles<T>::Set(const NzEulerAngles<U>& angles)
{
	pitch = static_cast<T>(angles.pitch);
	yaw = static_cast<T>(angles.yaw);
	roll = static_cast<T>(angles.roll);
}

template<typename T>
NzQuaternion<T> NzEulerAngles<T>::ToQuaternion() const
{
	NzQuaternion<T> rotX(pitch, NzVector3<T>::UnitX());
	NzQuaternion<T> rotY(yaw, NzVector3<T>::UnitY());
	NzQuaternion<T> rotZ(roll, NzVector3<T>::UnitZ());

	return rotY * rotX * rotZ;
}

template<typename T>
NzString NzEulerAngles<T>::ToString() const
{
	NzStringStream ss;

	return ss << "EulerAngles(" << pitch << ", " << yaw << ", " << roll << ')';
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::operator+(const NzEulerAngles& angles) const
{
	return NzEulerAngles(pitch + angles.pitch,
						 yaw + angles.yaw,
						 roll + angles.roll);
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::operator-(const NzEulerAngles& angles) const
{
	return NzEulerAngles(pitch - angles.pitch,
						 yaw - angles.yaw,
						 roll - angles.roll);
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::operator+=(const NzEulerAngles& angles)
{
	pitch += angles.pitch;
	yaw += angles.yaw;
	roll += angles.roll;

	return *this;
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::operator-=(const NzEulerAngles& angles)
{
	pitch -= angles.pitch;
	yaw -= angles.yaw;
	roll -= angles.roll;

	return *this;
}

template<typename T>
bool NzEulerAngles<T>::operator==(const NzEulerAngles& angles) const
{
	return NzNumberEquals(pitch, angles.pitch) &&
		   NzNumberEquals(yaw, angles.yaw) &&
		   NzNumberEquals(roll, angles.roll);
}

template<typename T>
bool NzEulerAngles<T>::operator!=(const NzEulerAngles& angles) const
{
	return !operator==(angles);
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::Zero()
{
	NzEulerAngles angles;
	angles.MakeZero();

	return angles;
}

template<typename T>
std::ostream& operator<<(std::ostream& out, const NzEulerAngles<T>& angles)
{
	return out << angles.ToString();
}

#undef F

#include <Nazara/Core/DebugOff.hpp>
<commit_msg>Fixed spaces<commit_after>// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Mathematics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/StringStream.hpp>
#include <Nazara/Math/Basic.hpp>
#include <Nazara/Math/Config.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <cstring>
#include <Nazara/Core/Debug.hpp>

#define F(a) static_cast<T>(a)

template<typename T>
NzEulerAngles<T>::NzEulerAngles(T P, T Y, T R)
{
	Set(P, Y, R);
}

template<typename T>
NzEulerAngles<T>::NzEulerAngles(const T angles[3])
{
	Set(angles);
}

template<typename T>
NzEulerAngles<T>::NzEulerAngles(const NzQuaternion<T>& quat)
{
	Set(quat);
}

template<typename T>
template<typename U>
NzEulerAngles<T>::NzEulerAngles(const NzEulerAngles<U>& angles)
{
	Set(angles);
}

template<typename T>
void NzEulerAngles<T>::MakeZero()
{
	Set(F(0.0), F(0.0), F(0.0));
}

template<typename T>
void NzEulerAngles<T>::Normalize()
{
	pitch = NzNormalizeAngle(pitch);
	yaw = NzNormalizeAngle(yaw);
	roll = NzNormalizeAngle(roll);
}

template<typename T>
void NzEulerAngles<T>::Set(T P, T Y, T R)
{
	pitch = P;
	yaw = Y;
	roll = R;
}

template<typename T>
void NzEulerAngles<T>::Set(const T angles[3])
{
	pitch = angles[0];
	yaw = angles[1];
	roll = angles[2];
}

template<typename T>
void NzEulerAngles<T>::Set(const NzEulerAngles& angles)
{
	std::memcpy(this, &angles, sizeof(NzEulerAngles));
}

template<typename T>
void NzEulerAngles<T>::Set(const NzQuaternion<T>& quat)
{
	Set(quat.ToEulerAngles());
}

template<typename T>
template<typename U>
void NzEulerAngles<T>::Set(const NzEulerAngles<U>& angles)
{
	pitch = static_cast<T>(angles.pitch);
	yaw = static_cast<T>(angles.yaw);
	roll = static_cast<T>(angles.roll);
}

template<typename T>
NzQuaternion<T> NzEulerAngles<T>::ToQuaternion() const
{
	NzQuaternion<T> rotX(pitch, NzVector3<T>::UnitX());
	NzQuaternion<T> rotY(yaw, NzVector3<T>::UnitY());
	NzQuaternion<T> rotZ(roll, NzVector3<T>::UnitZ());

	return rotY * rotX * rotZ;
}

template<typename T>
NzString NzEulerAngles<T>::ToString() const
{
	NzStringStream ss;

	return ss << "EulerAngles(" << pitch << ", " << yaw << ", " << roll << ')';
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::operator+(const NzEulerAngles& angles) const
{
	return NzEulerAngles(pitch + angles.pitch,
	                     yaw + angles.yaw,
	                     roll + angles.roll);
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::operator-(const NzEulerAngles& angles) const
{
	return NzEulerAngles(pitch - angles.pitch,
	                     yaw - angles.yaw,
	                     roll - angles.roll);
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::operator+=(const NzEulerAngles& angles)
{
	pitch += angles.pitch;
	yaw += angles.yaw;
	roll += angles.roll;

	return *this;
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::operator-=(const NzEulerAngles& angles)
{
	pitch -= angles.pitch;
	yaw -= angles.yaw;
	roll -= angles.roll;

	return *this;
}

template<typename T>
bool NzEulerAngles<T>::operator==(const NzEulerAngles& angles) const
{
	return NzNumberEquals(pitch, angles.pitch) &&
		   NzNumberEquals(yaw, angles.yaw) &&
		   NzNumberEquals(roll, angles.roll);
}

template<typename T>
bool NzEulerAngles<T>::operator!=(const NzEulerAngles& angles) const
{
	return !operator==(angles);
}

template<typename T>
NzEulerAngles<T> NzEulerAngles<T>::Zero()
{
	NzEulerAngles angles;
	angles.MakeZero();

	return angles;
}

template<typename T>
std::ostream& operator<<(std::ostream& out, const NzEulerAngles<T>& angles)
{
	return out << angles.ToString();
}

#undef F

#include <Nazara/Core/DebugOff.hpp>
<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2014
Raffaello D. Di Napoli

This file is part of Abaclade.

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

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

You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#ifndef _ABACLADE_PERF_STOPWATCH_HXX
#define _ABACLADE_PERF_STOPWATCH_HXX

#ifndef _ABACLADE_HXX
   #error "Please #include <abaclade.hxx> before this file"
#endif
#ifdef ABC_CXX_PRAGMA_ONCE
   #pragma once
#endif

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::perf::stopwatch

namespace abc {
namespace perf {

//! Base class for test cases.
class ABACLADE_TESTING_SYM stopwatch {
public:
   //! Integer type used to measure durations.
   typedef std::uint64_t duration_type;

public:
   stopwatch();

   ~stopwatch();

   duration_type duration() const {
      return m_iTotalDuration;
   }

   void start();

   duration_type stop();

protected:
   /*! Start time of the current timed session. Large enough to accommodate the real type, defined
   in stopwatch.cxx. */
   std::max_align_t m_abStartTime[ABC_ALIGNED_SIZE(8)];
   //! Total measured time duration, in nanoseconds. Precision is not guaranteed on all platforms.
   duration_type m_iTotalDuration;
};

} //namespace perf
} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend – specialization for abc::perf::stopwatch

namespace abc {

template <>
class to_str_backend<perf::stopwatch> : public to_str_backend<perf::stopwatch::duration_type> {
public:
   /*! Writes a stopwatch by its duration in ns, applying the formatting options.

   @param sw
      Stopwatch to write.
   @param ptwOut
      Pointer to the writer to output to.
   */
   void write(perf::stopwatch const & sw, io::text::writer * ptwOut) {
      to_str_backend<perf::stopwatch::duration_type>::write(sw.duration(), ptwOut);
   }
};

} //namespace abc

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

#endif //ifndef _ABACLADE_PERF_STOPWATCH_HXX
<commit_msg>Improve code documentation<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2014
Raffaello D. Di Napoli

This file is part of Abaclade.

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

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

You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#ifndef _ABACLADE_PERF_STOPWATCH_HXX
#define _ABACLADE_PERF_STOPWATCH_HXX

#ifndef _ABACLADE_HXX
   #error "Please #include <abaclade.hxx> before this file"
#endif
#ifdef ABC_CXX_PRAGMA_ONCE
   #pragma once
#endif

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::perf::stopwatch

namespace abc {
namespace perf {

/*! Measures processing time intervals for the current process at a high platform-dependent
precision. */
class ABACLADE_TESTING_SYM stopwatch {
public:
   //! Integer type used to measure durations.
   typedef std::uint64_t duration_type;

public:
   //! Constructor.
   stopwatch();

   //! Destructor.
   ~stopwatch();

   /*! Returns the total tracked time.

   @return
      Cumulative time counted by start()/stop() call pairs.
   */
   duration_type duration() const {
      return m_iTotalDuration;
   }

   //! Starts tracking time.
   void start();

   /*! Stops tracking time.

   @return
      Time elapsed since the last call to start().
   */
   duration_type stop();

protected:
   /*! Start time of the current timed session. Large enough to accommodate the real type, defined
   in stopwatch.cxx. */
   std::max_align_t m_abStartTime[ABC_ALIGNED_SIZE(8)];
   //! Total measured time duration, in nanoseconds. Precision is not guaranteed on all platforms.
   duration_type m_iTotalDuration;
};

} //namespace perf
} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend – specialization for abc::perf::stopwatch

namespace abc {

template <>
class to_str_backend<perf::stopwatch> : public to_str_backend<perf::stopwatch::duration_type> {
public:
   /*! Writes a stopwatch by its duration in ns, applying the formatting options.

   @param sw
      Stopwatch to write.
   @param ptwOut
      Pointer to the writer to output to.
   */
   void write(perf::stopwatch const & sw, io::text::writer * ptwOut) {
      to_str_backend<perf::stopwatch::duration_type>::write(sw.duration(), ptwOut);
   }
};

} //namespace abc

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

#endif //ifndef _ABACLADE_PERF_STOPWATCH_HXX
<|endoftext|>


<commit_before>// Copyright (c) 2013-2014 Flowgrammable.org
//
// 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.

#ifndef NOCONTROL_OFP_HANDLER_HPP
#define NOCONTROL_OFP_HANDLER_HPP

#include <freeflow/sys/socket.hpp>
#include <freeflow/sys/handler.hpp>
#include <freeflow/sys/acceptor.hpp>
#include <freeflow/sdn/controller.hpp>
#include <freeflow/proto/ofp/protocol.hpp>

#include "prelude.hpp"

namespace nocontrol {

/// Represents an OpenFlow connection with a switch. This class acts as a
/// small shim that buffers messages and hands them to a state machine for
/// further processing.
///
/// \todo We're required to TLS for switch connections. This
/// seems like the likely integration point for that work.
class Ofp_handler : public ff::Socket_handler {
  struct Write_on_exit;
public:
  Ofp_handler(ff::Reactor&, ff::Socket&&, ff::Controller&);

  bool on_open();
  bool on_close();
  bool on_read();
  bool on_time(int);

private:
  bool read();
  bool write();

  ff::Controller& ctrl_;
  ff::ofp::Protocol* proto_;
};

/// The Ofp_factory is responsible for creating new service handlers
/// for connected switches.
///
/// \todo This is the same as the Nocontrol_factory. Factor this into
/// a template in the SDN library.
struct Ofp_factory {
  Ofp_factory(ff::Controller&);

  Ofp_handler* operator()(ff::Reactor&, ff::Socket&&) const;

private:
  ff::Controller& ctrl_;
};

/// The Switch_acceptor is responsible for accepting connections from
/// switches and constructing service handlers to manage the OpenFlow
/// protocol.
using Ofp_acceptor = ff::Acceptor<Ofp_handler, Ofp_factory>;

} // namespace nocontrol

#include "openflow.hpp"

#endif
<commit_msg>Fixing documentation error.<commit_after>// Copyright (c) 2013-2014 Flowgrammable.org
//
// 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.

#ifndef NOCONTROL_OFP_HANDLER_HPP
#define NOCONTROL_OFP_HANDLER_HPP

#include <freeflow/sys/socket.hpp>
#include <freeflow/sys/handler.hpp>
#include <freeflow/sys/acceptor.hpp>
#include <freeflow/sdn/controller.hpp>
#include <freeflow/proto/ofp/protocol.hpp>

#include "prelude.hpp"

namespace nocontrol {

/// Represents an OpenFlow connection with a switch. This class acts as a
/// small shim that buffers messages and hands them to a state machine for
/// further processing.
///
/// \todo We're required to TLS for switch connections. This
/// seems like the likely integration point for that work.
class Ofp_handler : public ff::Socket_handler {
  struct Write_on_exit;
public:
  Ofp_handler(ff::Reactor&, ff::Socket&&, ff::Controller&);

  bool on_open();
  bool on_close();
  bool on_read();
  bool on_time(int);

private:
  bool read();
  bool write();

  ff::Controller& ctrl_;
  ff::ofp::Protocol* proto_;
};

/// The Ofp_factory is responsible for creating new service handlers
/// for connected switches.
///
/// \todo This is the same as the Nocontrol_factory. Factor this into
/// a template in the SDN library.
struct Ofp_factory {
  Ofp_factory(ff::Controller&);

  Ofp_handler* operator()(ff::Reactor&, ff::Socket&&) const;

private:
  ff::Controller& ctrl_;
};

/// The Ofp_acceptor is responsible for accepting connections from
/// switches and constructing service handlers to manage the OpenFlow
/// protocol.
using Ofp_acceptor = ff::Acceptor<Ofp_handler, Ofp_factory>;

} // namespace nocontrol

#include "openflow.hpp"

#endif
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

//Get the implementations
#include "etl/impl/transpose.hpp"

namespace etl {

/*!
 * \brief A transposition expression.
 * \tparam T The value type
 */
template <typename T>
struct transpose_expr : impl_expr<transpose_expr<T>> {
    using value_type = T;                 ///< The type of value of the expression
    using this_type  = transpose_expr<T>; ///< The type of this expression

    static constexpr bool is_gpu = cublas_enabled; ///< Indicates if the expression runs on GPU

    /*!
     * \brief The result type for given sub types
     * \tparam A the sub expression type
     */
    template <typename A>
    using result_type = detail::expr_result_t<this_type, A>;

    /*!
     * \brief Validate the transposition dimensions
     * \param a The input matrix
     * \þaram c The output matrix
     */
    template <typename A, typename C, cpp_enable_if(all_fast<A,C>::value)>
    static void check(const A& a, const C& c) {
        cpp_unused(a);
        cpp_unused(c);

        static_assert(decay_traits<A>::template dim<0>() == decay_traits<C>::template dim<1>(), "Invalid dimensions for transposition");
        static_assert(decay_traits<C>::template dim<0>() == decay_traits<A>::template dim<1>(), "Invalid dimensions for transposition");
    }

    /*!
     * \brief Validate the transposition dimensions
     * \param a The input matrix
     * \þaram c The output matrix
     */
    template <typename A, typename C, cpp_disable_if(all_fast<A,C>::value)>
    static void check(const A& a, const C& c) {
        cpp_unused(a);
        cpp_unused(c);

        cpp_assert(etl::dim<0>(a) == etl::dim<1>(c), "Invalid dimensions for transposition");
        cpp_assert(etl::dim<1>(a) == etl::dim<0>(c), "Invalid dimensions for transposition");
    }

    /*!
     * \brief Apply the expression
     * \param a The input
     * \param c The expression where to store the results
     */
    template <typename A, typename C>
    static void apply(A&& a, C&& c) {
        static_assert(all_etl_expr<A, C>::value, "Transpose only supported for ETL expressions");

        check(a, c);

        detail::transpose::apply(make_temporary(std::forward<A>(a)), std::forward<C>(c));
    }

    /*!
     * \brief Returns a textual representation of the operation
     * \return a textual representation of the operation
     */
    static constexpr const char* desc() noexcept {
        return "transpose";
    }

    /*!
     * \brief Returns the DDth dimension of the expression
     * \return the DDth dimension of the expression
     */
    template <typename A, std::size_t DD>
    static constexpr std::size_t dim() {
        return DD == 0 ? decay_traits<A>::template dim<1>() : decay_traits<A>::template dim<0>();
    }

    /*!
     * \brief Returns the dth dimension of the expression
     * \param a The left hand side
     * \param d The dimension to get
     * \return the dth dimension of the expression
     */
    template <typename A>
    static std::size_t dim(const A& a, std::size_t d) {
        return d == 0 ? etl::dim<1>(a) : etl::dim<0>(a);
    }

    /*!
     * \brief Returns the size of the expression
     * \param a The left hand side
     * \return the size of the expression
     */
    template <typename A>
    static std::size_t size(const A& a) {
        return etl::size(a);
    }

    /*!
     * \brief Returns the size of the expression
     * \return the size of the expression
     */
    template <typename A>
    static constexpr std::size_t size() {
        return decay_traits<A>::size();
    }

    /*!
     * \brief Returns the storage order of the expression.
     * \return the storage order of the expression
     */
    template <typename A>
    static constexpr etl::order order() {
        return etl::order::RowMajor;
    }

    /*!
     * \brief Returns the number of dimensions of the expression
     * \return the number of dimensions of the expression
     */
    static constexpr std::size_t dimensions() {
        return 2;
    }
};

} //end of namespace etl
<commit_msg>Better checks for all cases<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

//Get the implementations
#include "etl/impl/transpose.hpp"

namespace etl {

/*!
 * \brief A transposition expression.
 * \tparam T The value type
 */
template <typename T>
struct transpose_expr : impl_expr<transpose_expr<T>> {
    using value_type = T;                 ///< The type of value of the expression
    using this_type  = transpose_expr<T>; ///< The type of this expression

    static constexpr bool is_gpu = cublas_enabled; ///< Indicates if the expression runs on GPU

    /*!
     * \brief The result type for given sub types
     * \tparam A the sub expression type
     */
    template <typename A>
    using result_type = detail::expr_result_t<this_type, A>;

    /*!
     * \brief Validate the transposition dimensions
     * \param a The input matrix
     * \þaram c The output matrix
     */
    template <typename A, typename C, cpp_enable_if(all_fast<A,C>::value)>
    static void check(const A& a, const C& c) {
        cpp_unused(a);
        cpp_unused(c);

        static constexpr etl::order order_lhs = decay_traits<C>::storage_order;
        static constexpr etl::order order_rhs = decay_traits<A>::storage_order;

        static constexpr bool rm_to_rm = order_lhs == etl::order::RowMajor && order_rhs == etl::order::RowMajor;
        static constexpr bool cm_to_cm = order_lhs == etl::order::ColumnMajor && order_rhs == etl::order::ColumnMajor;
        static constexpr bool rm_to_cm = order_lhs == etl::order::RowMajor && order_rhs == etl::order::ColumnMajor;
        static constexpr bool cm_to_rm = order_lhs == etl::order::ColumnMajor && order_rhs == etl::order::RowMajor;

        static constexpr size_t L1 = decay_traits<C>::template dim<0>();
        static constexpr size_t L2 = decay_traits<C>::template dim<1>();
        static constexpr size_t R1 = decay_traits<A>::template dim<0>();
        static constexpr size_t R2 = decay_traits<A>::template dim<1>();

        // Case 1: RM -> RM
        static_assert(!rm_to_rm || (L1 == R2 && L2 == R1), "Invalid dimensions for transposition");

        // Case 2: CM -> CM
        static_assert(!cm_to_cm || (L1 == R2 && L2 == R1), "Invalid dimensions for transposition");

        // Case 3: RM -> CM (two possible cases)
        static_assert(!rm_to_cm || ((L1 == R2 && L2 == R1) || (L1 == R1 && L2 == R2)), "Invalid dimensions for transposition");

        // Case 4: RM -> CM (two possible cases)
        static_assert(!cm_to_rm || ((L1 == R2 && L2 == R1) || (L1 == R1 && L2 == R2)), "Invalid dimensions for transposition");
    }

    /*!
     * \brief Validate the transposition dimensions
     * \param a The input matrix
     * \þaram c The output matrix
     */
    template <typename A, typename C, cpp_disable_if(all_fast<A,C>::value)>
    static void check(const A& a, const C& c) {
        static constexpr etl::order order_lhs = decay_traits<A>::storage_order;
        static constexpr etl::order order_rhs = decay_traits<A>::storage_order;

        static constexpr bool rm_to_rm = order_lhs == etl::order::RowMajor && order_rhs == etl::order::RowMajor;
        static constexpr bool cm_to_cm = order_lhs == etl::order::ColumnMajor && order_rhs == etl::order::ColumnMajor;
        static constexpr bool rm_to_cm = order_lhs == etl::order::RowMajor && order_rhs == etl::order::ColumnMajor;
        static constexpr bool cm_to_rm = order_lhs == etl::order::ColumnMajor && order_rhs == etl::order::RowMajor;

        const size_t L1 = etl::dim<0>(c);
        const size_t L2 = etl::dim<1>(c);
        const size_t R1 = etl::dim<0>(a);
        const size_t R2 = etl::dim<1>(a);

        // Case 1: RM -> RM
        cpp_assert(!rm_to_rm || (L1 == R2 && L2 == R1), "Invalid dimensions for transposition");

        // Case 2: CM -> CM
        cpp_assert(!cm_to_cm || (L1 == R2 && L2 == R1), "Invalid dimensions for transposition");

        // Case 3: RM -> CM (two possible cases)
        cpp_assert(!rm_to_cm || ((L1 == R2 && L2 == R1) || (L1 == R1 && L2 == R2)), "Invalid dimensions for transposition");

        // Case 4: RM -> CM (two possible cases)
        cpp_assert(!cm_to_rm || ((L1 == R2 && L2 == R1) || (L1 == R1 && L2 == R2)), "Invalid dimensions for transposition");

        cpp_unused(L1);
        cpp_unused(L2);
        cpp_unused(R1);
        cpp_unused(R2);
    }

    /*!
     * \brief Apply the expression
     * \param a The input
     * \param c The expression where to store the results
     */
    template <typename A, typename C>
    static void apply(A&& a, C&& c) {
        static_assert(all_etl_expr<A, C>::value, "Transpose only supported for ETL expressions");

        check(a, c);

        detail::transpose::apply(make_temporary(std::forward<A>(a)), std::forward<C>(c));
    }

    /*!
     * \brief Returns a textual representation of the operation
     * \return a textual representation of the operation
     */
    static constexpr const char* desc() noexcept {
        return "transpose";
    }

    /*!
     * \brief Returns the DDth dimension of the expression
     * \return the DDth dimension of the expression
     */
    template <typename A, std::size_t DD>
    static constexpr std::size_t dim() {
        return DD == 0 ? decay_traits<A>::template dim<1>() : decay_traits<A>::template dim<0>();
    }

    /*!
     * \brief Returns the dth dimension of the expression
     * \param a The left hand side
     * \param d The dimension to get
     * \return the dth dimension of the expression
     */
    template <typename A>
    static std::size_t dim(const A& a, std::size_t d) {
        return d == 0 ? etl::dim<1>(a) : etl::dim<0>(a);
    }

    /*!
     * \brief Returns the size of the expression
     * \param a The left hand side
     * \return the size of the expression
     */
    template <typename A>
    static std::size_t size(const A& a) {
        return etl::size(a);
    }

    /*!
     * \brief Returns the size of the expression
     * \return the size of the expression
     */
    template <typename A>
    static constexpr std::size_t size() {
        return decay_traits<A>::size();
    }

    /*!
     * \brief Returns the storage order of the expression.
     * \return the storage order of the expression
     */
    template <typename A>
    static constexpr etl::order order() {
        return etl::order::RowMajor;
    }

    /*!
     * \brief Returns the number of dimensions of the expression
     * \return the number of dimensions of the expression
     */
    static constexpr std::size_t dimensions() {
        return 2;
    }
};

} //end of namespace etl
<|endoftext|>


<commit_before>#include <stdio.h>
#include <conio.h> // getch()
#include <math.h> // fmod() abs()

// ********* WINDOWS ONLY *********
#include <windows.h>
void color(unsigned char color){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); }
enum COLORS { // these values varies in consoles, they should be factory default ;)
	BLACK, 	DARKBLUE, 	DARKGREEN, 	DARKCYAN, 	DARKRED, 	MAGENTTA, 	ORANGE, 	GRAY,
	DARKGRAY, 	BLUE, 	GREEN, 		CYAN, 		RED,  		PINK, 		YELLOW, 	WHITE
};
void printFlag(int width){
	double x = width;
	double y = 2*x/3;
	double c = (double)width/(double)15;

	for(int i = 0;i < y;i++){
		for(int j = 0;j < x;j++){
			if( j/2 <= ( (width/8) + c - abs(c - fmod(i,c*2) ) ) ) color(WHITE);
			else color(RED);
			printf("%c",219);
		}printf("\n");
	}
}
// *********
int main()
{
	printFlag(80); // define your flag width here
	getch();
	return 0;
}

<commit_msg>Color now changes only when needed<commit_after>#include <stdio.h>
#include <conio.h> // getch()
#include <math.h> // fmod() abs()

// ********* WINDOWS ONLY *********
#include <windows.h>
void color(unsigned char color){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); }
enum COLORS { // these values varies in consoles, they should be factory default ;)
	BLACK, 	DARKBLUE, 	DARKGREEN, 	DARKCYAN, 	DARKRED, 	MAGENTTA, 	ORANGE, 	GRAY,
	DARKGRAY, 	BLUE, 	GREEN, 		CYAN, 		RED,  		PINK, 		YELLOW, 	WHITE
};
void printFlag(int width){
	double x = width;
	double y = 2*x/3;
	double c = (double)width/(double)15;

	for(int i = 0;i < y;i++){
		color(WHITE);
		for(int j = 0;j < x;j++){
			if( (int)(j/2 == (int)( (width/8) + c - abs(c - fmod(i,c*2) ) ) ) ) color(RED);
			printf("%c",219);
		}printf("\n");
	}
}
// *********
int main()
{
	printFlag(100); // define your flag width here
	getch();
	return 0;
}

<|endoftext|>


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

#ifndef MAPNIK_SYMBOLIZER_UTILS_HPP
#define MAPNIK_SYMBOLIZER_UTILS_HPP

// mapnik
#include <mapnik/symbolizer.hpp>
// boost
#include <boost/variant/apply_visitor.hpp>

namespace mapnik {

template <typename Symbolizer>
struct symbolizer_traits
{
    static char const* name() { return "Unknown";}
};

template<>
struct symbolizer_traits<point_symbolizer>
{
    static char const* name() { return "PointSymbolizer";}
};

template<>
struct symbolizer_traits<line_symbolizer>
{
    static char const* name() { return "LineSymbolizer";}
};

template<>
struct symbolizer_traits<polygon_symbolizer>
{
    static char const* name() { return "PolygonSymbolizer";}
};

template<>
struct symbolizer_traits<text_symbolizer>
{
    static char const* name() { return "TextSymbolizer";}
};

template<>
struct symbolizer_traits<line_pattern_symbolizer>
{
    static char const* name() { return "LinePatternSymbolizer";}
};

template<>
struct symbolizer_traits<polygon_pattern_symbolizer>
{
    static char const* name() { return "PolygonPatternSymbolizer";}
};

template<>
struct symbolizer_traits<markers_symbolizer>
{
    static char const* name() { return "MarkersSymbolizer";}
};

template<>
struct symbolizer_traits<shield_symbolizer>
{
    static char const* name() { return "ShieldSymbolizer";}
};

template<>
struct symbolizer_traits<raster_symbolizer>
{
    static char const* name() { return "RasterSymbolizer";}
};

template<>
struct symbolizer_traits<building_symbolizer>
{
    static char const* name() { return "BuildingSymbolizer";}
};

template<>
struct symbolizer_traits<debug_symbolizer>
{
    static char const* name() { return "DebugSymbolizer";}
};

// symbolizer name impl
namespace detail {

struct symbolizer_name_impl : public boost::static_visitor<std::string>
{
public:
    template <typename Symbolizer>
    std::string operator () (Symbolizer const& sym) const
    {
        boost::ignore_unused_variable_warning(sym);
        return symbolizer_traits<Symbolizer>::name();
    }
};
}

std::string symbolizer_name(symbolizer const& sym)
{
    std::string type = boost::apply_visitor( detail::symbolizer_name_impl(), sym);
    return type;
}

};

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

#ifndef MAPNIK_SYMBOLIZER_UTILS_HPP
#define MAPNIK_SYMBOLIZER_UTILS_HPP

// mapnik
#include <mapnik/symbolizer.hpp>
#include <mapnik/transform_processor.hpp>
#include <mapnik/expression_string.hpp>

// boost
#include <boost/variant/apply_visitor.hpp>

namespace mapnik {

template <typename Symbolizer>
struct symbolizer_traits
{
    static char const* name() { return "Unknown";}
};

template<>
struct symbolizer_traits<point_symbolizer>
{
    static char const* name() { return "PointSymbolizer";}
};

template<>
struct symbolizer_traits<line_symbolizer>
{
    static char const* name() { return "LineSymbolizer";}
};

template<>
struct symbolizer_traits<polygon_symbolizer>
{
    static char const* name() { return "PolygonSymbolizer";}
};

template<>
struct symbolizer_traits<text_symbolizer>
{
    static char const* name() { return "TextSymbolizer";}
};

template<>
struct symbolizer_traits<line_pattern_symbolizer>
{
    static char const* name() { return "LinePatternSymbolizer";}
};

template<>
struct symbolizer_traits<polygon_pattern_symbolizer>
{
    static char const* name() { return "PolygonPatternSymbolizer";}
};

template<>
struct symbolizer_traits<markers_symbolizer>
{
    static char const* name() { return "MarkersSymbolizer";}
};

template<>
struct symbolizer_traits<shield_symbolizer>
{
    static char const* name() { return "ShieldSymbolizer";}
};

template<>
struct symbolizer_traits<raster_symbolizer>
{
    static char const* name() { return "RasterSymbolizer";}
};

template<>
struct symbolizer_traits<building_symbolizer>
{
    static char const* name() { return "BuildingSymbolizer";}
};

template<>
struct symbolizer_traits<debug_symbolizer>
{
    static char const* name() { return "DebugSymbolizer";}
};

// symbolizer name impl
namespace detail {

struct symbolizer_name_impl : public boost::static_visitor<std::string>
{
public:
    template <typename Symbolizer>
    std::string operator () (Symbolizer const& sym) const
    {
        boost::ignore_unused_variable_warning(sym);
        return symbolizer_traits<Symbolizer>::name();
    }
};
}

std::string symbolizer_name(symbolizer const& sym)
{
    std::string type = boost::apply_visitor( detail::symbolizer_name_impl(), sym);
    return type;
}

template <typename Meta>
class symbolizer_property_value_string : public boost::static_visitor<std::string>
{
public:
    symbolizer_property_value_string (Meta const& meta)
        : meta_(meta) {}

    std::string operator() ( mapnik::enumeration_wrapper const& e) const
    {
        std::stringstream ss;
        auto const& convert_fun_ptr(std::get<2>(meta_));
        if ( convert_fun_ptr )
        {
            ss << convert_fun_ptr(e);
        }
        return ss.str();
    }

    std::string operator () ( path_expression_ptr const& expr) const
    {
        if (expr)
        {
            return path_processor::to_string(*expr);
        }
        return std::string();
    }

    std::string operator () (text_placements_ptr const& expr) const
    {
        return std::string("\"<fixme-text-placement-ptr>\"");
    }

    std::string operator () (raster_colorizer_ptr const& expr) const
    {
        return std::string("\"<fixme-raster-colorizer-ptr>\"");
    }

    std::string operator () (transform_type const& expr) const
    {
        if (expr)
        {
            return transform_processor_type::to_string(*expr);
        }
        return std::string();
    }

    std::string operator () (expression_ptr const& expr) const
    {
        if (expr)
        {
            return mapnik::to_expression_string(*expr);
        }
        return std::string();
    }

    std::string operator () (dash_array const& dash) const
    {
        std::ostringstream ss;
        for (std::size_t i = 0; i < dash.size(); ++i)
        {
            ss << dash[i].first << ", " << dash[i].second;
            if ( i + 1 < dash.size() ) ss << ",";
        }
        return ss.str();
    }

    template <typename T>
    std::string operator () ( T const& val ) const
    {
        std::ostringstream ss;
        ss << val;
        return ss.str();
    }

private:
    Meta const& meta_;
};

};

#endif // MAPNIK_SYMBOLIZER_UTILS_HPP
<|endoftext|>