<commit_before>#ifndef FROMEVENT_HPP
#define FROMEVENT_HPP

#include "FlagStatus.hpp"
#include "IOLogWrapper.hpp"
#include "List.hpp"
#include "Params.hpp"
#include "Vector.hpp"
#include "bridge.h"

namespace org_pqrs_Karabiner {
class FromEvent;

class PressingFromEvents {
  friend class FromEvent;

public:
  class Item final : public List::Item {
  public:
    Item(const FromEvent* p) : fromEvent_(p) {}
    ~Item(void) {}

    const FromEvent* getFromEvent(void) const { return fromEvent_; }

  private:
    const FromEvent* fromEvent_;
  };

  static Item* find(const FromEvent* p) {
    for (Item* q = static_cast<Item*>(list_.safe_front()); q; q = static_cast<Item*>(q->getnext())) {
      if (q->getFromEvent() == p) {
        return q;
      }
    }
    return nullptr;
  }

  static void clear(void) {
    list_.clear();
  }

  static void push_back(const FromEvent* p) {
    list_.push_back(new Item(p));
  }

  static bool erase(const FromEvent* p) {
    Item* q = find(p);
    if (q) {
      list_.erase_and_delete(q);
      return true;
    }
    return false;
  }

  static void erase_all(const FromEvent* p) {
    for (;;) {
      if (!erase(p)) {
        break;
      }
    }
  }

private:
  static List list_;
};

class FromEvent final {
public:
  class Type final {
  public:
    enum Value {
      NONE,
      KEY,
      CONSUMER_KEY, // Mute, VolumeIncrement, VolumeDecrement, etcetc.
      POINTING_BUTTON,
    };
  };

  FromEvent(void) : type_(Type::NONE) {}
  explicit FromEvent(KeyCode v) : type_(Type::KEY), key_(v) {}
  explicit FromEvent(ConsumerKeyCode v) : type_(Type::CONSUMER_KEY), consumer_(v) {}
  explicit FromEvent(PointingButton v) : type_(Type::POINTING_BUTTON), button_(v) {}

  explicit FromEvent(const Params_Base& paramsBase) {
    type_ = Type::NONE;

    {
      auto p = paramsBase.get_Params_KeyboardEventCallBack();
      if (p) {
        type_ = Type::KEY;
        key_ = p->key;
        return;
      }
    }
    {
      auto p = paramsBase.get_Params_KeyboardSpecialEventCallback();
      if (p) {
        type_ = Type::CONSUMER_KEY;
        consumer_ = p->key;
        return;
      }
    }
    {
      auto p = paramsBase.get_Params_RelativePointerEventCallback();
      if (p) {
        type_ = Type::POINTING_BUTTON;
        button_ = p->ex_button;
        return;
      }
    }
  }

  FromEvent(AddDataType datatype, AddValue v) {
    switch (datatype) {
    case BRIDGE_DATATYPE_KEYCODE:
      type_ = Type::KEY;
      key_ = KeyCode(v);
      break;
    case BRIDGE_DATATYPE_CONSUMERKEYCODE:
      type_ = Type::CONSUMER_KEY;
      consumer_ = ConsumerKeyCode(v);
      break;
    case BRIDGE_DATATYPE_POINTINGBUTTON:
      type_ = Type::POINTING_BUTTON;
      button_ = PointingButton(v);
      break;
    default:
      IOLOG_ERROR("Unknown datatype: %u\n", static_cast<unsigned int>(datatype));
      type_ = Type::NONE;
      break;
    }
  }

  ~FromEvent(void) { PressingFromEvents::erase_all(this); }

  Type::Value getType(void) const { return type_; }

  // Return whether pressing state is changed.
  bool changePressingState(const Params_Base& paramsBase,
                           const FlagStatus& currentFlags,
                           const Vector_ModifierFlag& fromFlags);

  bool isPressing(void) const { return PressingFromEvents::find(this); }

  // Primitive functions:
  // These functions do not treat Flags.
  // Use changePressingState in general.
  bool isTargetEvent(const Params_Base& paramsBase) const;
  bool isTargetDownEvent(const Params_Base& paramsBase) const;
  bool isTargetUpEvent(const Params_Base& paramsBase) const;

  // Get ModifierFlag from KeyCode.
  ModifierFlag getModifierFlag(void) const {
    if (type_ != Type::KEY) return ModifierFlag::ZERO;
    return key_.getModifierFlag();
  }
  PointingButton getPointingButton(void) const {
    if (type_ != Type::POINTING_BUTTON) return PointingButton::NONE;
    return button_;
  }

private:
  bool isTargetEvent(bool& isDown, const Params_Base& paramsBase) const;

  // Do not store Flags in FromEvent because SimultaneousKeyPresses uses multiple FromEvents.

  Type::Value type_;
  KeyCode key_;
  ConsumerKeyCode consumer_;
  PointingButton button_;
};

DECLARE_VECTOR(FromEvent);
}

#endif
<commit_msg>add final specifier<commit_after>#ifndef FROMEVENT_HPP
#define FROMEVENT_HPP

#include "FlagStatus.hpp"
#include "IOLogWrapper.hpp"
#include "List.hpp"
#include "Params.hpp"
#include "Vector.hpp"
#include "bridge.h"

namespace org_pqrs_Karabiner {
class FromEvent;

class PressingFromEvents final {
  friend class FromEvent;

public:
  class Item final : public List::Item {
  public:
    Item(const FromEvent* p) : fromEvent_(p) {}
    ~Item(void) {}

    const FromEvent* getFromEvent(void) const { return fromEvent_; }

  private:
    const FromEvent* fromEvent_;
  };

  static Item* find(const FromEvent* p) {
    for (Item* q = static_cast<Item*>(list_.safe_front()); q; q = static_cast<Item*>(q->getnext())) {
      if (q->getFromEvent() == p) {
        return q;
      }
    }
    return nullptr;
  }

  static void clear(void) {
    list_.clear();
  }

  static void push_back(const FromEvent* p) {
    list_.push_back(new Item(p));
  }

  static bool erase(const FromEvent* p) {
    Item* q = find(p);
    if (q) {
      list_.erase_and_delete(q);
      return true;
    }
    return false;
  }

  static void erase_all(const FromEvent* p) {
    for (;;) {
      if (!erase(p)) {
        break;
      }
    }
  }

private:
  static List list_;
};

class FromEvent final {
public:
  class Type final {
  public:
    enum Value {
      NONE,
      KEY,
      CONSUMER_KEY, // Mute, VolumeIncrement, VolumeDecrement, etcetc.
      POINTING_BUTTON,
    };
  };

  FromEvent(void) : type_(Type::NONE) {}
  explicit FromEvent(KeyCode v) : type_(Type::KEY), key_(v) {}
  explicit FromEvent(ConsumerKeyCode v) : type_(Type::CONSUMER_KEY), consumer_(v) {}
  explicit FromEvent(PointingButton v) : type_(Type::POINTING_BUTTON), button_(v) {}

  explicit FromEvent(const Params_Base& paramsBase) {
    type_ = Type::NONE;

    {
      auto p = paramsBase.get_Params_KeyboardEventCallBack();
      if (p) {
        type_ = Type::KEY;
        key_ = p->key;
        return;
      }
    }
    {
      auto p = paramsBase.get_Params_KeyboardSpecialEventCallback();
      if (p) {
        type_ = Type::CONSUMER_KEY;
        consumer_ = p->key;
        return;
      }
    }
    {
      auto p = paramsBase.get_Params_RelativePointerEventCallback();
      if (p) {
        type_ = Type::POINTING_BUTTON;
        button_ = p->ex_button;
        return;
      }
    }
  }

  FromEvent(AddDataType datatype, AddValue v) {
    switch (datatype) {
    case BRIDGE_DATATYPE_KEYCODE:
      type_ = Type::KEY;
      key_ = KeyCode(v);
      break;
    case BRIDGE_DATATYPE_CONSUMERKEYCODE:
      type_ = Type::CONSUMER_KEY;
      consumer_ = ConsumerKeyCode(v);
      break;
    case BRIDGE_DATATYPE_POINTINGBUTTON:
      type_ = Type::POINTING_BUTTON;
      button_ = PointingButton(v);
      break;
    default:
      IOLOG_ERROR("Unknown datatype: %u\n", static_cast<unsigned int>(datatype));
      type_ = Type::NONE;
      break;
    }
  }

  ~FromEvent(void) { PressingFromEvents::erase_all(this); }

  Type::Value getType(void) const { return type_; }

  // Return whether pressing state is changed.
  bool changePressingState(const Params_Base& paramsBase,
                           const FlagStatus& currentFlags,
                           const Vector_ModifierFlag& fromFlags);

  bool isPressing(void) const { return PressingFromEvents::find(this); }

  // Primitive functions:
  // These functions do not treat Flags.
  // Use changePressingState in general.
  bool isTargetEvent(const Params_Base& paramsBase) const;
  bool isTargetDownEvent(const Params_Base& paramsBase) const;
  bool isTargetUpEvent(const Params_Base& paramsBase) const;

  // Get ModifierFlag from KeyCode.
  ModifierFlag getModifierFlag(void) const {
    if (type_ != Type::KEY) return ModifierFlag::ZERO;
    return key_.getModifierFlag();
  }
  PointingButton getPointingButton(void) const {
    if (type_ != Type::POINTING_BUTTON) return PointingButton::NONE;
    return button_;
  }

private:
  bool isTargetEvent(bool& isDown, const Params_Base& paramsBase) const;

  // Do not store Flags in FromEvent because SimultaneousKeyPresses uses multiple FromEvents.

  Type::Value type_;
  KeyCode key_;
  ConsumerKeyCode consumer_;
  PointingButton button_;
};

DECLARE_VECTOR(FromEvent);
}

#endif
<|endoftext|>


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

#include "qdir.h"
#include "qfile.h"
#include "qconfig.h"
#include "qsettings.h"
#include "qlibraryinfo.h"
#include "qscopedpointer.h"

#ifdef QT_BUILD_QMAKE
QT_BEGIN_NAMESPACE
extern QString qmake_libraryInfoFile();
QT_END_NAMESPACE
#else
# include "qcoreapplication.h"
#endif

#ifdef Q_OS_MAC
#  include "private/qcore_mac_p.h"
#endif

#include "qconfig.cpp"

QT_BEGIN_NAMESPACE

#ifndef QT_NO_SETTINGS

struct QLibrarySettings
{
    QLibrarySettings();
    QScopedPointer<QSettings> settings;
};
Q_GLOBAL_STATIC(QLibrarySettings, qt_library_settings)

class QLibraryInfoPrivate
{
public:
    static QSettings *findConfiguration();
    static void cleanup()
    {
        QLibrarySettings *ls = qt_library_settings();
        if (ls)
            ls->settings.reset(0);
    }
    static QSettings *configuration()
    {
        QLibrarySettings *ls = qt_library_settings();
        return ls ? ls->settings.data() : 0;
    }
};

QLibrarySettings::QLibrarySettings()
    : settings(QLibraryInfoPrivate::findConfiguration())
{
#ifndef QT_BUILD_QMAKE
    qAddPostRoutine(QLibraryInfoPrivate::cleanup);
#endif
}

QSettings *QLibraryInfoPrivate::findConfiguration()
{
    QString qtconfig = QLatin1String(":/qt/etc/qt.conf");
#ifdef QT_BUILD_QMAKE
    if(!QFile::exists(qtconfig))
        qtconfig = qmake_libraryInfoFile();
#else
    if (!QFile::exists(qtconfig) && QCoreApplication::instance()) {
#ifdef Q_OS_MAC
	CFBundleRef bundleRef = CFBundleGetMainBundle();
        if (bundleRef) {
	    QCFType<CFURLRef> urlRef = CFBundleCopyResourceURL(bundleRef,
							       QCFString(QLatin1String("qt.conf")),
							       0,
							       0);
	    if (urlRef) {
	        QCFString path = CFURLCopyFileSystemPath(urlRef, kCFURLPOSIXPathStyle);
		qtconfig = QDir::cleanPath(path);
	    }
	}
	if (qtconfig.isEmpty())
#endif
            {
                QDir pwd(QCoreApplication::applicationDirPath());
                qtconfig = pwd.filePath(QLatin1String("qt.conf"));
	    }
    }
#endif
    if (QFile::exists(qtconfig))
        return new QSettings(qtconfig, QSettings::IniFormat);
    return 0;     //no luck
}

/*!
    \class QLibraryInfo
    \brief The QLibraryInfo class provides information about the Qt library.

    Many pieces of information are established when Qt is configured.
    Installation paths, license information, and even a unique build
    key. This class provides an abstraction for accessing this
    information.

    \table
    \header \o Function           \o Return value
    \row    \o buildKey()         \o A string that identifies the Qt version and
                                     the configuration. This key is used to ensure
                                     that \l{plugins} link against the same version
                                     of Qt as the application.
    \row    \o location()         \o The path to a certain Qt
                                     component (e.g., documentation, header files).
    \row    \o licensee(),
               licensedProducts() \o Licensing information.
    \endtable

    You can also use a \c qt.conf file to override the hard-coded paths
    that are compiled into the Qt library. For more information, see
    the \l {Using qt.conf} documentation.

    \sa QSysInfo, {Using qt.conf}
*/

/*! \internal

   You cannot create a QLibraryInfo, instead only the static functions are available to query
   information.
*/

QLibraryInfo::QLibraryInfo()
{ }

/*!
  Returns the person to whom this build of Qt is licensed.

  \sa licensedProducts()
*/

QString
QLibraryInfo::licensee()
{
    const char *str = QT_CONFIGURE_LICENSEE;
    return QString::fromLocal8Bit(str);
}

/*!
  Returns the products that the license for this build of Qt has access to.

  \sa licensee()
*/

QString
QLibraryInfo::licensedProducts()
{
    const char *str = QT_CONFIGURE_LICENSED_PRODUCTS;
    return QString::fromLatin1(str);
}

/*!
    Returns a unique key identifying this build of Qt and its
    configurations. This key is not globally unique, rather only useful
    for establishing of two configurations are compatible. This can be
    used to compare with the \c QT_BUILD_KEY preprocessor symbol.

    \sa location()
*/

QString
QLibraryInfo::buildKey()
{
    return QString::fromLatin1(QT_BUILD_KEY);
}

/*!
    \since 4.6
    Returns the installation date for this build of Qt. The install date will
    usually be the last time that Qt sources were configured.
*/
QDate
QLibraryInfo::buildDate()
{
    return QDate::fromString(QString::fromLatin1(qt_configure_installation + 12), Qt::ISODate);
}

/*!
  Returns the location specified by \a loc.

*/

QString
QLibraryInfo::location(LibraryLocation loc)
{
    QString ret;
    if(!QLibraryInfoPrivate::configuration()) {
        const char *path = 0;
        switch (loc) {
#ifdef QT_CONFIGURE_PREFIX_PATH
        case PrefixPath:
            path = QT_CONFIGURE_PREFIX_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_DOCUMENTATION_PATH
        case DocumentationPath:
            path = QT_CONFIGURE_DOCUMENTATION_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_HEADERS_PATH
        case HeadersPath:
            path = QT_CONFIGURE_HEADERS_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_LIBRARIES_PATH
        case LibrariesPath:
            path = QT_CONFIGURE_LIBRARIES_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_BINARIES_PATH
        case BinariesPath:
            path = QT_CONFIGURE_BINARIES_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_PLUGINS_PATH
        case PluginsPath:
            path = QT_CONFIGURE_PLUGINS_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_DATA_PATH
        case DataPath:
            path = QT_CONFIGURE_DATA_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_TRANSLATIONS_PATH
        case TranslationsPath:
            path = QT_CONFIGURE_TRANSLATIONS_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_SETTINGS_PATH
        case SettingsPath:
            path = QT_CONFIGURE_SETTINGS_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_EXAMPLES_PATH
        case ExamplesPath:
            path = QT_CONFIGURE_EXAMPLES_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_DEMOS_PATH
        case DemosPath:
            path = QT_CONFIGURE_DEMOS_PATH;
            break;
#endif
        default:
            break;
        }

        if (path)
            ret = QString::fromLocal8Bit(path);
    } else {
        QString key;
        QString defaultValue;
        switch(loc) {
        case PrefixPath:
            key = QLatin1String("Prefix");
            break;
        case DocumentationPath:
            key = QLatin1String("Documentation");
            defaultValue = QLatin1String("doc");
            break;
        case HeadersPath:
            key = QLatin1String("Headers");
            defaultValue = QLatin1String("include");
            break;
        case LibrariesPath:
            key = QLatin1String("Libraries");
            defaultValue = QLatin1String("lib");
            break;
        case BinariesPath:
            key = QLatin1String("Binaries");
            defaultValue = QLatin1String("bin");
            break;
        case PluginsPath:
            key = QLatin1String("Plugins");
            defaultValue = QLatin1String("plugins");
            break;
        case DataPath:
            key = QLatin1String("Data");
            break;
        case TranslationsPath:
            key = QLatin1String("Translations");
            defaultValue = QLatin1String("translations");
            break;
        case SettingsPath:
            key = QLatin1String("Settings");
            break;
        case ExamplesPath:
            key = QLatin1String("Examples");
            break;
        case DemosPath:
            key = QLatin1String("Demos");
            break;
        default:
            break;
        }

        if(!key.isNull()) {
            QSettings *config = QLibraryInfoPrivate::configuration();
            config->beginGroup(QLatin1String("Paths"));

            QString subKey;
            {
                /*
                  find the child group whose version number is closest
                  to the library version.  for example and we have the
                  following groups:

                  Paths
                  Paths/4.0
                  Paths/4.1.2
                  Paths/4.2.5
                  Paths/5

                  if QT_VERSION is 4.0.1, then we use 'Paths/4.0'
                  if QT_VERSION is 4.1.5, then we use 'Paths/4.1.2'
                  if QT_VERSION is 4.6.3, then we use 'Paths/4.2.5'
                  if QT_VERSION is 6.0.2, then we use 'Paths/5'

                  note: any of the trailing version numbers may be
                  omitted (in which case, they default to zero),
                  i.e. 4 == 4.0.0, 4.1 == 4.1.0, and so on
                */
                enum {
                    QT_MAJOR = ((QT_VERSION >> 16) & 0xFF),
                    QT_MINOR = ((QT_VERSION >> 8) & 0xFF),
                    QT_PATCH = (QT_VERSION & 0xFF)
                };
                int maj = 0, min = 0, pat = 0;
                QStringList children = config->childGroups();
                for(int child = 0; child < children.size(); ++child) {
                    QString cver = children.at(child);
                    QStringList cver_list = cver.split(QLatin1Char('.'));
                    if(cver_list.size() > 0 && cver_list.size() < 4) {
                        bool ok;
                        int cmaj = -1, cmin = -1, cpat = -1;
                        cmaj = cver_list[0].toInt(&ok);
                        if(!ok || cmaj < 0)
                            continue;
                        if(cver_list.size() >= 2) {
                            cmin = cver_list[1].toInt(&ok);
                            if(!ok)
                                continue;
                            if(cmin < 0)
                                cmin = -1;
                        }
                        if(cver_list.size() >= 3) {
                            cpat = cver_list[2].toInt(&ok);
                            if(!ok)
                                continue;
                            if(cpat < 0)
                                cpat = -1;
                        }
                        if((cmaj >= maj && cmaj <= QT_MAJOR) &&
                           (cmin == -1 || (cmin >= min && cmin <= QT_MINOR)) &&
                           (cpat == -1 || (cpat >= pat && cpat <= QT_PATCH)) &&
                           config->contains(cver + QLatin1Char('/') + key)) {
                            subKey = cver + QLatin1Char('/');
                            maj = cmaj;
                            min = cmin;
                            pat = cpat;
                        }
                    }
                }
            }
            ret = config->value(subKey + key, defaultValue).toString();
            // expand environment variables in the form $(ENVVAR)
            int rep;
            QRegExp reg_var(QLatin1String("\\$\\(.*\\)"));
            reg_var.setMinimal(true);
            while((rep = reg_var.indexIn(ret)) != -1) {
                ret.replace(rep, reg_var.matchedLength(),
                            QString::fromLocal8Bit(qgetenv(ret.mid(rep + 2,
                                reg_var.matchedLength() - 3).toLatin1().constData()).constData()));
            }
            config->endGroup();
        }
    }

    if (QDir::isRelativePath(ret)) {
        if (loc == PrefixPath) {
            // we make the prefix path absolute to the executable's directory
#ifdef QT_BUILD_QMAKE
            return QFileInfo(qmake_libraryInfoFile()).absolutePath();
#else
            if (QCoreApplication::instance()) {
#ifdef Q_OS_MAC
                CFBundleRef bundleRef = CFBundleGetMainBundle();
                if (bundleRef) {
                    QCFType<CFURLRef> urlRef = CFBundleCopyBundleURL(bundleRef);
                    if (urlRef) {
                        QCFString path = CFURLCopyFileSystemPath(urlRef, kCFURLPOSIXPathStyle);
                        return QDir::cleanPath(path + QLatin1String("/Contents/") + ret);
                    }
                }
#endif
                return QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(ret);
            } else {
                return QDir::current().absoluteFilePath(ret);
            }
#endif
        } else {
            // we make any other path absolute to the prefix directory
            return QDir(location(PrefixPath)).absoluteFilePath(ret);
        }
    }
    return ret;
}

/*!
    \enum QLibraryInfo::LibraryLocation

    \keyword library location

    This enum type is used to specify a specific location
    specifier:

    \value PrefixPath The default prefix for all paths.
    \value DocumentationPath The location for documentation upon install.
    \value HeadersPath The location for all headers.
    \value LibrariesPath The location of installed librarires.
    \value BinariesPath The location of installed Qt binaries (tools and applications).
    \value PluginsPath The location of installed Qt plugins.
    \value DataPath The location of general Qt data.
    \value TranslationsPath The location of translation information for Qt strings.
    \value SettingsPath The location for Qt settings.
    \value ExamplesPath The location for examples upon install.
    \value DemosPath The location for demos upon install.

    \sa location()
*/

#endif // QT_NO_SETTINGS

QT_END_NAMESPACE

#if defined(Q_CC_GNU) && defined(ELF_INTERPRETER)
#  include <stdio.h>
#  include <stdlib.h>

extern const char qt_core_interpreter[] __attribute__((section(".interp")))
    = ELF_INTERPRETER;

extern "C" void qt_core_boilerplate();
void qt_core_boilerplate()
{
    printf("This is the QtCore library version " QT_VERSION_STR "\n"
           "Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).\n"
           "Contact: Nokia Corporation (qt-info@nokia.com)\n"
           "\n"
           "Build key:           " QT_BUILD_KEY "\n"
           "Installation prefix: %s\n"
           "Library path:        %s\n"
           "Include path:        %s\n",
           qt_configure_prefix_path_str + 12,
           qt_configure_libraries_path_str + 12,
           qt_configure_headers_path_str + 12);
    exit(0);
}

#endif
<commit_msg>Add the Qt Evaluation message to the hidden libQtCore.so boilerplate.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdir.h"
#include "qfile.h"
#include "qconfig.h"
#include "qsettings.h"
#include "qlibraryinfo.h"
#include "qscopedpointer.h"

#ifdef QT_BUILD_QMAKE
QT_BEGIN_NAMESPACE
extern QString qmake_libraryInfoFile();
QT_END_NAMESPACE
#else
# include "qcoreapplication.h"
#endif

#ifdef Q_OS_MAC
#  include "private/qcore_mac_p.h"
#endif

#include "qconfig.cpp"

QT_BEGIN_NAMESPACE

#ifndef QT_NO_SETTINGS

struct QLibrarySettings
{
    QLibrarySettings();
    QScopedPointer<QSettings> settings;
};
Q_GLOBAL_STATIC(QLibrarySettings, qt_library_settings)

class QLibraryInfoPrivate
{
public:
    static QSettings *findConfiguration();
    static void cleanup()
    {
        QLibrarySettings *ls = qt_library_settings();
        if (ls)
            ls->settings.reset(0);
    }
    static QSettings *configuration()
    {
        QLibrarySettings *ls = qt_library_settings();
        return ls ? ls->settings.data() : 0;
    }
};

QLibrarySettings::QLibrarySettings()
    : settings(QLibraryInfoPrivate::findConfiguration())
{
#ifndef QT_BUILD_QMAKE
    qAddPostRoutine(QLibraryInfoPrivate::cleanup);
#endif
}

QSettings *QLibraryInfoPrivate::findConfiguration()
{
    QString qtconfig = QLatin1String(":/qt/etc/qt.conf");
#ifdef QT_BUILD_QMAKE
    if(!QFile::exists(qtconfig))
        qtconfig = qmake_libraryInfoFile();
#else
    if (!QFile::exists(qtconfig) && QCoreApplication::instance()) {
#ifdef Q_OS_MAC
	CFBundleRef bundleRef = CFBundleGetMainBundle();
        if (bundleRef) {
	    QCFType<CFURLRef> urlRef = CFBundleCopyResourceURL(bundleRef,
							       QCFString(QLatin1String("qt.conf")),
							       0,
							       0);
	    if (urlRef) {
	        QCFString path = CFURLCopyFileSystemPath(urlRef, kCFURLPOSIXPathStyle);
		qtconfig = QDir::cleanPath(path);
	    }
	}
	if (qtconfig.isEmpty())
#endif
            {
                QDir pwd(QCoreApplication::applicationDirPath());
                qtconfig = pwd.filePath(QLatin1String("qt.conf"));
	    }
    }
#endif
    if (QFile::exists(qtconfig))
        return new QSettings(qtconfig, QSettings::IniFormat);
    return 0;     //no luck
}

/*!
    \class QLibraryInfo
    \brief The QLibraryInfo class provides information about the Qt library.

    Many pieces of information are established when Qt is configured.
    Installation paths, license information, and even a unique build
    key. This class provides an abstraction for accessing this
    information.

    \table
    \header \o Function           \o Return value
    \row    \o buildKey()         \o A string that identifies the Qt version and
                                     the configuration. This key is used to ensure
                                     that \l{plugins} link against the same version
                                     of Qt as the application.
    \row    \o location()         \o The path to a certain Qt
                                     component (e.g., documentation, header files).
    \row    \o licensee(),
               licensedProducts() \o Licensing information.
    \endtable

    You can also use a \c qt.conf file to override the hard-coded paths
    that are compiled into the Qt library. For more information, see
    the \l {Using qt.conf} documentation.

    \sa QSysInfo, {Using qt.conf}
*/

/*! \internal

   You cannot create a QLibraryInfo, instead only the static functions are available to query
   information.
*/

QLibraryInfo::QLibraryInfo()
{ }

/*!
  Returns the person to whom this build of Qt is licensed.

  \sa licensedProducts()
*/

QString
QLibraryInfo::licensee()
{
    const char *str = QT_CONFIGURE_LICENSEE;
    return QString::fromLocal8Bit(str);
}

/*!
  Returns the products that the license for this build of Qt has access to.

  \sa licensee()
*/

QString
QLibraryInfo::licensedProducts()
{
    const char *str = QT_CONFIGURE_LICENSED_PRODUCTS;
    return QString::fromLatin1(str);
}

/*!
    Returns a unique key identifying this build of Qt and its
    configurations. This key is not globally unique, rather only useful
    for establishing of two configurations are compatible. This can be
    used to compare with the \c QT_BUILD_KEY preprocessor symbol.

    \sa location()
*/

QString
QLibraryInfo::buildKey()
{
    return QString::fromLatin1(QT_BUILD_KEY);
}

/*!
    \since 4.6
    Returns the installation date for this build of Qt. The install date will
    usually be the last time that Qt sources were configured.
*/
QDate
QLibraryInfo::buildDate()
{
    return QDate::fromString(QString::fromLatin1(qt_configure_installation + 12), Qt::ISODate);
}

/*!
  Returns the location specified by \a loc.

*/

QString
QLibraryInfo::location(LibraryLocation loc)
{
    QString ret;
    if(!QLibraryInfoPrivate::configuration()) {
        const char *path = 0;
        switch (loc) {
#ifdef QT_CONFIGURE_PREFIX_PATH
        case PrefixPath:
            path = QT_CONFIGURE_PREFIX_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_DOCUMENTATION_PATH
        case DocumentationPath:
            path = QT_CONFIGURE_DOCUMENTATION_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_HEADERS_PATH
        case HeadersPath:
            path = QT_CONFIGURE_HEADERS_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_LIBRARIES_PATH
        case LibrariesPath:
            path = QT_CONFIGURE_LIBRARIES_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_BINARIES_PATH
        case BinariesPath:
            path = QT_CONFIGURE_BINARIES_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_PLUGINS_PATH
        case PluginsPath:
            path = QT_CONFIGURE_PLUGINS_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_DATA_PATH
        case DataPath:
            path = QT_CONFIGURE_DATA_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_TRANSLATIONS_PATH
        case TranslationsPath:
            path = QT_CONFIGURE_TRANSLATIONS_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_SETTINGS_PATH
        case SettingsPath:
            path = QT_CONFIGURE_SETTINGS_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_EXAMPLES_PATH
        case ExamplesPath:
            path = QT_CONFIGURE_EXAMPLES_PATH;
            break;
#endif
#ifdef QT_CONFIGURE_DEMOS_PATH
        case DemosPath:
            path = QT_CONFIGURE_DEMOS_PATH;
            break;
#endif
        default:
            break;
        }

        if (path)
            ret = QString::fromLocal8Bit(path);
    } else {
        QString key;
        QString defaultValue;
        switch(loc) {
        case PrefixPath:
            key = QLatin1String("Prefix");
            break;
        case DocumentationPath:
            key = QLatin1String("Documentation");
            defaultValue = QLatin1String("doc");
            break;
        case HeadersPath:
            key = QLatin1String("Headers");
            defaultValue = QLatin1String("include");
            break;
        case LibrariesPath:
            key = QLatin1String("Libraries");
            defaultValue = QLatin1String("lib");
            break;
        case BinariesPath:
            key = QLatin1String("Binaries");
            defaultValue = QLatin1String("bin");
            break;
        case PluginsPath:
            key = QLatin1String("Plugins");
            defaultValue = QLatin1String("plugins");
            break;
        case DataPath:
            key = QLatin1String("Data");
            break;
        case TranslationsPath:
            key = QLatin1String("Translations");
            defaultValue = QLatin1String("translations");
            break;
        case SettingsPath:
            key = QLatin1String("Settings");
            break;
        case ExamplesPath:
            key = QLatin1String("Examples");
            break;
        case DemosPath:
            key = QLatin1String("Demos");
            break;
        default:
            break;
        }

        if(!key.isNull()) {
            QSettings *config = QLibraryInfoPrivate::configuration();
            config->beginGroup(QLatin1String("Paths"));

            QString subKey;
            {
                /*
                  find the child group whose version number is closest
                  to the library version.  for example and we have the
                  following groups:

                  Paths
                  Paths/4.0
                  Paths/4.1.2
                  Paths/4.2.5
                  Paths/5

                  if QT_VERSION is 4.0.1, then we use 'Paths/4.0'
                  if QT_VERSION is 4.1.5, then we use 'Paths/4.1.2'
                  if QT_VERSION is 4.6.3, then we use 'Paths/4.2.5'
                  if QT_VERSION is 6.0.2, then we use 'Paths/5'

                  note: any of the trailing version numbers may be
                  omitted (in which case, they default to zero),
                  i.e. 4 == 4.0.0, 4.1 == 4.1.0, and so on
                */
                enum {
                    QT_MAJOR = ((QT_VERSION >> 16) & 0xFF),
                    QT_MINOR = ((QT_VERSION >> 8) & 0xFF),
                    QT_PATCH = (QT_VERSION & 0xFF)
                };
                int maj = 0, min = 0, pat = 0;
                QStringList children = config->childGroups();
                for(int child = 0; child < children.size(); ++child) {
                    QString cver = children.at(child);
                    QStringList cver_list = cver.split(QLatin1Char('.'));
                    if(cver_list.size() > 0 && cver_list.size() < 4) {
                        bool ok;
                        int cmaj = -1, cmin = -1, cpat = -1;
                        cmaj = cver_list[0].toInt(&ok);
                        if(!ok || cmaj < 0)
                            continue;
                        if(cver_list.size() >= 2) {
                            cmin = cver_list[1].toInt(&ok);
                            if(!ok)
                                continue;
                            if(cmin < 0)
                                cmin = -1;
                        }
                        if(cver_list.size() >= 3) {
                            cpat = cver_list[2].toInt(&ok);
                            if(!ok)
                                continue;
                            if(cpat < 0)
                                cpat = -1;
                        }
                        if((cmaj >= maj && cmaj <= QT_MAJOR) &&
                           (cmin == -1 || (cmin >= min && cmin <= QT_MINOR)) &&
                           (cpat == -1 || (cpat >= pat && cpat <= QT_PATCH)) &&
                           config->contains(cver + QLatin1Char('/') + key)) {
                            subKey = cver + QLatin1Char('/');
                            maj = cmaj;
                            min = cmin;
                            pat = cpat;
                        }
                    }
                }
            }
            ret = config->value(subKey + key, defaultValue).toString();
            // expand environment variables in the form $(ENVVAR)
            int rep;
            QRegExp reg_var(QLatin1String("\\$\\(.*\\)"));
            reg_var.setMinimal(true);
            while((rep = reg_var.indexIn(ret)) != -1) {
                ret.replace(rep, reg_var.matchedLength(),
                            QString::fromLocal8Bit(qgetenv(ret.mid(rep + 2,
                                reg_var.matchedLength() - 3).toLatin1().constData()).constData()));
            }
            config->endGroup();
        }
    }

    if (QDir::isRelativePath(ret)) {
        if (loc == PrefixPath) {
            // we make the prefix path absolute to the executable's directory
#ifdef QT_BUILD_QMAKE
            return QFileInfo(qmake_libraryInfoFile()).absolutePath();
#else
            if (QCoreApplication::instance()) {
#ifdef Q_OS_MAC
                CFBundleRef bundleRef = CFBundleGetMainBundle();
                if (bundleRef) {
                    QCFType<CFURLRef> urlRef = CFBundleCopyBundleURL(bundleRef);
                    if (urlRef) {
                        QCFString path = CFURLCopyFileSystemPath(urlRef, kCFURLPOSIXPathStyle);
                        return QDir::cleanPath(path + QLatin1String("/Contents/") + ret);
                    }
                }
#endif
                return QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(ret);
            } else {
                return QDir::current().absoluteFilePath(ret);
            }
#endif
        } else {
            // we make any other path absolute to the prefix directory
            return QDir(location(PrefixPath)).absoluteFilePath(ret);
        }
    }
    return ret;
}

/*!
    \enum QLibraryInfo::LibraryLocation

    \keyword library location

    This enum type is used to specify a specific location
    specifier:

    \value PrefixPath The default prefix for all paths.
    \value DocumentationPath The location for documentation upon install.
    \value HeadersPath The location for all headers.
    \value LibrariesPath The location of installed librarires.
    \value BinariesPath The location of installed Qt binaries (tools and applications).
    \value PluginsPath The location of installed Qt plugins.
    \value DataPath The location of general Qt data.
    \value TranslationsPath The location of translation information for Qt strings.
    \value SettingsPath The location for Qt settings.
    \value ExamplesPath The location for examples upon install.
    \value DemosPath The location for demos upon install.

    \sa location()
*/

#endif // QT_NO_SETTINGS

QT_END_NAMESPACE

#if defined(Q_CC_GNU) && defined(ELF_INTERPRETER)
#  include <stdio.h>
#  include <stdlib.h>

extern const char qt_core_interpreter[] __attribute__((section(".interp")))
    = ELF_INTERPRETER;

extern "C" void qt_core_boilerplate();
void qt_core_boilerplate()
{
    printf("This is the QtCore library version " QT_VERSION_STR "\n"
           "Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).\n"
           "Contact: Nokia Corporation (qt-info@nokia.com)\n"
           "\n"
           "Build key:           " QT_BUILD_KEY "\n"
           "Build date:          %s\n"
           "Installation prefix: %s\n"
           "Library path:        %s\n"
           "Include path:        %s\n",
           qt_configure_installation + 12,
           qt_configure_prefix_path_str + 12,
           qt_configure_libraries_path_str + 12,
           qt_configure_headers_path_str + 12);

#ifdef QT_EVAL
    extern void qt_core_eval_init(uint);
    qt_core_eval_init(1);
#endif

    exit(0);
}

#endif
<|endoftext|>


<commit_before>/*
 * DIPlib 3.0
 * This file contains data-type--related functions.
 *
 * (c)2015-2019, Cris Luengo.
 * Based on original DIPlib code: (c)1995-2014, Delft University of Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "diplib.h"

/* These are the dip_DataTypeGetInfo() functions actually used in the old DIPlib, and what to use in the new infrastructure:
DIP_DT_INFO_SIZEOF                  // DataType::SizeOf
DIP_DT_INFO_C2R                     // DataType::SuggestFloat, FloatType
DIP_DT_INFO_R2C                     // DataType::SuggestComplex, ComplexType
DIP_DT_INFO_GET_MAXIMUM_PRECISION   // Used with dip_ImagesCheck(DIP_CKIM_MAX_PRECISION_MATCH) and in dip_DetermineDataType() in a way I don't understand.
DIP_DT_INFO_MAXIMUM_VALUE           // std::numeric_limits<T>::max()
DIP_DT_INFO_MINIMUM_VALUE           // std::numeric_limits<T>::lowest()
DIP_DT_INFO_PROPS                   // DataType::IsReal, DataType::IsComplex, etc.
DIP_DT_INFO_SUGGEST_2               // DataType::SuggestComplex
DIP_DT_INFO_SUGGEST_5               // A non-binary type that can hold the data (bin->sint8, others don't change) => `if (dt.IsBinary()) { dt = dip::DT_SINT8; }`
DIP_DT_INFO_SUGGEST_6               // DataType::SuggestDouble
DIP_DT_INFO_TO_FLEX                 // DataType::SuggestFlex, FlexType
DIP_DT_INFO_TO_DIPIMAGE             // DataType::SuggestFlexBin, FlexBinType
DIP_DT_INFO_TO_FLOAT                // DataType::SuggestFloat, FloatType
*/

namespace dip {

DataType DataType::SuggestInteger( DataType type ) {
   switch( type ) {
      case DT_BIN:
         return DT_UINT8;
      case DT_SFLOAT:
      case DT_SCOMPLEX:
         return DT_SINT32;
      case DT_DFLOAT:
      case DT_DCOMPLEX:
         return DT_SINT64;
      default:
         return type;
   }
}

DataType DataType::SuggestSigned( DataType type ) {
   switch( type ) {
      case DT_BIN:
         return DT_SINT8;
      case DT_UINT8:
         return DT_SINT16;
      case DT_UINT16:
         return DT_SINT32;
      case DT_UINT32:
      case DT_UINT64:
         return DT_SINT64;
      default:
         return type;
   }
}

DataType DataType::SuggestFloat( DataType type ) {
   switch( type ) {
      default:
         return DT_SFLOAT;
      case DT_UINT32:
      case DT_SINT32:
      case DT_UINT64:
      case DT_SINT64:
      case DT_DFLOAT:
      case DT_DCOMPLEX:
         return DT_DFLOAT;
   }
}

DataType DataType::SuggestDouble( DataType type ) {
   switch( type ) {
      default:
         return DT_DFLOAT;
      case DT_SCOMPLEX:
      case DT_DCOMPLEX:
         return DT_DCOMPLEX;
   }
}

DataType DataType::SuggestComplex( DataType type ) {
   switch( type ) {
      default:
         return DT_SCOMPLEX;
      case DT_UINT32:
      case DT_SINT32:
      case DT_UINT64:
      case DT_SINT64:
      case DT_DFLOAT:
      case DT_DCOMPLEX:
         return DT_DCOMPLEX;
   }
}

DataType DataType::SuggestFlex( DataType type ) {
   switch( type ) {
      default:
         return DT_SFLOAT;
      case DT_UINT32:
      case DT_SINT32:
      case DT_UINT64:
      case DT_SINT64:
      case DT_DFLOAT:
         return DT_DFLOAT;
      case DT_SCOMPLEX:
         return DT_SCOMPLEX;
      case DT_DCOMPLEX:
         return DT_DCOMPLEX;
   }
}

DataType DataType::SuggestFlexBin( DataType type ) {
   switch( type ) {
      case DT_BIN:
         return DT_BIN;
      default:
         return DT_SFLOAT;
      case DT_UINT32:
      case DT_SINT32:
      case DT_UINT64:
      case DT_SINT64:
      case DT_DFLOAT:
         return DT_DFLOAT;
      case DT_SCOMPLEX:
         return DT_SCOMPLEX;
      case DT_DCOMPLEX:
         return DT_DCOMPLEX;
   }
}

DataType DataType::SuggestAbs( DataType type ) {
   switch( type ) {
      default:
         return type;
      case DT_SINT8:
         return DT_UINT8;
      case DT_SINT16:
         return DT_UINT16;
      case DT_SINT32:
         return DT_UINT32;
      case DT_SINT64:
         return DT_UINT64;
      case DT_SCOMPLEX:
         return DT_SFLOAT;
      case DT_DCOMPLEX:
         return DT_DFLOAT;
   }
}

DataType DataType::SuggestReal( DataType type ) {
   switch( type ) {
      default:
         return type;
      case DT_BIN:
         return DT_UINT8;
      case DT_SCOMPLEX:
         return DT_SFLOAT;
      case DT_DCOMPLEX:
         return DT_DFLOAT;
   }
}

DataType DataType::SuggestArithmetic( DataType type1, DataType type2 ) {
   type1 = DataType::SuggestFlexBin( type1 );
   type2 = DataType::SuggestFlexBin( type2 );
   if( type2 > type1 ) {
      dip::swap( type1, type2 ); // sort the two, it saves us lots of tests
   }
   if( type1 == DT_DCOMPLEX ) {
      return DT_DCOMPLEX;
   }
   if(( type1 == DT_SCOMPLEX ) && ( type2 == DT_DFLOAT )) {
      return DT_DCOMPLEX;
   }
   if( type1 == DT_SCOMPLEX ) {
      return DT_SCOMPLEX;
   }
   if( type1 == DT_DFLOAT ) {
      return DT_DFLOAT;
   }
   if( type1 == DT_SFLOAT ) {
      return DT_SFLOAT;
   }
   return DT_BIN;
}

DataType DataType::SuggestDyadicOperation( DataType type1, DataType type2 ) {
   if( type1 == type2 ) {
      return type1;                 // short-cut
   }
   if( type2 > type1 ) {            // compares after casting to integer, see `enum class DT` for order
      dip::swap( type1, type2 );    // sort the two, it saves us lots of tests
   }

   if( type1 == DT_DCOMPLEX ) {
      return DT_DCOMPLEX;
   }
   if( type1 == DT_SCOMPLEX ) {
      if(( type2 == DT_DFLOAT ) || ( type2 == DT_UINT64 ) || ( type2 == DT_SINT64 ) || ( type2 == DT_UINT32 ) || ( type2 == DT_SINT32 )) {
         return DT_DCOMPLEX;
      }
      return DT_SCOMPLEX;
   }

   if( type1 == DT_DFLOAT ) {
      return DT_DFLOAT;
   }
   if( type1 == DT_SFLOAT ) {
      if(( type2 == DT_UINT64 ) || ( type2 == DT_SINT64 ) || ( type2 == DT_UINT32 ) || ( type2 == DT_SINT32 )) {
         return DT_DFLOAT;
      }
      return DT_SFLOAT;
   }

   if( type1 == DT_SINT64 ) {
      return DT_SINT64;
   }
   if( type1 == DT_UINT64 ) {
      if(( type2 == DT_SINT32 ) || ( type2 == DT_SINT16 ) || ( type2 == DT_SINT8 )) {
         return DT_SINT64;
      }
      return DT_UINT64;
   }

   if( type1 == DT_SINT32 ) {
      if( type2 == DT_UINT32 ) {
         return DT_SINT64;
      }
      return DT_SINT32;
   }
   if( type1 == DT_UINT32 ) {
      if(( type2 == DT_SINT16 ) || ( type2 == DT_SINT8 )) {
         return DT_SINT64;
      }
      return DT_UINT32;
   }

   if( type1 == DT_SINT16 ) {
      if( type2 == DT_UINT16 ) {
         return DT_SINT32;
      }
      return DT_SINT16;
   }
   if( type1 == DT_UINT16 ) {
      if( type2 == DT_SINT8 ) {
         return DT_SINT32;
      }
      return DT_UINT16;
   }

   if( type1 == DT_SINT8 ) {
      if( type2 == DT_UINT8 ) {
         return DT_SINT16;
      }
      return DT_SINT8;
   }
   DIP_ASSERT( type1 == DT_UINT8  ) // is always the case: if it's DT_BIN, then type2 is also DT_BIN, and we returned at the first test in this function.
   return DT_UINT8;
}

// Static data members of dip::DataType need to have a place in memory, which is claimed here.
constexpr DataType::Classes DataType::Class_Bin;
constexpr DataType::Classes DataType::Class_UInt8;
constexpr DataType::Classes DataType::Class_SInt8;
constexpr DataType::Classes DataType::Class_UInt16;
constexpr DataType::Classes DataType::Class_SInt16;
constexpr DataType::Classes DataType::Class_UInt32;
constexpr DataType::Classes DataType::Class_SInt32;
constexpr DataType::Classes DataType::Class_UInt64;
constexpr DataType::Classes DataType::Class_SInt64;
constexpr DataType::Classes DataType::Class_SFloat;
constexpr DataType::Classes DataType::Class_DFloat;
constexpr DataType::Classes DataType::Class_SComplex;
constexpr DataType::Classes DataType::Class_DComplex;
constexpr DataType::Classes DataType::Class_Binary;
constexpr DataType::Classes DataType::Class_UInt;
constexpr DataType::Classes DataType::Class_SInt;
constexpr DataType::Classes DataType::Class_Integer;
constexpr DataType::Classes DataType::Class_IntOrBin;
constexpr DataType::Classes DataType::Class_Float;
constexpr DataType::Classes DataType::Class_Complex;
constexpr DataType::Classes DataType::Class_Flex;
constexpr DataType::Classes DataType::Class_FlexBin;
constexpr DataType::Classes DataType::Class_Unsigned;
constexpr DataType::Classes DataType::Class_Signed;
constexpr DataType::Classes DataType::Class_Real;
constexpr DataType::Classes DataType::Class_SignedReal;
constexpr DataType::Classes DataType::Class_NonBinary;
constexpr DataType::Classes DataType::Class_NonComplex;
constexpr DataType::Classes DataType::Class_All;

} // namespace dip
<commit_msg>Don't forget to build with assertions enabled before commiting...<commit_after>/*
 * DIPlib 3.0
 * This file contains data-type--related functions.
 *
 * (c)2015-2019, Cris Luengo.
 * Based on original DIPlib code: (c)1995-2014, Delft University of Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "diplib.h"

/* These are the dip_DataTypeGetInfo() functions actually used in the old DIPlib, and what to use in the new infrastructure:
DIP_DT_INFO_SIZEOF                  // DataType::SizeOf
DIP_DT_INFO_C2R                     // DataType::SuggestFloat, FloatType
DIP_DT_INFO_R2C                     // DataType::SuggestComplex, ComplexType
DIP_DT_INFO_GET_MAXIMUM_PRECISION   // Used with dip_ImagesCheck(DIP_CKIM_MAX_PRECISION_MATCH) and in dip_DetermineDataType() in a way I don't understand.
DIP_DT_INFO_MAXIMUM_VALUE           // std::numeric_limits<T>::max()
DIP_DT_INFO_MINIMUM_VALUE           // std::numeric_limits<T>::lowest()
DIP_DT_INFO_PROPS                   // DataType::IsReal, DataType::IsComplex, etc.
DIP_DT_INFO_SUGGEST_2               // DataType::SuggestComplex
DIP_DT_INFO_SUGGEST_5               // A non-binary type that can hold the data (bin->sint8, others don't change) => `if (dt.IsBinary()) { dt = dip::DT_SINT8; }`
DIP_DT_INFO_SUGGEST_6               // DataType::SuggestDouble
DIP_DT_INFO_TO_FLEX                 // DataType::SuggestFlex, FlexType
DIP_DT_INFO_TO_DIPIMAGE             // DataType::SuggestFlexBin, FlexBinType
DIP_DT_INFO_TO_FLOAT                // DataType::SuggestFloat, FloatType
*/

namespace dip {

DataType DataType::SuggestInteger( DataType type ) {
   switch( type ) {
      case DT_BIN:
         return DT_UINT8;
      case DT_SFLOAT:
      case DT_SCOMPLEX:
         return DT_SINT32;
      case DT_DFLOAT:
      case DT_DCOMPLEX:
         return DT_SINT64;
      default:
         return type;
   }
}

DataType DataType::SuggestSigned( DataType type ) {
   switch( type ) {
      case DT_BIN:
         return DT_SINT8;
      case DT_UINT8:
         return DT_SINT16;
      case DT_UINT16:
         return DT_SINT32;
      case DT_UINT32:
      case DT_UINT64:
         return DT_SINT64;
      default:
         return type;
   }
}

DataType DataType::SuggestFloat( DataType type ) {
   switch( type ) {
      default:
         return DT_SFLOAT;
      case DT_UINT32:
      case DT_SINT32:
      case DT_UINT64:
      case DT_SINT64:
      case DT_DFLOAT:
      case DT_DCOMPLEX:
         return DT_DFLOAT;
   }
}

DataType DataType::SuggestDouble( DataType type ) {
   switch( type ) {
      default:
         return DT_DFLOAT;
      case DT_SCOMPLEX:
      case DT_DCOMPLEX:
         return DT_DCOMPLEX;
   }
}

DataType DataType::SuggestComplex( DataType type ) {
   switch( type ) {
      default:
         return DT_SCOMPLEX;
      case DT_UINT32:
      case DT_SINT32:
      case DT_UINT64:
      case DT_SINT64:
      case DT_DFLOAT:
      case DT_DCOMPLEX:
         return DT_DCOMPLEX;
   }
}

DataType DataType::SuggestFlex( DataType type ) {
   switch( type ) {
      default:
         return DT_SFLOAT;
      case DT_UINT32:
      case DT_SINT32:
      case DT_UINT64:
      case DT_SINT64:
      case DT_DFLOAT:
         return DT_DFLOAT;
      case DT_SCOMPLEX:
         return DT_SCOMPLEX;
      case DT_DCOMPLEX:
         return DT_DCOMPLEX;
   }
}

DataType DataType::SuggestFlexBin( DataType type ) {
   switch( type ) {
      case DT_BIN:
         return DT_BIN;
      default:
         return DT_SFLOAT;
      case DT_UINT32:
      case DT_SINT32:
      case DT_UINT64:
      case DT_SINT64:
      case DT_DFLOAT:
         return DT_DFLOAT;
      case DT_SCOMPLEX:
         return DT_SCOMPLEX;
      case DT_DCOMPLEX:
         return DT_DCOMPLEX;
   }
}

DataType DataType::SuggestAbs( DataType type ) {
   switch( type ) {
      default:
         return type;
      case DT_SINT8:
         return DT_UINT8;
      case DT_SINT16:
         return DT_UINT16;
      case DT_SINT32:
         return DT_UINT32;
      case DT_SINT64:
         return DT_UINT64;
      case DT_SCOMPLEX:
         return DT_SFLOAT;
      case DT_DCOMPLEX:
         return DT_DFLOAT;
   }
}

DataType DataType::SuggestReal( DataType type ) {
   switch( type ) {
      default:
         return type;
      case DT_BIN:
         return DT_UINT8;
      case DT_SCOMPLEX:
         return DT_SFLOAT;
      case DT_DCOMPLEX:
         return DT_DFLOAT;
   }
}

DataType DataType::SuggestArithmetic( DataType type1, DataType type2 ) {
   type1 = DataType::SuggestFlexBin( type1 );
   type2 = DataType::SuggestFlexBin( type2 );
   if( type2 > type1 ) {
      dip::swap( type1, type2 ); // sort the two, it saves us lots of tests
   }
   if( type1 == DT_DCOMPLEX ) {
      return DT_DCOMPLEX;
   }
   if(( type1 == DT_SCOMPLEX ) && ( type2 == DT_DFLOAT )) {
      return DT_DCOMPLEX;
   }
   if( type1 == DT_SCOMPLEX ) {
      return DT_SCOMPLEX;
   }
   if( type1 == DT_DFLOAT ) {
      return DT_DFLOAT;
   }
   if( type1 == DT_SFLOAT ) {
      return DT_SFLOAT;
   }
   return DT_BIN;
}

DataType DataType::SuggestDyadicOperation( DataType type1, DataType type2 ) {
   if( type1 == type2 ) {
      return type1;                 // short-cut
   }
   if( type2 > type1 ) {            // compares after casting to integer, see `enum class DT` for order
      dip::swap( type1, type2 );    // sort the two, it saves us lots of tests
   }

   if( type1 == DT_DCOMPLEX ) {
      return DT_DCOMPLEX;
   }
   if( type1 == DT_SCOMPLEX ) {
      if(( type2 == DT_DFLOAT ) || ( type2 == DT_UINT64 ) || ( type2 == DT_SINT64 ) || ( type2 == DT_UINT32 ) || ( type2 == DT_SINT32 )) {
         return DT_DCOMPLEX;
      }
      return DT_SCOMPLEX;
   }

   if( type1 == DT_DFLOAT ) {
      return DT_DFLOAT;
   }
   if( type1 == DT_SFLOAT ) {
      if(( type2 == DT_UINT64 ) || ( type2 == DT_SINT64 ) || ( type2 == DT_UINT32 ) || ( type2 == DT_SINT32 )) {
         return DT_DFLOAT;
      }
      return DT_SFLOAT;
   }

   if( type1 == DT_SINT64 ) {
      return DT_SINT64;
   }
   if( type1 == DT_UINT64 ) {
      if(( type2 == DT_SINT32 ) || ( type2 == DT_SINT16 ) || ( type2 == DT_SINT8 )) {
         return DT_SINT64;
      }
      return DT_UINT64;
   }

   if( type1 == DT_SINT32 ) {
      if( type2 == DT_UINT32 ) {
         return DT_SINT64;
      }
      return DT_SINT32;
   }
   if( type1 == DT_UINT32 ) {
      if(( type2 == DT_SINT16 ) || ( type2 == DT_SINT8 )) {
         return DT_SINT64;
      }
      return DT_UINT32;
   }

   if( type1 == DT_SINT16 ) {
      if( type2 == DT_UINT16 ) {
         return DT_SINT32;
      }
      return DT_SINT16;
   }
   if( type1 == DT_UINT16 ) {
      if( type2 == DT_SINT8 ) {
         return DT_SINT32;
      }
      return DT_UINT16;
   }

   if( type1 == DT_SINT8 ) {
      if( type2 == DT_UINT8 ) {
         return DT_SINT16;
      }
      return DT_SINT8;
   }
   DIP_ASSERT( type1 == DT_UINT8 ); // is always the case: if it's DT_BIN, then type2 is also DT_BIN, and we returned at the first test in this function.
   return DT_UINT8;
}

// Static data members of dip::DataType need to have a place in memory, which is claimed here.
constexpr DataType::Classes DataType::Class_Bin;
constexpr DataType::Classes DataType::Class_UInt8;
constexpr DataType::Classes DataType::Class_SInt8;
constexpr DataType::Classes DataType::Class_UInt16;
constexpr DataType::Classes DataType::Class_SInt16;
constexpr DataType::Classes DataType::Class_UInt32;
constexpr DataType::Classes DataType::Class_SInt32;
constexpr DataType::Classes DataType::Class_UInt64;
constexpr DataType::Classes DataType::Class_SInt64;
constexpr DataType::Classes DataType::Class_SFloat;
constexpr DataType::Classes DataType::Class_DFloat;
constexpr DataType::Classes DataType::Class_SComplex;
constexpr DataType::Classes DataType::Class_DComplex;
constexpr DataType::Classes DataType::Class_Binary;
constexpr DataType::Classes DataType::Class_UInt;
constexpr DataType::Classes DataType::Class_SInt;
constexpr DataType::Classes DataType::Class_Integer;
constexpr DataType::Classes DataType::Class_IntOrBin;
constexpr DataType::Classes DataType::Class_Float;
constexpr DataType::Classes DataType::Class_Complex;
constexpr DataType::Classes DataType::Class_Flex;
constexpr DataType::Classes DataType::Class_FlexBin;
constexpr DataType::Classes DataType::Class_Unsigned;
constexpr DataType::Classes DataType::Class_Signed;
constexpr DataType::Classes DataType::Class_Real;
constexpr DataType::Classes DataType::Class_SignedReal;
constexpr DataType::Classes DataType::Class_NonBinary;
constexpr DataType::Classes DataType::Class_NonComplex;
constexpr DataType::Classes DataType::Class_All;

} // namespace dip
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.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.
 *
 */

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <expat.h>
#include <string.h>
#include <fstream>
#include <string>
#include <stack>
#include <iomanip>

#include <votca/tools/property.h>
#include <votca/tools/tokenizer.h>
#include <votca/tools/propertyformat.h>

#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>

namespace votca { namespace tools {

// ostream modifier defines the output format, level, indentation
const int Property::_format = std::ios_base::xalloc();
const int Property::_output_level = std::ios_base::xalloc();
const int Property::_output_indent = std::ios_base::xalloc();

Property &Property::get(const string &key)
{
    Tokenizer tok(key, ".");
    Tokenizer::iterator n;

    n = tok.begin();
    if(n==tok.end()) return *this;

    Property *p;
    map<string, Property*>::iterator iter;
    if(*n=="") {
        p = this;
    }
    else {
        iter = _map.find(*n);

        if(iter == _map.end())
            throw runtime_error("property not found: " + key);

        p = (((*iter).second));
    }
    ++n;
    try {
        for(; n!=tok.end(); ++n) {
            p = &p->get(*n);
        }
    }
    catch(string err) { // catch here to get full key in exception
        throw runtime_error("property not found: " + key);
    }

    return *p;
}

std::list<Property *> Property::Select(const string &filter)
{
    Tokenizer tok(filter, ".");

    std::list<Property *> selection;

    if(tok.begin()==tok.end()) return selection;

    selection.push_back(this);

    for (Tokenizer::iterator n = tok.begin();
            n != tok.end(); ++n) {
        std::list<Property *> childs;
        for (std::list<Property *>::iterator p = selection.begin();
                p != selection.end(); ++p) {
                for (list<Property>::iterator iter = (*p)->_properties.begin();
                    iter != (*p)->_properties.end(); ++iter) {
                    if (wildcmp((*n).c_str(), (*iter).name().c_str())) {
                        childs.push_back(&(*iter));
                    }
                }
        }
        selection = childs;
    }

    return selection;
}

void PrintNodeTXT(std::ostream &out, Property &p, const int start_level, int level, string prefix, string offset)
{

    list<Property>::iterator iter;

    /* int indent = 10;
    string fmt = "%|" + boost::lexical_cast<string>(indent) +"t|%1%%|15t|%2%\n";
    out << boost::format(fmt) % "A" % "B"; */

    if((p.value() != "") || p.HasChilds() ) {

        if ( level >= start_level ) {
                if((p.value()).find_first_not_of("\t\n ") != std::string::npos)
                        out << offset << prefix << " = " << p.value() << endl;
        } else {
            prefix="";
        }
    }

    for(iter = p.begin(); iter!=p.end(); ++iter) {
        if(prefix=="") {
            level++;
            PrintNodeTXT(out, (*iter), start_level, level, prefix + (*iter).name(), offset );
            level--;
        } else {
            level++;
            PrintNodeTXT(out, (*iter), start_level, level, prefix + "." + (*iter).name(), offset );
            level--;
        }
    }
}

void PrintNodeXML(std::ostream &out, Property &p, const int start_level, int level, string prefix,  string offset)
{

    list<Property>::iterator iter;
    map<string,string>::iterator ia;
    bool _endl = true;

        // print starting only from the start_level (the first node (level 0) can be <> </>)
        if ( level >= start_level )  {
            // print the node name
            out << offset << "<" << p._name ;
            // print the node attributes
            for(ia = p._attributes.begin(); ia!=p._attributes.end(); ++ia)
                out << " " << ia->first << "=\"" << ia->second << "\"" ;
            out << ">";

            // print node value if it is not empty
            bool has_value = ( (p._value).find_first_not_of("\t\n ") != std::string::npos );
            if( has_value ) { out << p._value; _endl = false; }

            // check if we need the end of the line or not
            if( !has_value &&  p.HasChilds() ) out << endl;
            if( !has_value &&  !p.HasChilds() ) _endl = false;
        }

        // continue iteratively through the rest of the nodes
        for(iter = p._properties.begin(); iter!=p._properties.end(); ++iter) {
            level++;
            if (  level > start_level ) offset += "\t";
            PrintNodeXML(out, (*iter), start_level, level, (*iter)._name, offset);
            if (  level > start_level ) offset.resize(offset.size()-1);
            level--;
        }

        if ( level >= start_level ) {
            if ( _endl ) {
                out << offset << "</" << p._name << ">"  << endl;
            } else {
                out << "</" << p._name << ">"  << endl;
            }
        }
}

void PrintNodeT2T(std::ostream &out, const string &prefix, Property &p) {
    out << "T2T format is not implemented";
}

void PrintNodeLOG(std::ostream &out, const string &prefix, Property &p) {
    out << "LOG format is not implemented";
}

void PrintNodeTEX(std::ostream &out, Property &p, const int start_level, int level, string prefix,  string offset) {

    list<Property>::iterator iter;
    string head_name;
    string _label(""); // reference of the xml file in the manual
    string _section(""); // reference of the description section in the manual
    string _help("");
    string _default(""); // default value if supplied
    string _unit(""); //unit, if supplied

    string header_format("\\subsection{%1%}\n"
                         "\\label{%2%}\n%3%\n"
                         "\\rowcolors{1}{invisiblegray}{white}\n"
                         "{\\small\n "
                         "\\begin{longtable}{m{3cm}|m{2cm}|m{1cm}|m{8cm}}\n"
                         " option & default & unit & description\\\\\n\\hline\n");

    string footer_format("\\end{longtable}\n}\n"
                         "\\noindent Return to the description of \\slink{%1%}{\\texttt{%2%}}.\n");

    string body_format(" \\hspace{%1%pt}\\hypertarget{%2%}{%3%} & %4% & %5% & %6% \\\\\n");

    // if this is the head node, print the header
    if ( level == start_level )  {
            head_name = p._name;
            if ( p.hasAttribute("label") ) _label = p.getAttribute<string>("label");
            if ( p.hasAttribute("section") ) _section = p.getAttribute<string>("section");
            if ( p.hasAttribute("help") ) _help = p.getAttribute<string>("help");
            out << boost::format(header_format) % head_name % _label % _help;
            prefix = p._name;
     }

    if ( level > start_level ) {

        // if this node has children or a value or is not the first, start recursive printing
        if( ( p.value() != "" || p.HasChilds() ) && level > -1) {
            string _tex_name = boost::replace_all_copy( p.name(), "_", "\\_" );

            if ( p.hasAttribute("default") ) _default = p.getAttribute<string>("default");
            if ( p.hasAttribute("unit") ) _unit = p.getAttribute<string>("unit");
            if ( p.hasAttribute("help") ) _help = p.getAttribute<string>("help");

            out << boost::format(body_format) % int((level-start_level-1)*10)
                    % prefix
                    % _tex_name
                    % _default
                    % _unit
                    % _help;
        }
    }

    // continue iteratively through the rest of the nodes
    for(iter = p.begin(); iter != p.end(); ++iter) {
        if(prefix=="") {
            level++;
            PrintNodeTEX(out, (*iter), start_level, level, (*iter)._name, offset);
            level--;
        } else {
            level++;
            PrintNodeTEX(out, (*iter), start_level, level, prefix + "." + (*iter)._name, offset);
            level--;
        }
    }

    // if this is the head node, print the footer
    if ( level == start_level )  out << boost::format(footer_format) % _section % head_name;

}

void PrintNodeHLP(std::ostream &out, Property &p, const int start_level, int level=0, string prefix="",  int offset=0) {

    list<Property>::iterator iter;
    string head_name;
    string help("");
    string fmt("t|%1%%|15t|%2%%|40t|%3%%|55t|%4%\n");

    // if this is the head node, print the header
    if ( level == start_level ) {
            head_name = p.name();
            if ( p.hasAttribute("help") ) {
                if  ( p.hasAttribute("help") ) help = p.getAttribute<string>("help");
                out << boost::format(" %1%: %|18t| %2%\n") % head_name % help;
            }
            offset=0;
            //out << boost::format(fmt) % "option" % "def" % "[un]" % "description";
    }

    if ( level > start_level ) {

            string ofmt;
            ofmt = "%|" + boost::lexical_cast<string>(offset) + fmt;
            //cout << ofmt << " " << fmt << endl;
            string _unit("");
            string _default("");

            if  ( p.hasAttribute("unit") ) _unit = p.getAttribute<string>("unit");
            if  ( p.hasAttribute("default") ) _default = p.getAttribute<string>("default") ;
            if ( !_unit.empty() ) _unit = "[" + _unit + "]";
            if ( !_default.empty() ) _default = "(" + _default + ")";

            out << boost::format(ofmt)
                    % p.name()
                    % _default
                    % _unit
                    % p.getAttribute<string>("help");
    }

    for(iter = p.begin(); iter != p.end(); ++iter) {
        if(prefix=="") {
            offset += 2; level++;
            PrintNodeHLP(out, (*iter), start_level, level, prefix + (*iter).name(), offset);
            offset -= 2; level--;
        } else {
            offset += 2; level++;
            PrintNodeHLP(out, (*iter), start_level, level, prefix + "." + (*iter).name(), offset);
            offset -= 2; level--;
        }
    }

    // if this is the head node, print the footer
    if ( level == start_level ) {
     }
}

std::ostream &operator<<(std::ostream &out, Property& p)
{
    if (!out.good())
        return out;

    std::ostream::sentry sentry(out);

    if(sentry)
    {
        // level from which to start node output
        int _level = out.iword(p.outputLevel());
        int _indent = out.iword(p.outputIndent());
        string sindent;
        for (int i = 0; i < _indent; i++ ) sindent +=  " ";

        switch(out.iword(p.outputFormat()))
        {
        default:
            PrintNodeTXT(out, p, _level);
            case PropertyFormat::XML:
            PrintNodeXML(out, p, _level);
            break;
        case PropertyFormat::TXT:
            PrintNodeTXT(out, p, _level, 0, "", sindent);
            break;
        case PropertyFormat::T2T:
            PrintNodeT2T(out, "", p);
            break;
        case PropertyFormat::LOG:
            PrintNodeLOG(out, "", p);
            break;
        case PropertyFormat::TEX:
            PrintNodeTEX(out, p, _level);
            break;
        case PropertyFormat::HLP:
            PrintNodeHLP(out, p, _level);
            break;
        }
        //out << endl;
    }

    return out;
};

static void start_hndl(void *data, const char *el, const char **attr)
{
    stack<Property *> *property_stack =
        (stack<Property *> *)XML_GetUserData((XML_Parser*)data);

    Property *cur = property_stack->top();
    Property &np = cur->add(el, "");

    for (int i = 0; attr[i]; i += 2)
        np.setAttribute(attr[i], attr[i + 1]);

    property_stack->push(&np);
}

static void end_hndl(void *data, const char *el)
{
    stack<Property *> *property_stack =
        (stack<Property *> *)XML_GetUserData((XML_Parser*)data);
    property_stack->pop();
}

void char_hndl(void *data, const char *txt, int txtlen)
{
    stack<Property *> *property_stack =
        (stack<Property *> *)XML_GetUserData((XML_Parser*)data);

    Property *cur = property_stack->top();
    cur->value().append(txt, txtlen);
}

bool load_property_from_xml(Property &p, string filename)
{
  XML_Parser parser = XML_ParserCreate(NULL);
  if (! parser)
    throw std::runtime_error("Couldn't allocate memory for xml parser");

  XML_UseParserAsHandlerArg(parser);
  XML_SetElementHandler(parser, start_hndl, end_hndl);
  XML_SetCharacterDataHandler(parser, char_hndl);

  ifstream fl;
  fl.open(filename.c_str());
  if(!fl.is_open())
    throw std::ios_base::failure("Error on open xml file: " + filename);

  stack<Property *> pstack;
  pstack.push(&p);

  XML_SetUserData(parser, (void*)&pstack);
  while(!fl.eof()) {
    string line;
    getline(fl, line);
    line=line + "\n";
    if (! XML_Parse(parser, line.c_str(), line.length(), fl.eof()))
      throw  std::ios_base::failure(filename + ": Parse error at line " +
          boost::lexical_cast<string>(XML_GetCurrentLineNumber(parser)) + "\n" +
          XML_ErrorString(XML_GetErrorCode(parser)));
  }
  fl.close();
  return true;
}

}}
<commit_msg>fixed HLP format<commit_after>/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.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.
 *
 */

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <expat.h>
#include <string.h>
#include <fstream>
#include <string>
#include <stack>
#include <iomanip>

#include <votca/tools/property.h>
#include <votca/tools/tokenizer.h>
#include <votca/tools/propertyformat.h>

#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>

namespace votca { namespace tools {

// ostream modifier defines the output format, level, indentation
const int Property::_format = std::ios_base::xalloc();
const int Property::_output_level = std::ios_base::xalloc();
const int Property::_output_indent = std::ios_base::xalloc();

Property &Property::get(const string &key)
{
    Tokenizer tok(key, ".");
    Tokenizer::iterator n;

    n = tok.begin();
    if(n==tok.end()) return *this;

    Property *p;
    map<string, Property*>::iterator iter;
    if(*n=="") {
        p = this;
    }
    else {
        iter = _map.find(*n);

        if(iter == _map.end())
            throw runtime_error("property not found: " + key);

        p = (((*iter).second));
    }
    ++n;
    try {
        for(; n!=tok.end(); ++n) {
            p = &p->get(*n);
        }
    }
    catch(string err) { // catch here to get full key in exception
        throw runtime_error("property not found: " + key);
    }

    return *p;
}

std::list<Property *> Property::Select(const string &filter)
{
    Tokenizer tok(filter, ".");

    std::list<Property *> selection;

    if(tok.begin()==tok.end()) return selection;

    selection.push_back(this);

    for (Tokenizer::iterator n = tok.begin();
            n != tok.end(); ++n) {
        std::list<Property *> childs;
        for (std::list<Property *>::iterator p = selection.begin();
                p != selection.end(); ++p) {
                for (list<Property>::iterator iter = (*p)->_properties.begin();
                    iter != (*p)->_properties.end(); ++iter) {
                    if (wildcmp((*n).c_str(), (*iter).name().c_str())) {
                        childs.push_back(&(*iter));
                    }
                }
        }
        selection = childs;
    }

    return selection;
}

void PrintNodeTXT(std::ostream &out, Property &p, const int start_level, int level, string prefix, string offset)
{

    list<Property>::iterator iter;

    /* int indent = 10;
    string fmt = "%|" + boost::lexical_cast<string>(indent) +"t|%1%%|15t|%2%\n";
    out << boost::format(fmt) % "A" % "B"; */

    if((p.value() != "") || p.HasChilds() ) {

        if ( level >= start_level ) {
                if((p.value()).find_first_not_of("\t\n ") != std::string::npos)
                        out << offset << prefix << " = " << p.value() << endl;
        } else {
            prefix="";
        }
    }

    for(iter = p.begin(); iter!=p.end(); ++iter) {
        if(prefix=="") {
            level++;
            PrintNodeTXT(out, (*iter), start_level, level, prefix + (*iter).name(), offset );
            level--;
        } else {
            level++;
            PrintNodeTXT(out, (*iter), start_level, level, prefix + "." + (*iter).name(), offset );
            level--;
        }
    }
}

void PrintNodeXML(std::ostream &out, Property &p, const int start_level, int level, string prefix,  string offset)
{

    list<Property>::iterator iter;
    map<string,string>::iterator ia;
    bool _endl = true;

        // print starting only from the start_level (the first node (level 0) can be <> </>)
        if ( level >= start_level )  {
            // print the node name
            out << offset << "<" << p._name ;
            // print the node attributes
            for(ia = p._attributes.begin(); ia!=p._attributes.end(); ++ia)
                out << " " << ia->first << "=\"" << ia->second << "\"" ;
            out << ">";

            // print node value if it is not empty
            bool has_value = ( (p._value).find_first_not_of("\t\n ") != std::string::npos );
            if( has_value ) { out << p._value; _endl = false; }

            // check if we need the end of the line or not
            if( !has_value &&  p.HasChilds() ) out << endl;
            if( !has_value &&  !p.HasChilds() ) _endl = false;
        }

        // continue iteratively through the rest of the nodes
        for(iter = p._properties.begin(); iter!=p._properties.end(); ++iter) {
            level++;
            if (  level > start_level ) offset += "\t";
            PrintNodeXML(out, (*iter), start_level, level, (*iter)._name, offset);
            if (  level > start_level ) offset.resize(offset.size()-1);
            level--;
        }

        if ( level >= start_level ) {
            if ( _endl ) {
                out << offset << "</" << p._name << ">"  << endl;
            } else {
                out << "</" << p._name << ">"  << endl;
            }
        }
}

void PrintNodeT2T(std::ostream &out, const string &prefix, Property &p) {
    out << "T2T format is not implemented";
}

void PrintNodeLOG(std::ostream &out, const string &prefix, Property &p) {
    out << "LOG format is not implemented";
}

void PrintNodeTEX(std::ostream &out, Property &p, const int start_level, int level, string prefix,  string offset) {

    list<Property>::iterator iter;
    string head_name;
    string _label(""); // reference of the xml file in the manual
    string _section(""); // reference of the description section in the manual
    string _help("");
    string _default(""); // default value if supplied
    string _unit(""); //unit, if supplied

    string header_format("\\subsection{%1%}\n"
                         "\\label{%2%}\n%3%\n"
                         "\\rowcolors{1}{invisiblegray}{white}\n"
                         "{\\small\n "
                         "\\begin{longtable}{m{3cm}|m{2cm}|m{1cm}|m{8cm}}\n"
                         " option & default & unit & description\\\\\n\\hline\n");

    string footer_format("\\end{longtable}\n}\n"
                         "\\noindent Return to the description of \\slink{%1%}{\\texttt{%2%}}.\n");

    string body_format(" \\hspace{%1%pt}\\hypertarget{%2%}{%3%} & %4% & %5% & %6% \\\\\n");

    // if this is the head node, print the header
    if ( level == start_level )  {
            head_name = p._name;
            if ( p.hasAttribute("label") ) _label = p.getAttribute<string>("label");
            if ( p.hasAttribute("section") ) _section = p.getAttribute<string>("section");
            if ( p.hasAttribute("help") ) _help = p.getAttribute<string>("help");
            out << boost::format(header_format) % head_name % _label % _help;
            prefix = p._name;
     }

    if ( level > start_level ) {

        // if this node has children or a value or is not the first, start recursive printing
        if( ( p.value() != "" || p.HasChilds() ) && level > -1) {
            string _tex_name = boost::replace_all_copy( p.name(), "_", "\\_" );

            if ( p.hasAttribute("default") ) _default = p.getAttribute<string>("default");
            if ( p.hasAttribute("unit") ) _unit = p.getAttribute<string>("unit");
            if ( p.hasAttribute("help") ) _help = p.getAttribute<string>("help");

            out << boost::format(body_format) % int((level-start_level-1)*10)
                    % prefix
                    % _tex_name
                    % _default
                    % _unit
                    % _help;
        }
    }

    // continue iteratively through the rest of the nodes
    for(iter = p.begin(); iter != p.end(); ++iter) {
        if(prefix=="") {
            level++;
            PrintNodeTEX(out, (*iter), start_level, level, (*iter)._name, offset);
            level--;
        } else {
            level++;
            PrintNodeTEX(out, (*iter), start_level, level, prefix + "." + (*iter)._name, offset);
            level--;
        }
    }

    // if this is the head node, print the footer
    if ( level == start_level )  out << boost::format(footer_format) % _section % head_name;

}

void PrintNodeHLP(std::ostream &out, Property &p, const int start_level, int level=0, string prefix="",  int offset=0) {

    list<Property>::iterator iter;
    string head_name;
    string _help("");
    string _unit("");
    string _default("");
    string fmt("t|%1%%|15t|%2%%|40t|%3%%|55t|%4%\n");

    // if this is the head node, print the header
    if ( level == start_level ) {
            head_name = p.name();
            if ( p.hasAttribute("help") ) {
                if  ( p.hasAttribute("help") ) _help = p.getAttribute<string>("help");
                out << boost::format(" %1%: %|18t| %2%\n") % head_name % _help;
            }
            offset=0;
            //out << boost::format(fmt) % "option" % "def" % "[un]" % "description";
    }

    if ( level > start_level ) {

            string ofmt;
            ofmt = "%|" + boost::lexical_cast<string>(offset) + fmt;
            //cout << ofmt << " " << fmt << endl;

            if  ( p.hasAttribute("unit") ) _unit = p.getAttribute<string>("unit");
            if  ( p.hasAttribute("default") ) _default = p.getAttribute<string>("default") ;
            if  ( p.hasAttribute("help") ) _help = p.getAttribute<string>("help") ;
            if ( !_unit.empty() ) _unit = "[" + _unit + "]";
            if ( !_default.empty() ) _default = "(" + _default + ")";

            out << boost::format(ofmt)
                    % p.name()
                    % _default
                    % _unit
                    % _help;
    }

    for(iter = p.begin(); iter != p.end(); ++iter) {
        if(prefix=="") {
            offset += 2; level++;
            PrintNodeHLP(out, (*iter), start_level, level, prefix + (*iter).name(), offset);
            offset -= 2; level--;
        } else {
            offset += 2; level++;
            PrintNodeHLP(out, (*iter), start_level, level, prefix + "." + (*iter).name(), offset);
            offset -= 2; level--;
        }
    }

    // if this is the head node, print the footer
    if ( level == start_level ) {
     }
}

std::ostream &operator<<(std::ostream &out, Property& p)
{
    if (!out.good())
        return out;

    std::ostream::sentry sentry(out);

    if(sentry)
    {
        // level from which to start node output
        int _level = out.iword(p.outputLevel());
        int _indent = out.iword(p.outputIndent());
        string sindent;
        for (int i = 0; i < _indent; i++ ) sindent +=  " ";

        switch(out.iword(p.outputFormat()))
        {
        default:
            PrintNodeTXT(out, p, _level);
            case PropertyFormat::XML:
            PrintNodeXML(out, p, _level);
            break;
        case PropertyFormat::TXT:
            PrintNodeTXT(out, p, _level, 0, "", sindent);
            break;
        case PropertyFormat::T2T:
            PrintNodeT2T(out, "", p);
            break;
        case PropertyFormat::LOG:
            PrintNodeLOG(out, "", p);
            break;
        case PropertyFormat::TEX:
            PrintNodeTEX(out, p, _level);
            break;
        case PropertyFormat::HLP:
            PrintNodeHLP(out, p, _level);
            break;
        }
        //out << endl;
    }

    return out;
};

static void start_hndl(void *data, const char *el, const char **attr)
{
    stack<Property *> *property_stack =
        (stack<Property *> *)XML_GetUserData((XML_Parser*)data);

    Property *cur = property_stack->top();
    Property &np = cur->add(el, "");

    for (int i = 0; attr[i]; i += 2)
        np.setAttribute(attr[i], attr[i + 1]);

    property_stack->push(&np);
}

static void end_hndl(void *data, const char *el)
{
    stack<Property *> *property_stack =
        (stack<Property *> *)XML_GetUserData((XML_Parser*)data);
    property_stack->pop();
}

void char_hndl(void *data, const char *txt, int txtlen)
{
    stack<Property *> *property_stack =
        (stack<Property *> *)XML_GetUserData((XML_Parser*)data);

    Property *cur = property_stack->top();
    cur->value().append(txt, txtlen);
}

bool load_property_from_xml(Property &p, string filename)
{
  XML_Parser parser = XML_ParserCreate(NULL);
  if (! parser)
    throw std::runtime_error("Couldn't allocate memory for xml parser");

  XML_UseParserAsHandlerArg(parser);
  XML_SetElementHandler(parser, start_hndl, end_hndl);
  XML_SetCharacterDataHandler(parser, char_hndl);

  ifstream fl;
  fl.open(filename.c_str());
  if(!fl.is_open())
    throw std::ios_base::failure("Error on open xml file: " + filename);

  stack<Property *> pstack;
  pstack.push(&p);

  XML_SetUserData(parser, (void*)&pstack);
  while(!fl.eof()) {
    string line;
    getline(fl, line);
    line=line + "\n";
    if (! XML_Parse(parser, line.c_str(), line.length(), fl.eof()))
      throw  std::ios_base::failure(filename + ": Parse error at line " +
          boost::lexical_cast<string>(XML_GetCurrentLineNumber(parser)) + "\n" +
          XML_ErrorString(XML_GetErrorCode(parser)));
  }
  fl.close();
  return true;
}

}}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//  $Id: vldapi.cpp,v 1.6 2006/01/20 01:22:54 dmouldin Exp $
//
//  Visual Leak Detector (Version 1.0)
//  Copyright (c) 2005 Dan Moulding
//
//  This program 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 program 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 program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  See COPYING.txt for the full terms of the GNU Lesser General Public License.
//
////////////////////////////////////////////////////////////////////////////////

#define VLDBUILD     // Declares that we are building Visual Leak Detector.
#include "vldint.h"  // Provides access to the Visual Leak Detector internals.
#include "vldheap.h" // Provides internal new and delete operators.

// Imported global variables.
extern VisualLeakDetector visualleakdetector;

////////////////////////////////////////////////////////////////////////////////
//
//  Visual Leak Detector APIs - see vldapi.h for each function's details
//

extern "C" __declspec(dllexport) VOID VLDDisable ()
{
    if (!visualleakdetector.enabled()) {
        // Already disabled for the current thread.
        return;
    }

    // Disable memory leak detection for the current thread.
    TlsSetValue(visualleakdetector.m_tlsindex, (LPVOID)VLD_TLS_DISABLED);
}

extern "C" __declspec(dllexport) VOID VLDEnable ()
{
    if (visualleakdetector.enabled()) {
        // Already enabled for the current thread.
        return;
    }

    // Enable memory leak detection for the current thread.
    TlsSetValue(visualleakdetector.m_tlsindex, (LPVOID)VLD_TLS_ENABLED);
    visualleakdetector.m_status &= ~VLD_STATUS_NEVER_ENABLED;
}
<commit_msg>The name of the VisualLeakDetector instance has been shortened to just "vld" for convenience. Updated thread-local storage so that multiple data items can be kept thread locally. Now there is an entire structure that is thread local.<commit_after>////////////////////////////////////////////////////////////////////////////////
//  $Id: vldapi.cpp,v 1.7 2006/01/27 23:06:12 dmouldin Exp $
//
//  Visual Leak Detector (Version 1.0)
//  Copyright (c) 2005 Dan Moulding
//
//  This program 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 program 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 program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  See COPYING.txt for the full terms of the GNU Lesser General Public License.
//
////////////////////////////////////////////////////////////////////////////////

#define VLDBUILD     // Declares that we are building Visual Leak Detector.
#include "vldint.h"  // Provides access to the Visual Leak Detector internals.
#include "vldheap.h" // Provides internal new and delete operators.

// Imported global variables.
extern VisualLeakDetector vld;
__declspec(thread) tls_t vldtls;

////////////////////////////////////////////////////////////////////////////////
//
//  Visual Leak Detector APIs - see vldapi.h for each function's details
//

extern "C" __declspec(dllexport) VOID VLDDisable ()
{
    if (!vld.enabled()) {
        // Already disabled for the current thread.
        return;
    }

    // Disable memory leak detection for the current thread.
    vldtls.status &= ~VLD_TLS_ENABLED;
}

extern "C" __declspec(dllexport) VOID VLDEnable ()
{
    if (vld.enabled()) {
        // Already enabled for the current thread.
        return;
    }

    // Enable memory leak detection for the current thread.
    vldtls.status |= VLD_TLS_ENABLED;
    vld.m_status &= ~VLD_STATUS_NEVER_ENABLED;
}
<|endoftext|>