<commit_before>#include "notificator.h"

#include <QMetaType>
#include <QVariant>
#include <QIcon>
#include <QApplication>
#include <QStyle>
#include <QByteArray>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QTemporaryFile>
#include <QImageWriter>

#ifdef USE_DBUS
#include <QtDBus/QtDBus>
#include <stdint.h>
#endif

#ifdef Q_OS_MAC
#include <ApplicationServices/ApplicationServices.h>
extern bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret);
#endif

// https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128
const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;

Notificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent):
    QObject(parent),
    parent(parent),
    programName(programName),
    mode(None),
    trayIcon(trayicon)
#ifdef USE_DBUS
    ,interface(0)
#endif
{
    if(trayicon && trayicon->supportsMessages())
    {
        mode = QSystemTray;
    }
#ifdef USE_DBUS
    interface = new QDBusInterface("org.freedesktop.Notifications",
          "/org/freedesktop/Notifications", "org.freedesktop.Notifications");
    if(interface->isValid())
    {
        mode = Freedesktop;
    }
#endif
#ifdef Q_OS_MAC
    // Check if Growl is installed (based on Qt's tray icon implementation)
    CFURLRef cfurl;
    OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
    if (status != kLSApplicationNotFoundErr) {
        CFBundleRef bundle = CFBundleCreate(0, cfurl);
        if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) {
            if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR("/Growl.app/")))
                mode = Growl13;
            else
                mode = Growl12;
        }
        CFRelease(cfurl);
        CFRelease(bundle);
    }
#endif
}

Notificator::~Notificator()
{
#ifdef USE_DBUS
    delete interface;
#endif
}

#ifdef USE_DBUS

// Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html
class FreedesktopImage
{
public:
    FreedesktopImage() {}
    FreedesktopImage(const QImage &img);

    static int metaType();

    // Image to variant that can be marshalled over DBus
    static QVariant toVariant(const QImage &img);

private:
    int width, height, stride;
    bool hasAlpha;
    int channels;
    int bitsPerSample;
    QByteArray image;

    friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i);
    friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i);
};

Q_DECLARE_METATYPE(FreedesktopImage);

// Image configuration settings
const int CHANNELS = 4;
const int BYTES_PER_PIXEL = 4;
const int BITS_PER_SAMPLE = 8;

FreedesktopImage::FreedesktopImage(const QImage &img):
    width(img.width()),
    height(img.height()),
    stride(img.width() * BYTES_PER_PIXEL),
    hasAlpha(true),
    channels(CHANNELS),
    bitsPerSample(BITS_PER_SAMPLE)
{
    // Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format
    QImage tmp = img.convertToFormat(QImage::Format_ARGB32);
    const uint32_t *data = reinterpret_cast<const uint32_t*>(tmp.constBits());

    unsigned int num_pixels = width * height;
    image.resize(num_pixels * BYTES_PER_PIXEL);

    for(unsigned int ptr = 0; ptr < num_pixels; ++ptr)
    {
        image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; // R
        image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8;  // G
        image[ptr*BYTES_PER_PIXEL+2] = data[ptr];       // B
        image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; // A
    }
}

QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i)
{
    a.beginStructure();
    a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;
    a.endStructure();
    return a;
}

const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i)
{
    a.beginStructure();
    a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;
    a.endStructure();
    return a;
}

int FreedesktopImage::metaType()
{
    return qDBusRegisterMetaType<FreedesktopImage>();
}

QVariant FreedesktopImage::toVariant(const QImage &img)
{
    FreedesktopImage fimg(img);
    return QVariant(FreedesktopImage::metaType(), &fimg);
}

void Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
    Q_UNUSED(cls);
    // Arguments for DBus call:
    QList<QVariant> args;

    // Program Name:
    args.append(programName);

    // Unique ID of this notification type:
    args.append(0U);

    // Application Icon, empty string
    args.append(QString());

    // Summary
    args.append(title);

    // Body
    args.append(text);

    // Actions (none, actions are deprecated)
    QStringList actions;
    args.append(actions);

    // Hints
    QVariantMap hints;

    // If no icon specified, set icon based on class
    QIcon tmpicon;
    if(icon.isNull())
    {
        QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
        switch(cls)
        {
        case Information: sicon = QStyle::SP_MessageBoxInformation; break;
        case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
        case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
        default: break;
        }
        tmpicon = QApplication::style()->standardIcon(sicon);
    }
    else
    {
        tmpicon = icon;
    }
    hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());
    args.append(hints);

    // Timeout (in msec)
    args.append(millisTimeout);

    // "Fire and forget"
    interface->callWithArgumentList(QDBus::NoBlock, "Notify", args);
}
#endif

void Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
    Q_UNUSED(icon);
    QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;
    switch(cls) // Set icon based on class
    {
    case Information: sicon = QSystemTrayIcon::Information; break;
    case Warning: sicon = QSystemTrayIcon::Warning; break;
    case Critical: sicon = QSystemTrayIcon::Critical; break;
    }
    trayIcon->showMessage(title, text, sicon, millisTimeout);
}

// Based on Qt's tray icon implementation
#ifdef Q_OS_MAC
void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)
{
    const QString script(
        "tell application \"%5\"\n"
        "  set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all)
        "  set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled)
        "  register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl
        "  notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification
        "end tell"
    );

    QString notificationApp(QApplication::applicationName());
    if (notificationApp.isEmpty())
        notificationApp = "Application";

    QPixmap notificationIconPixmap;
    if (icon.isNull()) { // If no icon specified, set icon based on class
        QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
        switch (cls)
        {
        case Information: sicon = QStyle::SP_MessageBoxInformation; break;
        case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
        case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
        }
        notificationIconPixmap = QApplication::style()->standardPixmap(sicon);
    }
    else {
        QSize size = icon.actualSize(QSize(48, 48));
        notificationIconPixmap = icon.pixmap(size);
    }

    QString notificationIcon;
    QTemporaryFile notificationIconFile;
    if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
        QImageWriter writer(&notificationIconFile, "PNG");
        if (writer.write(notificationIconPixmap.toImage()))
            notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName());
    }

    QString quotedTitle(title), quotedText(text);
    quotedTitle.replace("\\", "\\\\").replace("\"", "\\");
    quotedText.replace("\\", "\\\\").replace("\"", "\\");
    QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp");
    qt_mac_execute_apple_script(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp), 0);
}
#endif

void Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
    switch(mode)
    {
#ifdef USE_DBUS
    case Freedesktop:
        notifyDBus(cls, title, text, icon, millisTimeout);
        break;
#endif
    case QSystemTray:
        notifySystray(cls, title, text, icon, millisTimeout);
        break;
#ifdef Q_OS_MAC
    case Growl12:
    case Growl13:
        notifyGrowl(cls, title, text, icon);
        break;
#endif
    default:
        if(cls == Critical)
        {
            // Fall back to old fashioned pop-up dialog if critical and no other notification available
            QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);
        }
        break;
    }
}
<commit_msg>Freedesktop Fix<commit_after>#include "notificator.h"

#include <QMetaType>
#include <QVariant>
#include <QIcon>
#include <QApplication>
#include <QStyle>
#include <QByteArray>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QTemporaryFile>
#include <QImageWriter>

#ifdef USE_DBUS
#include <QtDBus/QtDBus>
#include <stdint.h>
#endif

#ifdef Q_OS_MAC
#include <ApplicationServices/ApplicationServices.h>
extern bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret);
#endif

// https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128
const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;

Notificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent):
    QObject(parent),
    parent(parent),
    programName(programName),
    mode(None),
    trayIcon(trayicon)
#ifdef USE_DBUS
    ,interface(0)
#endif
{
    if(trayicon && trayicon->supportsMessages())
    {
        mode = QSystemTray;
    }
#ifdef USE_DBUS
    interface = new QDBusInterface("org.freedesktop.Notifications",
          "/org/freedesktop/Notifications", "org.freedesktop.Notifications");
    if(interface->isValid())
    {
        mode = Freedesktop;
    }
#endif
#ifdef Q_OS_MAC
    // Check if Growl is installed (based on Qt's tray icon implementation)
    CFURLRef cfurl;
    OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
    if (status != kLSApplicationNotFoundErr) {
        CFBundleRef bundle = CFBundleCreate(0, cfurl);
        if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) {
            if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR("/Growl.app/")))
                mode = Growl13;
            else
                mode = Growl12;
        }
        CFRelease(cfurl);
        CFRelease(bundle);
    }
#endif
}

Notificator::~Notificator()
{
#ifdef USE_DBUS
    delete interface;
#endif
}

#ifdef USE_DBUS

// Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html
class FreedesktopImage
{
public:
    FreedesktopImage() {}
    FreedesktopImage(const QImage &img);

    static int metaType();

    // Image to variant that can be marshalled over DBus
    static QVariant toVariant(const QImage &img);

private:
    int width, height, stride;
    bool hasAlpha;
    int channels;
    int bitsPerSample;
    QByteArray image;

    friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i);
    friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i);
};

Q_DECLARE_METATYPE(FreedesktopImage);

// Image configuration settings
const int CHANNELS = 4;
const int BYTES_PER_PIXEL = 4;
const int BITS_PER_SAMPLE = 8;

FreedesktopImage::FreedesktopImage(const QImage &img):
    width(img.width()),
    height(img.height()),
    stride(img.width() * BYTES_PER_PIXEL),
    hasAlpha(true),
    channels(CHANNELS),
    bitsPerSample(BITS_PER_SAMPLE)
{
    // Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format
    QImage tmp = img.convertToFormat(QImage::Format_ARGB32);
    const uint32_t *data = reinterpret_cast<const uint32_t*>(tmp.bits());

    unsigned int num_pixels = width * height;
    image.resize(num_pixels * BYTES_PER_PIXEL);

    for(unsigned int ptr = 0; ptr < num_pixels; ++ptr)
    {
        image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; // R
        image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8;  // G
        image[ptr*BYTES_PER_PIXEL+2] = data[ptr];       // B
        image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; // A
    }
}

QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i)
{
    a.beginStructure();
    a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;
    a.endStructure();
    return a;
}

const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i)
{
    a.beginStructure();
    a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;
    a.endStructure();
    return a;
}

int FreedesktopImage::metaType()
{
    return qDBusRegisterMetaType<FreedesktopImage>();
}

QVariant FreedesktopImage::toVariant(const QImage &img)
{
    FreedesktopImage fimg(img);
    return QVariant(FreedesktopImage::metaType(), &fimg);
}

void Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
    Q_UNUSED(cls);
    // Arguments for DBus call:
    QList<QVariant> args;

    // Program Name:
    args.append(programName);

    // Unique ID of this notification type:
    args.append(0U);

    // Application Icon, empty string
    args.append(QString());

    // Summary
    args.append(title);

    // Body
    args.append(text);

    // Actions (none, actions are deprecated)
    QStringList actions;
    args.append(actions);

    // Hints
    QVariantMap hints;

    // If no icon specified, set icon based on class
    QIcon tmpicon;
    if(icon.isNull())
    {
        QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
        switch(cls)
        {
        case Information: sicon = QStyle::SP_MessageBoxInformation; break;
        case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
        case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
        default: break;
        }
        tmpicon = QApplication::style()->standardIcon(sicon);
    }
    else
    {
        tmpicon = icon;
    }
    hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());
    args.append(hints);

    // Timeout (in msec)
    args.append(millisTimeout);

    // "Fire and forget"
    interface->callWithArgumentList(QDBus::NoBlock, "Notify", args);
}
#endif

void Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
    Q_UNUSED(icon);
    QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;
    switch(cls) // Set icon based on class
    {
    case Information: sicon = QSystemTrayIcon::Information; break;
    case Warning: sicon = QSystemTrayIcon::Warning; break;
    case Critical: sicon = QSystemTrayIcon::Critical; break;
    }
    trayIcon->showMessage(title, text, sicon, millisTimeout);
}

// Based on Qt's tray icon implementation
#ifdef Q_OS_MAC
void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)
{
    const QString script(
        "tell application \"%5\"\n"
        "  set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all)
        "  set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled)
        "  register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl
        "  notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification
        "end tell"
    );

    QString notificationApp(QApplication::applicationName());
    if (notificationApp.isEmpty())
        notificationApp = "Application";

    QPixmap notificationIconPixmap;
    if (icon.isNull()) { // If no icon specified, set icon based on class
        QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
        switch (cls)
        {
        case Information: sicon = QStyle::SP_MessageBoxInformation; break;
        case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
        case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
        }
        notificationIconPixmap = QApplication::style()->standardPixmap(sicon);
    }
    else {
        QSize size = icon.actualSize(QSize(48, 48));
        notificationIconPixmap = icon.pixmap(size);
    }

    QString notificationIcon;
    QTemporaryFile notificationIconFile;
    if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
        QImageWriter writer(&notificationIconFile, "PNG");
        if (writer.write(notificationIconPixmap.toImage()))
            notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName());
    }

    QString quotedTitle(title), quotedText(text);
    quotedTitle.replace("\\", "\\\\").replace("\"", "\\");
    quotedText.replace("\\", "\\\\").replace("\"", "\\");
    QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp");
    qt_mac_execute_apple_script(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp), 0);
}
#endif

void Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
{
    switch(mode)
    {
#ifdef USE_DBUS
    case Freedesktop:
        notifyDBus(cls, title, text, icon, millisTimeout);
        break;
#endif
    case QSystemTray:
        notifySystray(cls, title, text, icon, millisTimeout);
        break;
#ifdef Q_OS_MAC
    case Growl12:
    case Growl13:
        notifyGrowl(cls, title, text, icon);
        break;
#endif
    default:
        if(cls == Critical)
        {
            // Fall back to old fashioned pop-up dialog if critical and no other notification available
            QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);
        }
        break;
    }
}
<|endoftext|>


<commit_before>/**
 *
 *  \file evaluator_proxy.cc
 *  \remark This file is part of VITA.
 *
 *  Copyright (C) 2011-2013 EOS di Manlio Morini.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this file,
 *  You can obtain one at http://mozilla.org/MPL/2.0/
 *
 */

#include "evaluator_proxy.h"
#include "individual.h"
#include "lambda_f.h"

namespace vita
{
  ///
  /// \param[in] eva pointer that lets the proxy access the real evaluator.
  /// \param[in] ts 2^\a ts is the number of elements of the cache.
  ///
  evaluator_proxy::evaluator_proxy(const evaluator::ptr &eva, unsigned ts)
    : eva_(eva), cache_(ts)
  {
    assert(eva);
    assert(ts > 6);
  }

  ///
  /// \param[in] ind the individual whose fitness we want to know.
  /// \return the fitness and the accuracy of \a ind.
  ///
  fitness_t evaluator_proxy::operator()(const individual &ind)
  {
    fitness_t f;
    if (!cache_.find(ind, &f))
    {
      f = (*eva_)(ind);

      cache_.insert(ind, f);

#if !defined(NDEBUG)
      fitness_t f1;
      assert(cache_.find(ind, &f1));
      assert(f == f1);
#endif
    }
#if !defined(NDEBUG)
    else  // hash collision checking code can slow down the program very much
    {
      const fitness_t f1((*eva_)(ind));
      if (f != f1)
        std::cerr << "********* COLLISION ********* [" << f
                  << " != " << f1 << "]" << std::endl;
    }
#endif

    return f;
  }

  ///
  /// \param[in] what what should be cleared? (all, cache, stats)
  ///
  /// \brief Resets the evaluation cache / clear the statistics.
  ///
  void evaluator_proxy::clear(unsigned what)
  {
    switch (what)
    {
    case all:
    case cache:
      cache_.clear();
      break;

    case stats:
      cache_.reset_seen();
    }
  }

  ///
  /// \param[in] ind an individual.
  ///
  /// Clears the cached informations for individual \a ind.
  ///
  void evaluator_proxy::clear(const individual &ind)
  {
    cache_.clear(ind);
  }

  double evaluator_proxy::accuracy(const individual &ind) const
  {
    return eva_->accuracy(ind);
  }

  ///
  /// \return number of cache probes / hits.
  ///
  std::string evaluator_proxy::info() const
  {
    return
      "hits " + boost::lexical_cast<std::string>(cache_.hits()) +
      ", probes " + boost::lexical_cast<std::string>(cache_.probes()) +
      " (ratio " +
      boost::lexical_cast<std::string>(cache_.hits() * 100 / cache_.probes()) +
      "%)";
  }

  ///
  /// \param[in] ind an individual.
  /// \return a pointer to the executable version of \a ind.
  ///
  std::unique_ptr<lambda_f> evaluator_proxy::lambdify(
    const individual &ind) const
  {
    return eva_->lambdify(ind);
  }
}  // namespace vita
<commit_msg>Fixed bug in collision detection<commit_after>/**
 *
 *  \file evaluator_proxy.cc
 *  \remark This file is part of VITA.
 *
 *  Copyright (C) 2011-2013 EOS di Manlio Morini.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this file,
 *  You can obtain one at http://mozilla.org/MPL/2.0/
 *
 */

#include "evaluator_proxy.h"
#include "individual.h"
#include "lambda_f.h"

namespace vita
{
  ///
  /// \param[in] eva pointer that lets the proxy access the real evaluator.
  /// \param[in] ts 2^\a ts is the number of elements of the cache.
  ///
  evaluator_proxy::evaluator_proxy(const evaluator::ptr &eva, unsigned ts)
    : eva_(eva), cache_(ts)
  {
    assert(eva);
    assert(ts > 6);
  }

  ///
  /// \param[in] ind the individual whose fitness we want to know.
  /// \return the fitness and the accuracy of \a ind.
  ///
  fitness_t evaluator_proxy::operator()(const individual &ind)
  {
    fitness_t f;
    if (!cache_.find(ind, &f))
    {
      f = (*eva_)(ind);

      cache_.insert(ind, f);

#if !defined(NDEBUG)
      fitness_t f1;
      assert(cache_.find(ind, &f1));
      assert(f == f1);
#endif
    }
#if !defined(NDEBUG)
    else  // hash collision checking code can slow down the program very much
    {
      const fitness_t f1((*eva_)(ind));
      if (f[0] != f1[0])
        std::cerr << "********* COLLISION ********* [" << f
                  << " != " << f1 << "]" << std::endl;

      // In the above comparison we consider only the first component of the
      // fitness otherwise we can have false positives.
      // For example if the fitness is a 2D vector (where the first component
      // is the "score" on the training set and the second one is the effective
      // length of the individual), then the following two individuals:
      //
      // INDIVIDUAL A              INDIVIDUAL B
      // ------------------        ------------------
      // [000] FADD 001 002        [000] FADD 001 001
      // [001] X1                  [001] X1
      // [002] X1
      //
      // have the same signature, the same stored "score" but distinct
      // effective size and so distinct fitnesses.
    }
#endif

    return f;
  }

  ///
  /// \param[in] what what should be cleared? (all, cache, stats)
  ///
  /// \brief Resets the evaluation cache / clear the statistics.
  ///
  void evaluator_proxy::clear(unsigned what)
  {
    switch (what)
    {
    case all:
    case cache:
      cache_.clear();
      break;

    case stats:
      cache_.reset_seen();
    }
  }

  ///
  /// \param[in] ind an individual.
  ///
  /// Clears the cached informations for individual \a ind.
  ///
  void evaluator_proxy::clear(const individual &ind)
  {
    cache_.clear(ind);
  }

  double evaluator_proxy::accuracy(const individual &ind) const
  {
    return eva_->accuracy(ind);
  }

  ///
  /// \return number of cache probes / hits.
  ///
  std::string evaluator_proxy::info() const
  {
    return
      "hits " + boost::lexical_cast<std::string>(cache_.hits()) +
      ", probes " + boost::lexical_cast<std::string>(cache_.probes()) +
      " (ratio " +
      boost::lexical_cast<std::string>(cache_.hits() * 100 / cache_.probes()) +
      "%)";
  }

  ///
  /// \param[in] ind an individual.
  /// \return a pointer to the executable version of \a ind.
  ///
  std::unique_ptr<lambda_f> evaluator_proxy::lambdify(
    const individual &ind) const
  {
    return eva_->lambdify(ind);
  }
}  // namespace vita
<|endoftext|>


<commit_before>#define NO_GLOBALS
#include "harlan.hpp"

#include <stdlib.h>
#include <limits.h>
#include <string>
#include <algorithm>

using namespace std;

#define ALLOC_MAGIC 0xa110ca7e

#define CHECK_MAGIC(hdr) assert((hdr)->magic == ALLOC_MAGIC)

void check_region(region *r) {
    CHECK_MAGIC(r);
    //assert(r->cl_buffer);
}

void print(bool b, std::ostream *f) {
    if(b)
        print("#t", f);
    else
        print("#f", f);
}

void harlan_error(const char *msg) {
    std::cerr << "Harlan Runtime Error: " << msg << std::endl;
    abort();
}

cl_device_type get_device_type()
{
  const char *cfg = getenv("HARLAN_DEVICE");

  if(cfg) {
    string s = cfg;
	transform(s.begin(), s.end(), s.begin(), ::tolower);
    if(s == "gpu") {
      return CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR;
    }
    else if(s == "cpu") {
      return CL_DEVICE_TYPE_CPU;
    }
	else {
		cerr << "HARLAN_DEVICE must be either `cpu` or `gpu`." << endl;
		abort();
	}
  }
  return (CL_DEVICE_TYPE_GPU |
          CL_DEVICE_TYPE_CPU |
          CL_DEVICE_TYPE_ACCELERATOR |
          0);
}

int get_default_region_size()
{
  const char *cfg = getenv("HARLAN_MIN_REGION_SIZE");

  if(cfg) {
	  int sz = atoi(cfg);
	  cerr << "Setting region size from HARLAN_MIN_REGION_SIZE to "
		   << sz << " bytes." << endl;
      return sz;
  }
  //else return 8192;
  else return 8 << 20; // 8 megs
}

region *create_region(int size)
{
    if(size == -1) size = get_default_region_size();

    assert(size > sizeof(region));

    // void *ptr = GC_MALLOC(size);
    void *ptr = malloc(size);

    region *header = (region *)ptr;
    header->magic = ALLOC_MAGIC;
    header->size = size;
    header->alloc_ptr = sizeof(region);
    header->cl_buffer = NULL;

    check_region(header);

    return header;
}

void free_region(region *r)
{
    //fprintf(stderr, "freeing region %p. %d bytes allocated\n",
    //        r, r->alloc_ptr);
    if(r->cl_buffer) {
        clReleaseMemObject((cl_mem)r->cl_buffer);
    }
    free(r);
}

void map_region(region *header)
{
    cl_int status = 0;

    assert(header->cl_buffer);

    cl_mem buffer = (cl_mem)header->cl_buffer;

    //printf("map_region: old alloc_ptr = %d\n", header->alloc_ptr);

    // Read just the header
    status = clEnqueueReadBuffer(g_queue,
                                 buffer,
                                 CL_TRUE,
                                 0,
                                 sizeof(region),
                                 header,
                                 0,
                                 NULL,
                                 NULL);
    CL_CHECK(status);

    //printf("map_region: new alloc_ptr = %d\n", header->alloc_ptr);

    //printf("map_region: read %lu bytes, reading %lu more.\n",
    //       sizeof(region), header->alloc_ptr - sizeof(region));

    // Now read the contents
    status = clEnqueueReadBuffer(g_queue,
                                 buffer,
                                 CL_TRUE,
                                 sizeof(region),
                                 header->alloc_ptr - sizeof(region),
                                 ((char *)header) + sizeof(region),
                                 0,
                                 NULL,
                                 NULL);
    CL_CHECK(status);

    CL_CHECK(clReleaseMemObject(buffer));
    assert(!header->cl_buffer);
    check_region(header);
}

void unmap_region(region *header)
{
    check_region(header);

    // Don't unmap the region twice...
    // TODO: we might want to report a warning in this case.
    if(header->cl_buffer) return;
    //assert(!header->cl_buffer);

    //fprintf(stderr, "unmap_region %p, alloc_ptr = %d\n",
    //        header, header->alloc_ptr);

    cl_int status = 0;
    cl_mem buffer = clCreateBuffer(g_ctx,
                                   CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR,
                                   header->size,
                                   NULL,
                                   &status);
    CL_CHECK(status);

    status = clEnqueueWriteBuffer(g_queue,
                                  buffer,
                                  CL_TRUE,
                                  0,
                                  header->alloc_ptr,
                                  header,
                                  0,
                                  NULL,
                                  NULL);
    CL_CHECK(status);

    header->cl_buffer = buffer;
}

region_ptr alloc_in_region(region **r, unsigned int size)
{
    if((*r)->cl_buffer)
        map_region(*r);

    // printf("allocating %d bytes from region %p\n", size, *r);
    region_ptr p = (*r)->alloc_ptr;
    (*r)->alloc_ptr += size;

    // If this fails, we allocated too much memory and need to resize
    // the region.
    while((*r)->alloc_ptr > (*r)->size) {
        unsigned int new_size = (*r)->size * 2;
		// As long as we stick with power of two region sizes, this
		// will let us get up to 4GB regions. It's a big of a hacky
		// special case...
		if(new_size == 0) {
		  new_size = UINT_MAX;
		}
		assert(new_size > (*r)->size);
        region *old = *r;
        unsigned int old_size = (*r)->size;
		//printf("realloc(%p, %d)\n", *r, new_size);
        (*r) = (region *)realloc(*r, new_size);

		assert(*r != NULL);

        (*r)->size = new_size;
    }

    return p;
}

cl_mem get_cl_buffer(region *r)
{
    assert(r->cl_buffer);
    return (cl_mem)r->cl_buffer;
}

int ARGC = 0;
char **ARGV = NULL;

extern int harlan_main();

int main(int argc, char **argv) {
	ARGC = argc;
	ARGV = argv;

	return harlan_main();
}
<commit_msg>Only report the minimum region size once when controlled by an environment variable.<commit_after>#define NO_GLOBALS
#include "harlan.hpp"

#include <stdlib.h>
#include <limits.h>
#include <string>
#include <algorithm>

using namespace std;

#define ALLOC_MAGIC 0xa110ca7e

#define CHECK_MAGIC(hdr) assert((hdr)->magic == ALLOC_MAGIC)

void check_region(region *r) {
    CHECK_MAGIC(r);
    //assert(r->cl_buffer);
}

void print(bool b, std::ostream *f) {
    if(b)
        print("#t", f);
    else
        print("#f", f);
}

void harlan_error(const char *msg) {
    std::cerr << "Harlan Runtime Error: " << msg << std::endl;
    abort();
}

cl_device_type get_device_type()
{
  const char *cfg = getenv("HARLAN_DEVICE");

  if(cfg) {
    string s = cfg;
	transform(s.begin(), s.end(), s.begin(), ::tolower);
    if(s == "gpu") {
      return CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR;
    }
    else if(s == "cpu") {
      return CL_DEVICE_TYPE_CPU;
    }
	else {
		cerr << "HARLAN_DEVICE must be either `cpu` or `gpu`." << endl;
		abort();
	}
  }
  return (CL_DEVICE_TYPE_GPU |
          CL_DEVICE_TYPE_CPU |
          CL_DEVICE_TYPE_ACCELERATOR |
          0);
}

int get_default_region_size()
{
    static bool first_time = true;

    const char *cfg = getenv("HARLAN_MIN_REGION_SIZE");

    if(cfg) {
        int sz = atoi(cfg);
        if(first_time) {
            cerr << "Setting region size from HARLAN_MIN_REGION_SIZE to "
                 << sz << " bytes." << endl;
            first_time = false;
        }
        return sz;
    }
    //else return 8192;
    else return 8 << 20; // 8 megs
}

region *create_region(int size)
{
    if(size == -1) size = get_default_region_size();

    assert(size > sizeof(region));

    // void *ptr = GC_MALLOC(size);
    void *ptr = malloc(size);

    region *header = (region *)ptr;
    header->magic = ALLOC_MAGIC;
    header->size = size;
    header->alloc_ptr = sizeof(region);
    header->cl_buffer = NULL;

    check_region(header);

    return header;
}

void free_region(region *r)
{
    //fprintf(stderr, "freeing region %p. %d bytes allocated\n",
    //        r, r->alloc_ptr);
    if(r->cl_buffer) {
        clReleaseMemObject((cl_mem)r->cl_buffer);
    }
    free(r);
}

void map_region(region *header)
{
    cl_int status = 0;

    assert(header->cl_buffer);

    cl_mem buffer = (cl_mem)header->cl_buffer;

    //printf("map_region: old alloc_ptr = %d\n", header->alloc_ptr);

    // Read just the header
    status = clEnqueueReadBuffer(g_queue,
                                 buffer,
                                 CL_TRUE,
                                 0,
                                 sizeof(region),
                                 header,
                                 0,
                                 NULL,
                                 NULL);
    CL_CHECK(status);

    //printf("map_region: new alloc_ptr = %d\n", header->alloc_ptr);

    //printf("map_region: read %lu bytes, reading %lu more.\n",
    //       sizeof(region), header->alloc_ptr - sizeof(region));

    // Now read the contents
    status = clEnqueueReadBuffer(g_queue,
                                 buffer,
                                 CL_TRUE,
                                 sizeof(region),
                                 header->alloc_ptr - sizeof(region),
                                 ((char *)header) + sizeof(region),
                                 0,
                                 NULL,
                                 NULL);
    CL_CHECK(status);

    CL_CHECK(clReleaseMemObject(buffer));
    assert(!header->cl_buffer);
    check_region(header);
}

void unmap_region(region *header)
{
    check_region(header);

    // Don't unmap the region twice...
    // TODO: we might want to report a warning in this case.
    if(header->cl_buffer) return;
    //assert(!header->cl_buffer);

    //fprintf(stderr, "unmap_region %p, alloc_ptr = %d\n",
    //        header, header->alloc_ptr);

    cl_int status = 0;
    cl_mem buffer = clCreateBuffer(g_ctx,
                                   CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR,
                                   header->size,
                                   NULL,
                                   &status);
    CL_CHECK(status);

    status = clEnqueueWriteBuffer(g_queue,
                                  buffer,
                                  CL_TRUE,
                                  0,
                                  header->alloc_ptr,
                                  header,
                                  0,
                                  NULL,
                                  NULL);
    CL_CHECK(status);

    header->cl_buffer = buffer;
}

region_ptr alloc_in_region(region **r, unsigned int size)
{
    if((*r)->cl_buffer)
        map_region(*r);

    // printf("allocating %d bytes from region %p\n", size, *r);
    region_ptr p = (*r)->alloc_ptr;
    (*r)->alloc_ptr += size;

    // If this fails, we allocated too much memory and need to resize
    // the region.
    while((*r)->alloc_ptr > (*r)->size) {
        unsigned int new_size = (*r)->size * 2;
		// As long as we stick with power of two region sizes, this
		// will let us get up to 4GB regions. It's a big of a hacky
		// special case...
		if(new_size == 0) {
		  new_size = UINT_MAX;
		}
		assert(new_size > (*r)->size);
        region *old = *r;
        unsigned int old_size = (*r)->size;
		//printf("realloc(%p, %d)\n", *r, new_size);
        (*r) = (region *)realloc(*r, new_size);

		assert(*r != NULL);

        (*r)->size = new_size;
    }

    return p;
}

cl_mem get_cl_buffer(region *r)
{
    assert(r->cl_buffer);
    return (cl_mem)r->cl_buffer;
}

int ARGC = 0;
char **ARGV = NULL;

extern int harlan_main();

int main(int argc, char **argv) {
	ARGC = argc;
	ARGV = argv;

	return harlan_main();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: setup.hxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "setup_main.hxx"

//--------------------------------------------------------------------------

#ifdef SetupAppX
 #undef SetupAppX
#endif

#ifdef Create_SetupAppX
 #undef Create_SetupAppX
#endif

#ifdef LanguageDataX
 #undef LanguageDataX
#endif

#ifdef UNICODE
 #define SetupAppX          SetupAppW
 #define Create_SetupAppX   Create_SetupAppW
 #define LanguageDataX      LanguageDataW
#else
 #define SetupAppX          SetupAppA
 #define Create_SetupAppX   Create_SetupAppA
 #define LanguageDataX      LanguageDataA
#endif

//--------------------------------------------------------------------------

struct LanguageDataX
{
    long    m_nLanguageID;
    LPTSTR  m_pTransform;

     LanguageDataX( LPTSTR pData );
    ~LanguageDataX();
};

//--------------------------------------------------------------------------

class SetupAppX : public SetupApp
{
    HINSTANCE   m_hInst;
    HANDLE      m_hMapFile;
    LPTSTR      m_pAppTitle;
    LPTSTR      m_pCmdLine;
    LPTSTR      m_pDatabase;
    LPTSTR      m_pInstMsiW;
    LPTSTR      m_pInstMsiA;
    LPTSTR      m_pReqVersion;
    LPTSTR      m_pProductName;
    LPTSTR      m_pAdvertise;
    LPTSTR      m_pTmpName;
    LPTSTR      m_pErrorText;
    LPTSTR      m_pModuleFile;
    int        *m_pMSIErrorCode;

    boolean     m_bQuiet            : 1;
    boolean     m_bAdministrative   : 1;
    boolean     m_bIgnoreAlreadyRunning : 1;

    FILE       *m_pLogFile;

    long            m_nLanguageID;
    long            m_nLanguageCount;
    LanguageDataX** m_ppLanguageList;

private:

    boolean     GetPathToFile( TCHAR* pFileName, TCHAR **pPath );
    LPCTSTR     GetPathToMSI();

    int         GetNameValue( TCHAR* pLine, TCHAR **pName, TCHAR **pValue );
    boolean     GetProfileSection( LPCTSTR pFileName, LPCTSTR pSection,
                                   DWORD& rSize, LPTSTR *pRetBuf );
    LPTSTR      CopyIniFile( LPCTSTR pIniFile );
    void        ConvertNewline( LPTSTR pText ) const;

    boolean     LaunchInstaller( LPCTSTR pParam );
    HMODULE     LoadMsiLibrary();
    DWORD       WaitForProcess( HANDLE hHandle );

    boolean     GetCmdLineParameters( LPTSTR *pCmdLine );
    DWORD       GetNextArgument( LPCTSTR pStr, LPTSTR *pArg,
                                 LPTSTR *pNext, boolean bStripQuotes = false );
    boolean     IsAdmin();

    boolean     GetCommandLine();
    boolean     InstallMsi( LPCTSTR pInstaller );

    boolean     IsTerminalServerInstalled() const;

public:
                    SetupAppX();
                   ~SetupAppX();

    virtual boolean Initialize( HINSTANCE hInst );
    virtual boolean AlreadyRunning() const;
    virtual boolean ReadProfile();
    virtual boolean ChooseLanguage( long& rLanguage );
    virtual boolean CheckVersion();
    virtual boolean Install( long nLanguage );

    virtual UINT    GetError() const;
    virtual void    DisplayError( UINT nErr ) const;

    void            Log( LPCTSTR pMessage, LPCTSTR pText = NULL ) const;

    long            GetLanguageCount() const { return m_nLanguageCount; }
    long            GetLanguageID( long nIndex ) const;
    void            GetLanguageName( long nLanguage, LPTSTR sName ) const;

    LPCTSTR         GetAppTitle() const { return m_pAppTitle; }
    LPTSTR          SetProdToAppTitle( LPCTSTR pProdName );
    HINSTANCE       GetHInst() const { return m_hInst; }
};

//--------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS sysui26 (1.10.74); FILE MERGED 2008/07/03 14:42:02 dv 1.10.74.1: Allow setting of msi properties for mso file types<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: setup.hxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "setup_main.hxx"

//--------------------------------------------------------------------------

#ifdef SetupAppX
 #undef SetupAppX
#endif

#ifdef Create_SetupAppX
 #undef Create_SetupAppX
#endif

#ifdef LanguageDataX
 #undef LanguageDataX
#endif

#ifdef UNICODE
 #define SetupAppX          SetupAppW
 #define Create_SetupAppX   Create_SetupAppW
 #define LanguageDataX      LanguageDataW
#else
 #define SetupAppX          SetupAppA
 #define Create_SetupAppX   Create_SetupAppA
 #define LanguageDataX      LanguageDataA
#endif

//--------------------------------------------------------------------------

struct LanguageDataX
{
    long    m_nLanguageID;
    LPTSTR  m_pTransform;

     LanguageDataX( LPTSTR pData );
    ~LanguageDataX();
};

//--------------------------------------------------------------------------

class SetupAppX : public SetupApp
{
    HINSTANCE   m_hInst;
    HANDLE      m_hMapFile;
    LPTSTR      m_pAppTitle;
    LPTSTR      m_pCmdLine;
    LPTSTR      m_pDatabase;
    LPTSTR      m_pInstMsiW;
    LPTSTR      m_pInstMsiA;
    LPTSTR      m_pReqVersion;
    LPTSTR      m_pProductName;
    LPTSTR      m_pAdvertise;
    LPTSTR      m_pTmpName;
    LPTSTR      m_pErrorText;
    LPTSTR      m_pModuleFile;
    int        *m_pMSIErrorCode;

    boolean     m_bQuiet            : 1;
    boolean     m_bAdministrative   : 1;
    boolean     m_bIgnoreAlreadyRunning : 1;
    boolean     m_bRegNoMsoTypes :1;
    boolean     m_bRegAllMsoTypes :1;

    FILE       *m_pLogFile;

    long            m_nLanguageID;
    long            m_nLanguageCount;
    LanguageDataX** m_ppLanguageList;

private:

    boolean     GetPathToFile( TCHAR* pFileName, TCHAR **pPath );
    LPCTSTR     GetPathToMSI();

    int         GetNameValue( TCHAR* pLine, TCHAR **pName, TCHAR **pValue );
    boolean     GetProfileSection( LPCTSTR pFileName, LPCTSTR pSection,
                                   DWORD& rSize, LPTSTR *pRetBuf );
    LPTSTR      CopyIniFile( LPCTSTR pIniFile );
    void        ConvertNewline( LPTSTR pText ) const;

    boolean     LaunchInstaller( LPCTSTR pParam );
    HMODULE     LoadMsiLibrary();
    DWORD       WaitForProcess( HANDLE hHandle );

    boolean     GetCmdLineParameters( LPTSTR *pCmdLine );
    DWORD       GetNextArgument( LPCTSTR pStr, LPTSTR *pArg,
                                 LPTSTR *pNext, boolean bStripQuotes = false );
    boolean     IsAdmin();

    boolean     GetCommandLine();
    boolean     InstallMsi( LPCTSTR pInstaller );

    boolean     IsTerminalServerInstalled() const;

public:
                    SetupAppX();
                   ~SetupAppX();

    virtual boolean Initialize( HINSTANCE hInst );
    virtual boolean AlreadyRunning() const;
    virtual boolean ReadProfile();
    virtual boolean ChooseLanguage( long& rLanguage );
    virtual boolean CheckVersion();
    virtual boolean Install( long nLanguage );

    virtual UINT    GetError() const;
    virtual void    DisplayError( UINT nErr ) const;

    void            Log( LPCTSTR pMessage, LPCTSTR pText = NULL ) const;

    long            GetLanguageCount() const { return m_nLanguageCount; }
    long            GetLanguageID( long nIndex ) const;
    void            GetLanguageName( long nLanguage, LPTSTR sName ) const;

    LPCTSTR         GetAppTitle() const { return m_pAppTitle; }
    LPTSTR          SetProdToAppTitle( LPCTSTR pProdName );
    HINSTANCE       GetHInst() const { return m_hInst; }
};

//--------------------------------------------------------------------------
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: nodeconverter.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 04:18:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>

#include "nodeconverter.hxx"

#ifndef CONFIGMGR_TREE_NODEFACTORY_HXX
#include "treenodefactory.hxx"
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

//..........................................................................
namespace configmgr
{

//==========================================================================
//= OTreeNodeConverter
//==========================================================================
OTreeNodeConverter::OTreeNodeConverter()
: m_rFactory( getDefaultTreeNodeFactory() )
{
}

std::auto_ptr<ISubtree>  OTreeNodeConverter::createCorrespondingNode(SubtreeChange const& _rChange)
{
    std::auto_ptr<ISubtree> aRet;

    //if ( isLocalizedValueSet(aSubtree) ) { ... } else - no special case yet
    if (_rChange.isSetNodeChange())
    {
        aRet = nodeFactory().createSetNode(_rChange.getNodeName(),
                                       _rChange.getElementTemplateName(),
                                       _rChange.getElementTemplateModule(),
                                       _rChange.getAttributes());
    }
    else
    {
        aRet = nodeFactory().createGroupNode(_rChange.getNodeName(),
                                           _rChange.getAttributes());
    }
    return aRet;
}

//--------------------------------------------------------------------------
std::auto_ptr<ValueNode> OTreeNodeConverter::createCorrespondingNode(ValueChange const&  _rChange)
{
   // DEFAULT-TODO
    OSL_ENSURE(_rChange.getValueType().getTypeClass() != uno::TypeClass_VOID, "Losing type information converting change to value");

    std::auto_ptr<ValueNode> aRet;
    if (_rChange.getNewValue().hasValue())
       aRet = nodeFactory().createValueNode(_rChange.getNodeName(), _rChange.getNewValue(), _rChange.getAttributes());

    else
       aRet = nodeFactory().createNullValueNode(_rChange.getNodeName(), _rChange.getValueType(), _rChange.getAttributes());

    OSL_ENSURE(aRet.get() && aRet->isValid(), "Could not create corresponding value node");

    return aRet;
}

//==========================================================================
//= ONodeConverter
//==========================================================================
class ONodeConverter : public ChangeTreeModification
{
    OTreeNodeConverter&     m_rFactory;
    std::auto_ptr<INode>    m_pNode;

public:
    explicit
    ONodeConverter(OTreeNodeConverter& rFactory)
        : m_rFactory(rFactory)
    {
    }

    virtual void handle(ValueChange& aValueNode);
    virtual void handle(AddNode& aAddNode);
    virtual void handle(RemoveNode& aRemoveNode);
    virtual void handle(SubtreeChange& aSubtree);

    std::auto_ptr<INode> result() { return m_pNode; }

};
//==========================================================================
//= OCreateSubtreeAction
//==========================================================================
//= creates a subtree out of a changes list
//==========================================================================
struct OCreateSubtreeAction : public ChangeTreeModification
{
    ISubtree&           m_rTree;
    OTreeNodeConverter& m_rNodeFactory;

public:
    OCreateSubtreeAction(ISubtree& _rTree, OTreeNodeConverter& rFactory)
        :m_rTree(_rTree)
        ,m_rNodeFactory(rFactory) {}

    void handle(ValueChange& aValueNode);
    void handle(AddNode& aAddNode);
    void handle(RemoveNode& aRemoveNode);
    void handle(SubtreeChange& aSubtree);
};

//--------------------------------------------------------------------------
std::auto_ptr<INode> OTreeNodeConverter::createCorrespondingNode(Change& _rChange)
{
    ONodeConverter aAction(*this);
    aAction.applyToChange(_rChange);
    return aAction.result();
}

//--------------------------------------------------------------------------
std::auto_ptr<ISubtree> OTreeNodeConverter::createCorrespondingTree(SubtreeChange& _rChange)
{
    std::auto_ptr<ISubtree> pBaseTree = this->createCorrespondingNode(_rChange);

    OCreateSubtreeAction aNextLevel(*pBaseTree,*this);
    _rChange.forEachChange(aNextLevel);

    return pBaseTree;
}

//--------------------------------------------------------------------------
void ONodeConverter::handle(ValueChange& aValueNode)
{
    m_pNode = base_ptr(m_rFactory.createCorrespondingNode(aValueNode));
}

//--------------------------------------------------------------------------
void ONodeConverter::handle(AddNode& aAddNode)
{
    m_pNode = aAddNode.getNewTree().cloneData(true);
}

//--------------------------------------------------------------------------
void ONodeConverter::handle(RemoveNode& aRemoveNode)
{
    m_pNode.reset();
}

//--------------------------------------------------------------------------
void ONodeConverter::handle(SubtreeChange& aSubtree)
{
    m_pNode = base_ptr(m_rFactory.createCorrespondingNode(aSubtree));
}

//--------------------------------------------------------------------------
void OCreateSubtreeAction::handle(ValueChange& _rChange)
{
    // create a node by a ValueChange
    std::auto_ptr<ValueNode> pNode = m_rNodeFactory.createCorrespondingNode(_rChange);

    m_rTree.addChild(base_ptr(pNode));
}

//--------------------------------------------------------------------------
void OCreateSubtreeAction::handle(SubtreeChange& _rChange)
{
    // create a node from a SubtreeChange (recursively)
    std::auto_ptr<ISubtree> pNode = m_rNodeFactory.createCorrespondingTree(_rChange);

    // add it to the tree
    m_rTree.addChild(base_ptr(pNode));
}

//--------------------------------------------------------------------------
void OCreateSubtreeAction::handle(RemoveNode& _rChange)
{
    // we have nothing to do
    OSL_ENSURE(!m_rTree.getChild(_rChange.getNodeName()), "Removed node found in tree being built");
}

//--------------------------------------------------------------------------
void OCreateSubtreeAction::handle(AddNode& _rChange)
{
    // free the node and add it to the subtree
    data::TreeSegment aNewNode = _rChange.getNewTree();
    m_rTree.addChild(aNewNode.cloneData(true));
}

//--------------------------------------------------------------------------

//..........................................................................
}   // namespace configmgr
//..........................................................................

<commit_msg>INTEGRATION: CWS warnings01 (1.3.4); FILE MERGED 2005/11/01 12:47:32 cd 1.3.4.1: #i53898# Warning free code for sun solaris compiler<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: nodeconverter.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 23:29:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>

#include "nodeconverter.hxx"

#ifndef CONFIGMGR_TREE_NODEFACTORY_HXX
#include "treenodefactory.hxx"
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

//..........................................................................
namespace configmgr
{

//==========================================================================
//= OTreeNodeConverter
//==========================================================================
OTreeNodeConverter::OTreeNodeConverter()
: m_rFactory( getDefaultTreeNodeFactory() )
{
}

std::auto_ptr<ISubtree>  OTreeNodeConverter::createCorrespondingNode(SubtreeChange const& _rChange)
{
    std::auto_ptr<ISubtree> aRet;

    //if ( isLocalizedValueSet(aSubtree) ) { ... } else - no special case yet
    if (_rChange.isSetNodeChange())
    {
        aRet = nodeFactory().createSetNode(_rChange.getNodeName(),
                                       _rChange.getElementTemplateName(),
                                       _rChange.getElementTemplateModule(),
                                       _rChange.getAttributes());
    }
    else
    {
        aRet = nodeFactory().createGroupNode(_rChange.getNodeName(),
                                           _rChange.getAttributes());
    }
    return aRet;
}

//--------------------------------------------------------------------------
std::auto_ptr<ValueNode> OTreeNodeConverter::createCorrespondingNode(ValueChange const&  _rChange)
{
   // DEFAULT-TODO
    OSL_ENSURE(_rChange.getValueType().getTypeClass() != uno::TypeClass_VOID, "Losing type information converting change to value");

    std::auto_ptr<ValueNode> aRet;
    if (_rChange.getNewValue().hasValue())
       aRet = nodeFactory().createValueNode(_rChange.getNodeName(), _rChange.getNewValue(), _rChange.getAttributes());

    else
       aRet = nodeFactory().createNullValueNode(_rChange.getNodeName(), _rChange.getValueType(), _rChange.getAttributes());

    OSL_ENSURE(aRet.get() && aRet->isValid(), "Could not create corresponding value node");

    return aRet;
}

//==========================================================================
//= ONodeConverter
//==========================================================================
class ONodeConverter : public ChangeTreeModification
{
    OTreeNodeConverter&     m_rFactory;
    std::auto_ptr<INode>    m_pNode;

public:
    explicit
    ONodeConverter(OTreeNodeConverter& rFactory)
        : m_rFactory(rFactory)
    {
    }

    virtual void handle(ValueChange& aValueNode);
    virtual void handle(AddNode& aAddNode);
    virtual void handle(RemoveNode& aRemoveNode);
    virtual void handle(SubtreeChange& aSubtree);

    std::auto_ptr<INode> result() { return m_pNode; }

};
//==========================================================================
//= OCreateSubtreeAction
//==========================================================================
//= creates a subtree out of a changes list
//==========================================================================
struct OCreateSubtreeAction : public ChangeTreeModification
{
    ISubtree&           m_rTree;
    OTreeNodeConverter& m_rNodeFactory;

public:
    OCreateSubtreeAction(ISubtree& _rTree, OTreeNodeConverter& rFactory)
        :m_rTree(_rTree)
        ,m_rNodeFactory(rFactory) {}

    void handle(ValueChange& aValueNode);
    void handle(AddNode& aAddNode);
    void handle(RemoveNode& aRemoveNode);
    void handle(SubtreeChange& aSubtree);
};

//--------------------------------------------------------------------------
std::auto_ptr<INode> OTreeNodeConverter::createCorrespondingNode(Change& _rChange)
{
    ONodeConverter aAction(*this);
    aAction.applyToChange(_rChange);
    return aAction.result();
}

//--------------------------------------------------------------------------
std::auto_ptr<ISubtree> OTreeNodeConverter::createCorrespondingTree(SubtreeChange& _rChange)
{
    std::auto_ptr<ISubtree> pBaseTree = this->createCorrespondingNode(_rChange);

    OCreateSubtreeAction aNextLevel(*pBaseTree,*this);
    _rChange.forEachChange(aNextLevel);

    return pBaseTree;
}

//--------------------------------------------------------------------------
void ONodeConverter::handle(ValueChange& aValueNode)
{
    m_pNode = base_ptr(m_rFactory.createCorrespondingNode(aValueNode));
}

//--------------------------------------------------------------------------
void ONodeConverter::handle(AddNode& aAddNode)
{
    m_pNode = aAddNode.getNewTree().cloneData(true);
}

//--------------------------------------------------------------------------
void ONodeConverter::handle(RemoveNode& /*aRemoveNode*/)
{
    m_pNode.reset();
}

//--------------------------------------------------------------------------
void ONodeConverter::handle(SubtreeChange& aSubtree)
{
    m_pNode = base_ptr(m_rFactory.createCorrespondingNode(aSubtree));
}

//--------------------------------------------------------------------------
void OCreateSubtreeAction::handle(ValueChange& _rChange)
{
    // create a node by a ValueChange
    std::auto_ptr<ValueNode> pNode = m_rNodeFactory.createCorrespondingNode(_rChange);

    m_rTree.addChild(base_ptr(pNode));
}

//--------------------------------------------------------------------------
void OCreateSubtreeAction::handle(SubtreeChange& _rChange)
{
    // create a node from a SubtreeChange (recursively)
    std::auto_ptr<ISubtree> pNode = m_rNodeFactory.createCorrespondingTree(_rChange);

    // add it to the tree
    m_rTree.addChild(base_ptr(pNode));
}

//--------------------------------------------------------------------------
void OCreateSubtreeAction::handle(RemoveNode& _rChange)
{
    { (void)_rChange; }
    // we have nothing to do
    OSL_ENSURE(!m_rTree.getChild(_rChange.getNodeName()), "Removed node found in tree being built");
}

//--------------------------------------------------------------------------
void OCreateSubtreeAction::handle(AddNode& _rChange)
{
    // free the node and add it to the subtree
    data::TreeSegment aNewNode = _rChange.getNewTree();
    m_rTree.addChild(aNewNode.cloneData(true));
}

//--------------------------------------------------------------------------

//..........................................................................
}   // namespace configmgr
//..........................................................................

<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2013-2016 Rapptz, ThePhD and contributors

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef SOL_STATE_HPP
#define SOL_STATE_HPP

#include "state_view.hpp"

namespace sol {
	inline int default_at_panic(lua_State* L) {
#ifdef SOL_NO_EXCEPTIONS
		(void)L;
		return -1;
#else
		const char* message = lua_tostring(L, -1);
		if (message) {
			std::string err = message;
			lua_pop(L, 1);
			throw error(err);
		}
		throw error(std::string("An unexpected error occurred and forced the lua state to call atpanic"));
#endif
	}

	class state : private std::unique_ptr<lua_State, void(*)(lua_State*)>, public state_view {
	private:
		typedef std::unique_ptr<lua_State, void(*)(lua_State*)> unique_base;
	public:
		state(lua_CFunction panic = default_at_panic) : unique_base(luaL_newstate(), lua_close),
			state_view(unique_base::get()) {
			set_panic(panic);
			stack::luajit_exception_handler(unique_base::get());
		}

		state(lua_CFunction panic, lua_Alloc alfunc, void* alpointer = nullptr) : unique_base(lua_newstate(alfunc, alpointer), lua_close),
			state_view(unique_base::get()) {
			set_panic(panic);
			stack::luajit_exception_handler(unique_base::get());
		}

		using state_view::get;
	};
} // sol

#endif // SOL_STATE_HPP
<commit_msg>Default error handler function for protected_function<commit_after>// The MIT License (MIT)

// Copyright (c) 2013-2016 Rapptz, ThePhD and contributors

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef SOL_STATE_HPP
#define SOL_STATE_HPP

#include "state_view.hpp"

namespace sol {
	inline int default_at_panic(lua_State* L) {
#ifdef SOL_NO_EXCEPTIONS
		(void)L;
		return -1;
#else
		const char* message = lua_tostring(L, -1);
		if (message) {
			std::string err = message;
			lua_pop(L, 1);
			throw error(err);
		}
		throw error(std::string("An unexpected error occurred and forced the lua state to call atpanic"));
#endif
	}

	inline int default_error_handler(lua_State*L) {
		using namespace sol;
		std::string msg = "An unknown error has triggered the default error handler";
		optional<string_detail::string_shim> maybetopmsg = stack::check_get<string_detail::string_shim>(L, 1);
		if (maybetopmsg) {
			const string_detail::string_shim& topmsg = maybetopmsg.value();
			msg.assign(topmsg.c_str(), topmsg.size());
		}
		luaL_traceback(L, L, msg.c_str(), 1);
		optional<string_detail::string_shim> maybetraceback = stack::check_get<string_detail::string_shim>(L, -1);
		if (maybetraceback) {
			const string_detail::string_shim& traceback = maybetraceback.value();
			msg.assign(traceback.c_str(), traceback.size());
		}
		return stack::push(L, msg);
	}

	class state : private std::unique_ptr<lua_State, void(*)(lua_State*)>, public state_view {
	private:
		typedef std::unique_ptr<lua_State, void(*)(lua_State*)> unique_base;
	public:
		state(lua_CFunction panic = default_at_panic) : unique_base(luaL_newstate(), lua_close),
			state_view(unique_base::get()) {
			set_panic(panic);
			stack::luajit_exception_handler(unique_base::get());
		}

		state(lua_CFunction panic, lua_Alloc alfunc, void* alpointer = nullptr) : unique_base(lua_newstate(alfunc, alpointer), lua_close),
			state_view(unique_base::get()) {
			set_panic(panic);
			sol::protected_function::set_default_handler(sol::object(lua_state(), in_place, default_error_handler));
			stack::luajit_exception_handler(unique_base::get());
		}

		using state_view::get;
	};
} // sol

#endif // SOL_STATE_HPP
<|endoftext|>


<commit_before>#include "lms7002_pnlCalibrations_view.h"
#include "lms7002_gui_utilities.h"
#include "LMS7002M.h"
#include <wx/msgdlg.h>
#include "numericSlider.h"
#include "lms7suiteEvents.h"
#include <wx/busyinfo.h>
using namespace lime;

lms7002_pnlCalibrations_view::lms7002_pnlCalibrations_view( wxWindow* parent )
:
pnlCalibrations_view( parent )
{

}

lms7002_pnlCalibrations_view::lms7002_pnlCalibrations_view(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
    : pnlCalibrations_view(parent, id, pos, size, style), lmsControl(nullptr)
{
    wndId2Enum[cmbIQCORR_TXTSP] = IQCORR_TXTSP;
    wndId2Enum[cmbDCCORRI_TXTSP] = DCCORRI_TXTSP;
    wndId2Enum[cmbDCCORRQ_TXTSP] = DCCORRQ_TXTSP;
    wndId2Enum[cmbGCORRI_TXTSP] = GCORRI_TXTSP;
    wndId2Enum[cmbGCORRQ_TXTSP] = GCORRQ_TXTSP;
    wndId2Enum[cmbGCORRI_RXTSP] = GCORRI_RXTSP;
    wndId2Enum[cmbGCORRQ_RXTSP] = GCORRQ_RXTSP;
    wndId2Enum[cmbIQCORR_RXTSP] = IQCORR_RXTSP;
    wndId2Enum[chkEN_DCOFF_RXFE_RFE] = EN_DCOFF_RXFE_RFE;
    wndId2Enum[cmbDCOFFI_RFE] = DCOFFI_RFE;
    wndId2Enum[cmbDCOFFQ_RFE] = DCOFFQ_RFE;

    LMS7002_WXGUI::UpdateTooltips(wndId2Enum, true);
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateRx(wxCommandEvent& event)
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating receiver...");
        status = lmsControl->CalibrateRx(bandwidth, false);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Rx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    else
    {
        wxMessageBox(_("Rx Calibration Finished"), _("Info"), wxOK, this);
        wxCommandEvent evt;
        evt.SetEventType(LOG_MESSAGE);
        evt.SetString(_("Rx Calibrated"));
        wxPostEvent(this, evt);
    }
    UpdateGUI();
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateTx( wxCommandEvent& event )
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating transmitter...");
        status = lmsControl->CalibrateTx(bandwidth);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Tx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    else
    {
        wxMessageBox(_("Tx Calibration Finished"), _("Info"), wxOK, this);
        wxCommandEvent evt;
        evt.SetEventType(LOG_MESSAGE);
        evt.SetString(_("Tx Calibrated"));
        wxPostEvent(this, evt);
    }
    UpdateGUI();
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateAll( wxCommandEvent& event )
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating transmitter...");
        status = lmsControl->CalibrateTx(bandwidth);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Tx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    {
        wxBusyInfo wait("Please wait, calibrating receiver...");
        status = lmsControl->CalibrateRx(bandwidth, false);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Rx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));

    wxMessageBox(_("Calibration Finished"), _("Info"), wxOK, this);
    UpdateGUI();
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateAllTDD(wxCommandEvent& event)
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating transmitter...");
        status = lmsControl->CalibrateTx(bandwidth);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Tx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    {
        wxBusyInfo wait("Please wait, calibrating receiver...");
        status = lmsControl->CalibrateRx(bandwidth, true);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Rx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));

    wxMessageBox(_("Calibration Finished"), _("Info"), wxOK, this);
    UpdateGUI();
}

void lms7002_pnlCalibrations_view::Initialize(LMS7002M* pControl)
{
    lmsControl = pControl;
    assert(lmsControl != nullptr);
}

void lms7002_pnlCalibrations_view::ParameterChangeHandler(wxSpinEvent& event)
{
    wxCommandEvent evt;
    evt.SetInt(event.GetInt());
    evt.SetId(event.GetId());
    evt.SetEventObject(event.GetEventObject());
    ParameterChangeHandler(evt);
}

void lms7002_pnlCalibrations_view::ParameterChangeHandler(wxCommandEvent& event)
{
    assert(lmsControl != nullptr);
    LMS7Parameter parameter;
    try
    {
        parameter = wndId2Enum.at(reinterpret_cast<wxWindow*>(event.GetEventObject()));
    }
    catch (std::exception & e)
    {
        std::cout << "Control element(ID = " << event.GetId() << ") don't have assigned LMS parameter." << std::endl;
        return;
    }
    lmsControl->Modify_SPI_Reg_bits(parameter, event.GetInt());
}

void lms7002_pnlCalibrations_view::UpdateGUI()
{
    LMS7002_WXGUI::UpdateControlsByMap(this, lmsControl, wndId2Enum);
    int16_t value = lmsControl->Get_SPI_Reg_bits(IQCORR_RXTSP);
    int bitsToShift = (15 - IQCORR_RXTSP.msb - IQCORR_RXTSP.lsb);
    value = value << bitsToShift;
    value = value >> bitsToShift;
    cmbIQCORR_RXTSP->SetValue(value);

    value = lmsControl->Get_SPI_Reg_bits(IQCORR_TXTSP);
    bitsToShift = (15 - IQCORR_TXTSP.msb - IQCORR_TXTSP.lsb);
    value = value << bitsToShift;
    value = value >> bitsToShift;
    cmbIQCORR_TXTSP->SetValue(value);

    value = lmsControl->Get_SPI_Reg_bits(DCOFFI_RFE);
    int16_t dcvalue = value & 0x3F;
    if ((value & 0x40) != 0)
        dcvalue *= -1;
    cmbDCOFFI_RFE->SetValue(dcvalue);
    value = lmsControl->Get_SPI_Reg_bits(DCOFFQ_RFE);
    dcvalue = value & 0x3F;
    if ((value & 0x40) != 0)
        dcvalue *= -1;
    cmbDCOFFQ_RFE->SetValue(dcvalue);

    int8_t dccorr = lmsControl->Get_SPI_Reg_bits(DCCORRI_TXTSP);
    cmbDCCORRI_TXTSP->SetValue(dccorr);
    dccorr = lmsControl->Get_SPI_Reg_bits(DCCORRQ_TXTSP);
    cmbDCCORRQ_TXTSP->SetValue(dccorr);

    lblCGENrefClk->SetLabel(wxString::Format(_("%f"), lmsControl->GetReferenceClk_SX(LMS7002M::Rx)));
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateRxTDD(wxCommandEvent& event)
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating receiver...");
        status = lmsControl->CalibrateRx(bandwidth, true);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Rx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    else
    {
        wxMessageBox(_("Rx Calibration Finished"), _("Info"), wxOK, this);
        wxCommandEvent evt;
        evt.SetEventType(LOG_MESSAGE);
        evt.SetString(_("Rx Calibrated"));
        wxPostEvent(this, evt);
    }
    UpdateGUI();
}
<commit_msg>Fix Rx DC offset controls in calibrations tab<commit_after>#include "lms7002_pnlCalibrations_view.h"
#include "lms7002_gui_utilities.h"
#include "LMS7002M.h"
#include <wx/msgdlg.h>
#include "numericSlider.h"
#include "lms7suiteEvents.h"
#include <wx/busyinfo.h>
using namespace lime;

lms7002_pnlCalibrations_view::lms7002_pnlCalibrations_view( wxWindow* parent )
:
pnlCalibrations_view( parent )
{

}

lms7002_pnlCalibrations_view::lms7002_pnlCalibrations_view(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
    : pnlCalibrations_view(parent, id, pos, size, style), lmsControl(nullptr)
{
    wndId2Enum[cmbIQCORR_TXTSP] = IQCORR_TXTSP;
    wndId2Enum[cmbDCCORRI_TXTSP] = DCCORRI_TXTSP;
    wndId2Enum[cmbDCCORRQ_TXTSP] = DCCORRQ_TXTSP;
    wndId2Enum[cmbGCORRI_TXTSP] = GCORRI_TXTSP;
    wndId2Enum[cmbGCORRQ_TXTSP] = GCORRQ_TXTSP;
    wndId2Enum[cmbGCORRI_RXTSP] = GCORRI_RXTSP;
    wndId2Enum[cmbGCORRQ_RXTSP] = GCORRQ_RXTSP;
    wndId2Enum[cmbIQCORR_RXTSP] = IQCORR_RXTSP;
    wndId2Enum[chkEN_DCOFF_RXFE_RFE] = EN_DCOFF_RXFE_RFE;
    wndId2Enum[cmbDCOFFI_RFE] = DCOFFI_RFE;
    wndId2Enum[cmbDCOFFQ_RFE] = DCOFFQ_RFE;

    LMS7002_WXGUI::UpdateTooltips(wndId2Enum, true);
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateRx(wxCommandEvent& event)
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating receiver...");
        status = lmsControl->CalibrateRx(bandwidth, false);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Rx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    else
    {
        wxMessageBox(_("Rx Calibration Finished"), _("Info"), wxOK, this);
        wxCommandEvent evt;
        evt.SetEventType(LOG_MESSAGE);
        evt.SetString(_("Rx Calibrated"));
        wxPostEvent(this, evt);
    }
    UpdateGUI();
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateTx( wxCommandEvent& event )
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating transmitter...");
        status = lmsControl->CalibrateTx(bandwidth);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Tx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    else
    {
        wxMessageBox(_("Tx Calibration Finished"), _("Info"), wxOK, this);
        wxCommandEvent evt;
        evt.SetEventType(LOG_MESSAGE);
        evt.SetString(_("Tx Calibrated"));
        wxPostEvent(this, evt);
    }
    UpdateGUI();
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateAll( wxCommandEvent& event )
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating transmitter...");
        status = lmsControl->CalibrateTx(bandwidth);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Tx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    {
        wxBusyInfo wait("Please wait, calibrating receiver...");
        status = lmsControl->CalibrateRx(bandwidth, false);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Rx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));

    wxMessageBox(_("Calibration Finished"), _("Info"), wxOK, this);
    UpdateGUI();
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateAllTDD(wxCommandEvent& event)
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating transmitter...");
        status = lmsControl->CalibrateTx(bandwidth);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Tx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    {
        wxBusyInfo wait("Please wait, calibrating receiver...");
        status = lmsControl->CalibrateRx(bandwidth, true);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Rx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));

    wxMessageBox(_("Calibration Finished"), _("Info"), wxOK, this);
    UpdateGUI();
}

void lms7002_pnlCalibrations_view::Initialize(LMS7002M* pControl)
{
    lmsControl = pControl;
    assert(lmsControl != nullptr);
}

void lms7002_pnlCalibrations_view::ParameterChangeHandler(wxSpinEvent& event)
{
    wxCommandEvent evt;
    evt.SetInt(event.GetInt());
    evt.SetId(event.GetId());
    evt.SetEventObject(event.GetEventObject());
    ParameterChangeHandler(evt);
}

void lms7002_pnlCalibrations_view::ParameterChangeHandler(wxCommandEvent& event)
{
    assert(lmsControl != nullptr);
    LMS7Parameter parameter;
    try
    {
        parameter = wndId2Enum.at(reinterpret_cast<wxWindow*>(event.GetEventObject()));
    }
    catch (std::exception & e)
    {
        std::cout << "Control element(ID = " << event.GetId() << ") don't have assigned LMS parameter." << std::endl;
        return;
    }
    if(parameter == DCOFFI_RFE || parameter == DCOFFQ_RFE)
    {
        int16_t value = (event.GetInt() < 0) << 6;
        value |= abs(event.GetInt()) & 0x2F;
        lmsControl->Modify_SPI_Reg_bits(parameter, value);
    }
    else
        lmsControl->Modify_SPI_Reg_bits(parameter, event.GetInt());
}

void lms7002_pnlCalibrations_view::UpdateGUI()
{
    LMS7002_WXGUI::UpdateControlsByMap(this, lmsControl, wndId2Enum);
    int16_t value = lmsControl->Get_SPI_Reg_bits(IQCORR_RXTSP);
    int bitsToShift = (15 - IQCORR_RXTSP.msb - IQCORR_RXTSP.lsb);
    value = value << bitsToShift;
    value = value >> bitsToShift;
    cmbIQCORR_RXTSP->SetValue(value);

    value = lmsControl->Get_SPI_Reg_bits(IQCORR_TXTSP);
    bitsToShift = (15 - IQCORR_TXTSP.msb - IQCORR_TXTSP.lsb);
    value = value << bitsToShift;
    value = value >> bitsToShift;
    cmbIQCORR_TXTSP->SetValue(value);

    value = lmsControl->Get_SPI_Reg_bits(DCOFFI_RFE);
    int16_t dcvalue = value & 0x3F;
    if ((value & 0x40) != 0)
        dcvalue *= -1;
    cmbDCOFFI_RFE->SetValue(dcvalue);
    value = lmsControl->Get_SPI_Reg_bits(DCOFFQ_RFE);
    dcvalue = value & 0x3F;
    if ((value & 0x40) != 0)
        dcvalue *= -1;
    cmbDCOFFQ_RFE->SetValue(dcvalue);

    int8_t dccorr = lmsControl->Get_SPI_Reg_bits(DCCORRI_TXTSP);
    cmbDCCORRI_TXTSP->SetValue(dccorr);
    dccorr = lmsControl->Get_SPI_Reg_bits(DCCORRQ_TXTSP);
    cmbDCCORRQ_TXTSP->SetValue(dccorr);

    lblCGENrefClk->SetLabel(wxString::Format(_("%f"), lmsControl->GetReferenceClk_SX(LMS7002M::Rx)));
}

void lms7002_pnlCalibrations_view::OnbtnCalibrateRxTDD(wxCommandEvent& event)
{
    double bandwidth = 0;
    txtCalibrationBW->GetValue().ToDouble(&bandwidth);
    liblms7_status status;
    {
        wxBusyInfo wait("Please wait, calibrating receiver...");
        status = lmsControl->CalibrateRx(bandwidth, true);
    }
    if (status != LIBLMS7_SUCCESS)
        wxMessageBox(wxString::Format(_("Rx calibration: %s"), wxString::From8BitData(liblms7_status2string(status))));
    else
    {
        wxMessageBox(_("Rx Calibration Finished"), _("Info"), wxOK, this);
        wxCommandEvent evt;
        evt.SetEventType(LOG_MESSAGE);
        evt.SetString(_("Rx Calibrated"));
        wxPostEvent(this, evt);
    }
    UpdateGUI();
}
<|endoftext|>


<commit_before>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER 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 <iostream>
#include "hashring.h"

int main(int argc, char* argv[]) {
  (void)argc, (void)argv;

  consistent_hash::HashRing hr;
  for (auto i = 0; i < 10; ++i) {
    std::string s("Node");
    consistent_hash::HashNode n(i + 5, s + std::to_string(i));
    hr.insert_node(n);
  }

  auto n = hr.get_node("Node3");
  std::cout << "n.name: " << n.get_name() << ", n.replicas: " << n.get_replicas() << std::endl;

  return 0;
}
<commit_msg>:construction: chore(consistenthash): consistent hash from google<commit_after>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER 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 <iostream>
#include "hashring.h"

static void test_consistent_hash(void) {
  consistent_hash::HashRing hr;
  for (auto i = 0; i < 10; ++i) {
    std::string s("Node");
    consistent_hash::HashNode n(i + 5, s + std::to_string(i));
    hr.insert_node(n);
  }

  auto n = hr.get_node("Node3");
  std::cout << "n.name: " << n.get_name() << ", n.replicas: " << n.get_replicas() << std::endl;
}

static std::int32_t jump_consistent_hash(std::uint64_t key, std::int32_t num_buckets) {
  std::int64_t b = -1;
  std::int64_t j = 0;
  while (j < num_buckets) {
    b = j;
    key = key * 2862933555777941757ULL + 1;
    j = (b + 1) * (double(1LL << 31) / double((key >> 33) + 1));
  }
  return b;
}

int main(int argc, char* argv[]) {
  (void)argc, (void)argv;

  test_consistent_hash();

  for (auto i = 0; i < 10; ++i)
    std::cout << "[" << i << "] => " << jump_consistent_hash(i, 5) << std::endl;

  std::cout << "######################################" << std::endl;
  for (auto i = 0; i < 10; ++i)
    std::cout << "[" << i << "] => " << jump_consistent_hash(i, 4) << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkSurface_Base.h"
#include "SkImagePriv.h"
#include "SkCanvas.h"
#include "SkGpuDevice.h"

class SkSurface_Gpu : public SkSurface_Base {
public:
    SK_DECLARE_INST_COUNT(SkSurface_Gpu)

    SkSurface_Gpu(GrRenderTarget*);
    virtual ~SkSurface_Gpu();

    virtual SkCanvas* onNewCanvas() SK_OVERRIDE;
    virtual SkSurface* onNewSurface(const SkImageInfo&) SK_OVERRIDE;
    virtual SkImage* onNewImageSnapshot() SK_OVERRIDE;
    virtual void onDraw(SkCanvas*, SkScalar x, SkScalar y,
                        const SkPaint*) SK_OVERRIDE;
    virtual void onCopyOnWrite(ContentChangeMode) SK_OVERRIDE;

private:
    SkGpuDevice* fDevice;

    typedef SkSurface_Base INHERITED;
};

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

SkSurface_Gpu::SkSurface_Gpu(GrRenderTarget* renderTarget)
        : INHERITED(renderTarget->width(), renderTarget->height()) {
    fDevice = SkNEW_ARGS(SkGpuDevice, (renderTarget->getContext(), renderTarget));

    if (kRGB_565_GrPixelConfig != renderTarget->config()) {
        fDevice->clear(0x0);
    }
}

SkSurface_Gpu::~SkSurface_Gpu() {
    SkSafeUnref(fDevice);
}

SkCanvas* SkSurface_Gpu::onNewCanvas() {
    return SkNEW_ARGS(SkCanvas, (fDevice));
}

SkSurface* SkSurface_Gpu::onNewSurface(const SkImageInfo& info) {
    GrRenderTarget* rt = fDevice->accessRenderTarget();
    int sampleCount = rt->numSamples();
    return SkSurface::NewRenderTarget(fDevice->context(), info, sampleCount);
}

SkImage* SkSurface_Gpu::onNewImageSnapshot() {
    return SkImage::NewTexture(fDevice->accessBitmap(false));
}

void SkSurface_Gpu::onDraw(SkCanvas* canvas, SkScalar x, SkScalar y,
                              const SkPaint* paint) {
    canvas->drawBitmap(fDevice->accessBitmap(false), x, y, paint);
}

// Create a new SkGpuDevice and, if necessary, copy the contents of the old
// device into it. Note that this flushes the SkGpuDevice but
// doesn't force an OpenGL flush.
void SkSurface_Gpu::onCopyOnWrite(ContentChangeMode mode) {
    GrRenderTarget* rt = fDevice->accessRenderTarget();
    // are we sharing our render target with the image?
    SkASSERT(NULL != this->getCachedImage());
    if (rt->asTexture() == SkTextureImageGetTexture(this->getCachedImage())) {
        SkAutoTUnref<SkGpuDevice> newDevice(SkGpuDevice::Create(fDevice->context(),
                                                     fDevice->imageInfo(),
                                                     rt->numSamples()));
        SkASSERT(newDevice.get());

        if (kRetain_ContentChangeMode == mode) {
            fDevice->context()->copyTexture(rt->asTexture(),
                reinterpret_cast<GrRenderTarget*>(newDevice->accessRenderTarget()));
        }
        SkASSERT(NULL != this->getCachedCanvas());
        SkASSERT(this->getCachedCanvas()->getDevice() == fDevice);
        this->getCachedCanvas()->setRootDevice(newDevice);
        SkRefCnt_SafeAssign(fDevice, newDevice.get());
    }
}

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

SkSurface* SkSurface::NewRenderTargetDirect(GrRenderTarget* target) {
    if (NULL == target) {
        return NULL;
    }
    return SkNEW_ARGS(SkSurface_Gpu, (target));
}

SkSurface* SkSurface::NewRenderTarget(GrContext* ctx, const SkImageInfo& info, int sampleCount) {
    if (NULL == ctx) {
        return NULL;
    }

    SkBitmap::Config config = SkImageInfoToBitmapConfig(info);

    GrTextureDesc desc;
    desc.fFlags = kRenderTarget_GrTextureFlagBit | kCheckAllocation_GrTextureFlagBit;
    desc.fWidth = info.fWidth;
    desc.fHeight = info.fHeight;
    desc.fConfig = SkBitmapConfig2GrPixelConfig(config);
    desc.fSampleCnt = sampleCount;

    SkAutoTUnref<GrTexture> tex(ctx->createUncachedTexture(desc, NULL, 0));
    if (NULL == tex) {
        return NULL;
    }

    return SkNEW_ARGS(SkSurface_Gpu, (tex->asRenderTarget()));
}
<commit_msg>Manual revert of https://code.google.com/p/skia/source/detail?r=13353 due to perf regression.<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkSurface_Base.h"
#include "SkImagePriv.h"
#include "SkCanvas.h"
#include "SkGpuDevice.h"

class SkSurface_Gpu : public SkSurface_Base {
public:
    SK_DECLARE_INST_COUNT(SkSurface_Gpu)

    SkSurface_Gpu(GrRenderTarget*);
    virtual ~SkSurface_Gpu();

    virtual SkCanvas* onNewCanvas() SK_OVERRIDE;
    virtual SkSurface* onNewSurface(const SkImageInfo&) SK_OVERRIDE;
    virtual SkImage* onNewImageSnapshot() SK_OVERRIDE;
    virtual void onDraw(SkCanvas*, SkScalar x, SkScalar y,
                        const SkPaint*) SK_OVERRIDE;
    virtual void onCopyOnWrite(ContentChangeMode) SK_OVERRIDE;

private:
    SkGpuDevice* fDevice;

    typedef SkSurface_Base INHERITED;
};

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

SkSurface_Gpu::SkSurface_Gpu(GrRenderTarget* renderTarget)
        : INHERITED(renderTarget->width(), renderTarget->height()) {
    fDevice = SkNEW_ARGS(SkGpuDevice, (renderTarget->getContext(), renderTarget));

    if (kRGB_565_GrPixelConfig != renderTarget->config()) {
        fDevice->clear(0x0);
    }
}

SkSurface_Gpu::~SkSurface_Gpu() {
    SkSafeUnref(fDevice);
}

SkCanvas* SkSurface_Gpu::onNewCanvas() {
    return SkNEW_ARGS(SkCanvas, (fDevice));
}

SkSurface* SkSurface_Gpu::onNewSurface(const SkImageInfo& info) {
    GrRenderTarget* rt = fDevice->accessRenderTarget();
    int sampleCount = rt->numSamples();
    return SkSurface::NewRenderTarget(fDevice->context(), info, sampleCount);
}

SkImage* SkSurface_Gpu::onNewImageSnapshot() {
    return SkImage::NewTexture(fDevice->accessBitmap(false));
}

void SkSurface_Gpu::onDraw(SkCanvas* canvas, SkScalar x, SkScalar y,
                              const SkPaint* paint) {
    canvas->drawBitmap(fDevice->accessBitmap(false), x, y, paint);
}

// Create a new SkGpuDevice and, if necessary, copy the contents of the old
// device into it. Note that this flushes the SkGpuDevice but
// doesn't force an OpenGL flush.
void SkSurface_Gpu::onCopyOnWrite(ContentChangeMode mode) {
    GrRenderTarget* rt = fDevice->accessRenderTarget();
    // are we sharing our render target with the image?
    SkASSERT(NULL != this->getCachedImage());
    if (rt->asTexture() == SkTextureImageGetTexture(this->getCachedImage())) {
        // We call createCompatibleDevice because it uses the texture cache. This isn't
        // necessarily correct (http://skbug.com/2252), but never using the cache causes
        // a Chromium regression. (http://crbug.com/344020)
        SkGpuDevice* newDevice = static_cast<SkGpuDevice*>(
            fDevice->createCompatibleDevice(fDevice->imageInfo()));
        SkAutoTUnref<SkGpuDevice> aurd(newDevice);
        if (kRetain_ContentChangeMode == mode) {
            fDevice->context()->copyTexture(rt->asTexture(), newDevice->accessRenderTarget());
        }
        SkASSERT(NULL != this->getCachedCanvas());
        SkASSERT(this->getCachedCanvas()->getDevice() == fDevice);

        this->getCachedCanvas()->setRootDevice(newDevice);
        SkRefCnt_SafeAssign(fDevice, newDevice);
    }
}

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

SkSurface* SkSurface::NewRenderTargetDirect(GrRenderTarget* target) {
    if (NULL == target) {
        return NULL;
    }
    return SkNEW_ARGS(SkSurface_Gpu, (target));
}

SkSurface* SkSurface::NewRenderTarget(GrContext* ctx, const SkImageInfo& info, int sampleCount) {
    if (NULL == ctx) {
        return NULL;
    }

    SkBitmap::Config config = SkImageInfoToBitmapConfig(info);

    GrTextureDesc desc;
    desc.fFlags = kRenderTarget_GrTextureFlagBit | kCheckAllocation_GrTextureFlagBit;
    desc.fWidth = info.fWidth;
    desc.fHeight = info.fHeight;
    desc.fConfig = SkBitmapConfig2GrPixelConfig(config);
    desc.fSampleCnt = sampleCount;

    SkAutoTUnref<GrTexture> tex(ctx->createUncachedTexture(desc, NULL, 0));
    if (NULL == tex) {
        return NULL;
    }

    return SkNEW_ARGS(SkSurface_Gpu, (tex->asRenderTarget()));
}
<|endoftext|>