<commit_before>/*
 IPAddress.cpp - Base class that provides IPAddress
 Copyright (c) 2011 Adrian McEwen.  All right reserved.

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

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

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <Arduino.h>
#include <IPAddress.h>
#include <Print.h>
#include <StreamString.h>

IPAddress::IPAddress(const IPAddress& from)
{
    ip_addr_copy(_ip, from._ip);
}

IPAddress::IPAddress() {
    _ip = *IP_ANY_TYPE; // lwIP's v4-or-v6 generic address
}

bool IPAddress::isSet () const {
    return !ip_addr_isany(&_ip);
}

IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet) {
    setV4();
    (*this)[0] = first_octet;
    (*this)[1] = second_octet;
    (*this)[2] = third_octet;
    (*this)[3] = fourth_octet;
}

void IPAddress::ctor32(uint32_t address) {
    setV4();
    v4() = address;
}

IPAddress::IPAddress(const uint8_t *address) {
    setV4();
    (*this)[0] = address[0];
    (*this)[1] = address[1];
    (*this)[2] = address[2];
    (*this)[3] = address[3];
}

bool IPAddress::fromString(const char *address) {
    if (!fromString4(address)) {
#if LWIP_IPV6
        return fromString6(address);
#else
        return false;
#endif
    }
    return true;
}

bool IPAddress::fromString4(const char *address) {
    // TODO: (IPv4) add support for "a", "a.b", "a.b.c" formats

    uint16_t acc = 0; // Accumulator
    uint8_t dots = 0;

    while (*address)
    {
        char c = *address++;
        if (c >= '0' && c <= '9')
        {
            acc = acc * 10 + (c - '0');
            if (acc > 255) {
                // Value out of [0..255] range
                return false;
            }
        }
        else if (c == '.')
        {
            if (dots == 3) {
                // Too much dots (there must be 3 dots)
                return false;
            }
            (*this)[dots++] = acc;
            acc = 0;
        }
        else
        {
            // Invalid char
            return false;
        }
    }

    if (dots != 3) {
        // Too few dots (there must be 3 dots)
        return false;
    }
    (*this)[3] = acc;

    setV4();
    return true;
}

IPAddress& IPAddress::operator=(const uint8_t *address) {
    setV4();
    v4() = *reinterpret_cast<const uint32_t*>(address);
    return *this;
}

IPAddress& IPAddress::operator=(uint32_t address) {
    setV4();
    v4() = address;
    return *this;
}

bool IPAddress::operator==(const uint8_t* addr) const {
    return isV4() && v4() == *reinterpret_cast<const uint32_t*>(addr);
}

size_t IPAddress::printTo(Print& p) const {
    size_t n = 0;

    if (!isSet())
        return p.print(F("(IP unset)"));

#if LWIP_IPV6
    if (isV6()) {
        int count0 = 0;
        for (int i = 0; i < 8; i++) {
            uint16_t bit = PP_NTOHS(raw6()[i]);
            if (bit || count0 < 0) {
                n += p.printf("%x", bit);
                if (count0 > 0)
                    // no more hiding 0
                    count0 = -8;
            } else
                count0++;
            if ((i != 7 && count0 < 2) || count0 == 7)
                n += p.print(':');
        }
        return n;
    }
#endif

    for(int i = 0; i < 4; i++) {
        n += p.print((*this)[i], DEC);
        if (i != 3)
            n += p.print('.');
    }
    return n;
}

String IPAddress::toString() const
{
    StreamString sstr;
#if LWIP_IPV6
    if (isV6())
        sstr.reserve(40); // 8 shorts x 4 chars each + 7 colons + nullterm
    else
#endif
        sstr.reserve(16); // 4 bytes with 3 chars max + 3 dots + nullterm, or '(IP unset)'
    printTo(sstr);
    return sstr;
}

bool IPAddress::isValid(const String& arg) {
	return IPAddress().fromString(arg);
}

bool IPAddress::isValid(const char* arg) {
	return IPAddress().fromString(arg);
}

const IPAddress INADDR_ANY; // generic "0.0.0.0" for IPv4 & IPv6
const IPAddress INADDR_NONE(255,255,255,255);

/**************************************/

#if LWIP_IPV6

bool IPAddress::fromString6(const char *address) {
    // TODO: test test test

    uint32_t acc = 0; // Accumulator
    int dots = 0, doubledots = -1;

    while (*address)
    {
        char c = tolower(*address++);
        if (isalnum(c)) {
            if (c >= 'a')
                c -= 'a' - '0' - 10;
            acc = acc * 16 + (c - '0');
            if (acc > 0xffff)
                // Value out of range
                return false;
        }
        else if (c == ':') {
            if (*address == ':') {
                if (doubledots >= 0)
                    // :: allowed once
                    return false;
                // remember location
                doubledots = dots + !!acc;
                address++;
            }
            if (dots == 7)
                // too many separators
                return false;
            raw6()[dots++] = PP_HTONS(acc);
            acc = 0;
        }
        else
            // Invalid char
            return false;
    }

    if (doubledots == -1 && dots != 7)
        // Too few separators
        return false;
    raw6()[dots++] = PP_HTONS(acc);

    if (doubledots != -1) {
        for (int i = dots - doubledots - 1; i >= 0; i--)
            raw6()[8 - dots + doubledots + i] = raw6()[doubledots + i];
        for (int i = doubledots; i < 8 - dots + doubledots; i++)
            raw6()[i] = 0;
    }

    setV6();
    return true;
}

#endif
<commit_msg>Check also if IP is not IPADDR_NONE (#7585)<commit_after>/*
 IPAddress.cpp - Base class that provides IPAddress
 Copyright (c) 2011 Adrian McEwen.  All right reserved.

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

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

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <Arduino.h>
#include <IPAddress.h>
#include <Print.h>
#include <StreamString.h>

IPAddress::IPAddress(const IPAddress& from)
{
    ip_addr_copy(_ip, from._ip);
}

IPAddress::IPAddress() {
    _ip = *IP_ANY_TYPE; // lwIP's v4-or-v6 generic address
}

bool IPAddress::isSet () const {
    return !ip_addr_isany(&_ip) && ((*this) != IPADDR_NONE);
}

IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet) {
    setV4();
    (*this)[0] = first_octet;
    (*this)[1] = second_octet;
    (*this)[2] = third_octet;
    (*this)[3] = fourth_octet;
}

void IPAddress::ctor32(uint32_t address) {
    setV4();
    v4() = address;
}

IPAddress::IPAddress(const uint8_t *address) {
    setV4();
    (*this)[0] = address[0];
    (*this)[1] = address[1];
    (*this)[2] = address[2];
    (*this)[3] = address[3];
}

bool IPAddress::fromString(const char *address) {
    if (!fromString4(address)) {
#if LWIP_IPV6
        return fromString6(address);
#else
        return false;
#endif
    }
    return true;
}

bool IPAddress::fromString4(const char *address) {
    // TODO: (IPv4) add support for "a", "a.b", "a.b.c" formats

    uint16_t acc = 0; // Accumulator
    uint8_t dots = 0;

    while (*address)
    {
        char c = *address++;
        if (c >= '0' && c <= '9')
        {
            acc = acc * 10 + (c - '0');
            if (acc > 255) {
                // Value out of [0..255] range
                return false;
            }
        }
        else if (c == '.')
        {
            if (dots == 3) {
                // Too much dots (there must be 3 dots)
                return false;
            }
            (*this)[dots++] = acc;
            acc = 0;
        }
        else
        {
            // Invalid char
            return false;
        }
    }

    if (dots != 3) {
        // Too few dots (there must be 3 dots)
        return false;
    }
    (*this)[3] = acc;

    setV4();
    return true;
}

IPAddress& IPAddress::operator=(const uint8_t *address) {
    setV4();
    v4() = *reinterpret_cast<const uint32_t*>(address);
    return *this;
}

IPAddress& IPAddress::operator=(uint32_t address) {
    setV4();
    v4() = address;
    return *this;
}

bool IPAddress::operator==(const uint8_t* addr) const {
    return isV4() && v4() == *reinterpret_cast<const uint32_t*>(addr);
}

size_t IPAddress::printTo(Print& p) const {
    size_t n = 0;

    if (!isSet())
        return p.print(F("(IP unset)"));

#if LWIP_IPV6
    if (isV6()) {
        int count0 = 0;
        for (int i = 0; i < 8; i++) {
            uint16_t bit = PP_NTOHS(raw6()[i]);
            if (bit || count0 < 0) {
                n += p.printf("%x", bit);
                if (count0 > 0)
                    // no more hiding 0
                    count0 = -8;
            } else
                count0++;
            if ((i != 7 && count0 < 2) || count0 == 7)
                n += p.print(':');
        }
        return n;
    }
#endif

    for(int i = 0; i < 4; i++) {
        n += p.print((*this)[i], DEC);
        if (i != 3)
            n += p.print('.');
    }
    return n;
}

String IPAddress::toString() const
{
    StreamString sstr;
#if LWIP_IPV6
    if (isV6())
        sstr.reserve(40); // 8 shorts x 4 chars each + 7 colons + nullterm
    else
#endif
        sstr.reserve(16); // 4 bytes with 3 chars max + 3 dots + nullterm, or '(IP unset)'
    printTo(sstr);
    return sstr;
}

bool IPAddress::isValid(const String& arg) {
	return IPAddress().fromString(arg);
}

bool IPAddress::isValid(const char* arg) {
	return IPAddress().fromString(arg);
}

const IPAddress INADDR_ANY; // generic "0.0.0.0" for IPv4 & IPv6
const IPAddress INADDR_NONE(255,255,255,255);

/**************************************/

#if LWIP_IPV6

bool IPAddress::fromString6(const char *address) {
    // TODO: test test test

    uint32_t acc = 0; // Accumulator
    int dots = 0, doubledots = -1;

    while (*address)
    {
        char c = tolower(*address++);
        if (isalnum(c)) {
            if (c >= 'a')
                c -= 'a' - '0' - 10;
            acc = acc * 16 + (c - '0');
            if (acc > 0xffff)
                // Value out of range
                return false;
        }
        else if (c == ':') {
            if (*address == ':') {
                if (doubledots >= 0)
                    // :: allowed once
                    return false;
                // remember location
                doubledots = dots + !!acc;
                address++;
            }
            if (dots == 7)
                // too many separators
                return false;
            raw6()[dots++] = PP_HTONS(acc);
            acc = 0;
        }
        else
            // Invalid char
            return false;
    }

    if (doubledots == -1 && dots != 7)
        // Too few separators
        return false;
    raw6()[dots++] = PP_HTONS(acc);

    if (doubledots != -1) {
        for (int i = dots - doubledots - 1; i >= 0; i--)
            raw6()[8 - dots + doubledots + i] = raw6()[doubledots + i];
        for (int i = doubledots; i < 8 - dots + doubledots; i++)
            raw6()[i] = 0;
    }

    setV6();
    return true;
}

#endif
<|endoftext|>


<commit_before>///
/// @file  CpuInfo.cpp
/// @brief Get the CPUs cache sizes in bytes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve/CpuInfo.hpp>
#include <cstddef>

#if defined(__APPLE__) && \
  (!defined(__has_include) || \
  (__has_include(<sys/types.h>) && \
   __has_include(<sys/sysctl.h>)))

#define APPLE_SYSCTL

#endif

#if defined(_WIN32)

#include <windows.h>
#include <vector>

#elif defined(APPLE_SYSCTL)

#include <sys/types.h>
#include <sys/sysctl.h>

#else // all other OSes

#include <array>
#include <cstdio>
#include <memory>
#include <string>

using namespace std;

namespace {

string getCacheStr(const char* filename)
{
  shared_ptr<FILE> file(
      fopen(filename, "r"), fclose);
  array<char, 64> buffer;
  string cacheStr;

  if (file)
  {
    while (!feof(file.get()))
    {
      if (fgets(buffer.data(), buffer.size(), file.get()))
        cacheStr += buffer.data();
    }
  }

  return cacheStr;
}

size_t getCacheSize(const char* filename)
{
  size_t cacheSize = 0;
  string cacheStr = getCacheStr(filename);
  size_t pos = cacheStr.find_first_of("0123456789");

  if (pos != string::npos)
  {
    // first character after number
    size_t idx = 0;
    cacheSize = stol(cacheStr.substr(pos), &idx);

    if (idx < cacheStr.size())
    {
      // Last character may be:
      // 'K' = kilobytes
      // 'M' = megabytes
      // 'G' = gigabytes

      if (cacheStr[idx] == 'K')
        cacheSize *= 1024;
      if (cacheStr[idx] == 'M')
        cacheSize *= 1024 * 1024;
      if (cacheStr[idx] == 'G')
        cacheSize *= 1024 * 1024 * 1024;
    }
  }

  return cacheSize;
}

} // namespace

#endif

using namespace std;

namespace primesieve {

CpuInfo::CpuInfo()
  : l1CacheSize_(0),
    l2CacheSize_(0),
    l3CacheSize_(0)
{
  initCache();
}

size_t CpuInfo::l1CacheSize() const
{
  return l1CacheSize_;
}

size_t CpuInfo::l2CacheSize() const
{
  return l2CacheSize_;
}

size_t CpuInfo::l3CacheSize() const
{
  return l3CacheSize_;
}

#if defined(APPLE_SYSCTL)

void CpuInfo::initCache()
{
  size_t l1Length = sizeof(l1CacheSize_);
  size_t l2Length = sizeof(l2CacheSize_);
  size_t l3Length = sizeof(l3CacheSize_);

  sysctlbyname("hw.l1dcachesize", &l1CacheSize_, &l1Length, NULL, 0);
  sysctlbyname("hw.l2cachesize" , &l2CacheSize_, &l2Length, NULL, 0);
  sysctlbyname("hw.l3cachesize" , &l3CacheSize_, &l3Length, NULL, 0);
}

#elif defined(_WIN32)

void CpuInfo::initCache()
{
  typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);

  LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");

  if (glpi)
  {
    DWORD bytes = 0;
    glpi(0, &bytes);
    size_t size = bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
    vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);
    glpi(info.data(), &bytes);

    for (size_t i = 0; i < size; i++)
    {
      if (info[i].Relationship == RelationCache)
      {
        if (info[i].Cache.Level == 1)
          l1CacheSize_ = info[i].Cache.Size;
        if (info[i].Cache.Level == 2)
          l2CacheSize_ = info[i].Cache.Size;
        if (info[i].Cache.Level == 3)
          l3CacheSize_ = info[i].Cache.Size;
      }
    }
  }
}

#else

/// This works on Linux, we also use this for
/// all unkown OSes, it might work.
///
void CpuInfo::initCache()
{
  l1CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index0/size");
  l2CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index2/size");
  l3CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index3/size");
}

#endif

/// Singleton
const CpuInfo cpuInfo;

} // namespace
<commit_msg>Use C++ instead of C<commit_after>///
/// @file  CpuInfo.cpp
/// @brief Get the CPUs cache sizes in bytes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve/CpuInfo.hpp>
#include <cstddef>

#if defined(__APPLE__) && \
  (!defined(__has_include) || \
  (__has_include(<sys/types.h>) && \
   __has_include(<sys/sysctl.h>)))

#define APPLE_SYSCTL

#endif

#if defined(_WIN32)

#include <windows.h>
#include <vector>

#elif defined(APPLE_SYSCTL)

#include <sys/types.h>
#include <sys/sysctl.h>

#else // all other OSes

#include <fstream>
#include <sstream>
#include <string>

using namespace std;

namespace {

string getCacheStr(const string& filename)
{
  ifstream file(filename);
  string cacheStr;

  if (file)
  {
    ostringstream oss;
    oss << file.rdbuf();
    cacheStr = oss.str();
  }

  return cacheStr;
}

size_t getCacheSize(const string& filename)
{
  size_t cacheSize = 0;
  string cacheStr = getCacheStr(filename);
  size_t pos = cacheStr.find_first_of("0123456789");

  if (pos != string::npos)
  {
    // first character after number
    size_t idx = 0;
    cacheSize = stol(cacheStr.substr(pos), &idx);

    if (idx < cacheStr.size())
    {
      // Last character may be:
      // 'K' = kilobytes
      // 'M' = megabytes
      // 'G' = gigabytes

      if (cacheStr[idx] == 'K')
        cacheSize *= 1024;
      if (cacheStr[idx] == 'M')
        cacheSize *= 1024 * 1024;
      if (cacheStr[idx] == 'G')
        cacheSize *= 1024 * 1024 * 1024;
    }
  }

  return cacheSize;
}

} // namespace

#endif

using namespace std;

namespace primesieve {

CpuInfo::CpuInfo()
  : l1CacheSize_(0),
    l2CacheSize_(0),
    l3CacheSize_(0)
{
  initCache();
}

size_t CpuInfo::l1CacheSize() const
{
  return l1CacheSize_;
}

size_t CpuInfo::l2CacheSize() const
{
  return l2CacheSize_;
}

size_t CpuInfo::l3CacheSize() const
{
  return l3CacheSize_;
}

#if defined(APPLE_SYSCTL)

void CpuInfo::initCache()
{
  size_t l1Length = sizeof(l1CacheSize_);
  size_t l2Length = sizeof(l2CacheSize_);
  size_t l3Length = sizeof(l3CacheSize_);

  sysctlbyname("hw.l1dcachesize", &l1CacheSize_, &l1Length, NULL, 0);
  sysctlbyname("hw.l2cachesize" , &l2CacheSize_, &l2Length, NULL, 0);
  sysctlbyname("hw.l3cachesize" , &l3CacheSize_, &l3Length, NULL, 0);
}

#elif defined(_WIN32)

void CpuInfo::initCache()
{
  typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);

  LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");

  if (glpi)
  {
    DWORD bytes = 0;
    glpi(0, &bytes);
    size_t size = bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
    vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);
    glpi(info.data(), &bytes);

    for (size_t i = 0; i < size; i++)
    {
      if (info[i].Relationship == RelationCache)
      {
        if (info[i].Cache.Level == 1)
          l1CacheSize_ = info[i].Cache.Size;
        if (info[i].Cache.Level == 2)
          l2CacheSize_ = info[i].Cache.Size;
        if (info[i].Cache.Level == 3)
          l3CacheSize_ = info[i].Cache.Size;
      }
    }
  }
}

#else

/// This works on Linux, we also use this for
/// all unkown OSes, it might work.
///
void CpuInfo::initCache()
{
  l1CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index0/size");
  l2CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index2/size");
  l3CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index3/size");
}

#endif

/// Singleton
const CpuInfo cpuInfo;

} // namespace
<|endoftext|>


<commit_before>/*****************************************************************************
 * Controller.cpp : Controller for the main interface
 ****************************************************************************
 * Copyright (C) 2006-2008 the VideoLAN team
 * $Id$
 *
 * Authors: Jean-Baptiste Kempf <jb@videolan.org>
 *          Ilkka Ollakka <ileoo@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * ( at your option ) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <vlc_vout.h>
#include <vlc_aout.h>
#include <vlc_keys.h>

#include "actions_manager.hpp"
#include "dialogs_provider.hpp" /* Opening Dialogs */
#include "input_manager.hpp"
#include "main_interface.hpp" /* Show playlist */

ActionsManager * ActionsManager::instance = NULL;

ActionsManager::ActionsManager( intf_thread_t * _p_i, QObject *_parent )
               : QObject( _parent )
{
    p_intf = _p_i;
}

ActionsManager::~ActionsManager(){}

void ActionsManager::doAction( int id_action )
{
    switch( id_action )
    {
        case PLAY_ACTION:
            play(); break;
        case STOP_ACTION:
            THEMIM->stop(); break;
        case OPEN_ACTION:
            THEDP->openDialog(); break;
        case PREVIOUS_ACTION:
            THEMIM->prev(); break;
        case NEXT_ACTION:
            THEMIM->next(); break;
        case SLOWER_ACTION:
            THEMIM->getIM()->slower(); break;
        case FASTER_ACTION:
            THEMIM->getIM()->faster(); break;
        case FULLSCREEN_ACTION:
            fullscreen(); break;
        case EXTENDED_ACTION:
            THEDP->extendedDialog(); break;
        case PLAYLIST_ACTION:
            playlist(); break;
        case SNAPSHOT_ACTION:
            snapshot(); break;
        case RECORD_ACTION:
            record(); break;
        case FRAME_ACTION:
            frame(); break;
        case ATOB_ACTION:
            THEMIM->getIM()->setAtoB(); break;
        case REVERSE_ACTION:
            THEMIM->getIM()->reverse(); break;
        case SKIP_BACK_ACTION:
            var_SetInteger( p_intf->p_libvlc, "key-action",
                    ACTIONID_JUMP_BACKWARD_SHORT );
            break;
        case SKIP_FW_ACTION:
            var_SetInteger( p_intf->p_libvlc, "key-action",
                    ACTIONID_JUMP_FORWARD_SHORT );
            break;
        case QUIT_ACTION:
            THEDP->quit();  break;
        case RANDOM_ACTION:
            THEMIM->toggleRandom(); break;
        case INFO_ACTION:
            THEDP->mediaInfoDialog(); break;
        default:
            msg_Dbg( p_intf, "Action: %i", id_action );
            break;
    }
}

void ActionsManager::play()
{
    if( THEPL->current.i_size == 0 )
    {
        /* The playlist is empty, open a file requester */
        THEDP->openFileDialog();
        return;
    }
    THEMIM->togglePlayPause();
}

/**
  * TODO
 * This functions toggle the fullscreen mode
 * If there is no video, it should first activate Visualisations...
 *  This has also to be fixed in enableVideo()
 */
void ActionsManager::fullscreen()
{
    bool fs = var_ToggleBool( THEPL, "fullscreen" );
    vout_thread_t *p_vout = THEMIM->getVout();
    if( p_vout)
    {
        var_SetBool( p_vout, "fullscreen", fs );
        vlc_object_release( p_vout );
    }
}

void ActionsManager::snapshot()
{
    vout_thread_t *p_vout = THEMIM->getVout();
    if( p_vout )
    {
        var_TriggerCallback( p_vout, "video-snapshot" );
        vlc_object_release( p_vout );
    }
}

void ActionsManager::playlist()
{
    if( p_intf->p_sys->p_mi ) p_intf->p_sys->p_mi->togglePlaylist();
}

void ActionsManager::record()
{
    input_thread_t *p_input = THEMIM->getInput();
    if( p_input )
    {
        /* This method won't work fine if the stream can't be cut anywhere */
        var_ToggleBool( p_input, "record" );
#if 0
        else
        {
            /* 'record' access-filter is not loaded, we open Save dialog */
            input_item_t *p_item = input_GetItem( p_input );
            if( !p_item )
                return;

            char *psz = input_item_GetURI( p_item );
            if( psz )
                THEDP->streamingDialog( NULL, psz, true );
        }
#endif
    }
}

void ActionsManager::frame()
{
    input_thread_t *p_input = THEMIM->getInput();
    if( p_input )
        var_TriggerCallback( p_input, "frame-next" );
}

void ActionsManager::toggleMuteAudio()
{
     aout_ToggleMute( THEPL, NULL );
}

void ActionsManager::AudioUp()
{
    aout_VolumeUp( THEPL, 1, NULL );
}

void ActionsManager::AudioDown()
{
    aout_VolumeDown( THEPL, 1, NULL );
}

<commit_msg>Qt4: missing qfu() (in commented out code)<commit_after>/*****************************************************************************
 * Controller.cpp : Controller for the main interface
 ****************************************************************************
 * Copyright (C) 2006-2008 the VideoLAN team
 * $Id$
 *
 * Authors: Jean-Baptiste Kempf <jb@videolan.org>
 *          Ilkka Ollakka <ileoo@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * ( at your option ) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <vlc_vout.h>
#include <vlc_aout.h>
#include <vlc_keys.h>

#include "actions_manager.hpp"
#include "dialogs_provider.hpp" /* Opening Dialogs */
#include "input_manager.hpp"
#include "main_interface.hpp" /* Show playlist */

ActionsManager * ActionsManager::instance = NULL;

ActionsManager::ActionsManager( intf_thread_t * _p_i, QObject *_parent )
               : QObject( _parent )
{
    p_intf = _p_i;
}

ActionsManager::~ActionsManager(){}

void ActionsManager::doAction( int id_action )
{
    switch( id_action )
    {
        case PLAY_ACTION:
            play(); break;
        case STOP_ACTION:
            THEMIM->stop(); break;
        case OPEN_ACTION:
            THEDP->openDialog(); break;
        case PREVIOUS_ACTION:
            THEMIM->prev(); break;
        case NEXT_ACTION:
            THEMIM->next(); break;
        case SLOWER_ACTION:
            THEMIM->getIM()->slower(); break;
        case FASTER_ACTION:
            THEMIM->getIM()->faster(); break;
        case FULLSCREEN_ACTION:
            fullscreen(); break;
        case EXTENDED_ACTION:
            THEDP->extendedDialog(); break;
        case PLAYLIST_ACTION:
            playlist(); break;
        case SNAPSHOT_ACTION:
            snapshot(); break;
        case RECORD_ACTION:
            record(); break;
        case FRAME_ACTION:
            frame(); break;
        case ATOB_ACTION:
            THEMIM->getIM()->setAtoB(); break;
        case REVERSE_ACTION:
            THEMIM->getIM()->reverse(); break;
        case SKIP_BACK_ACTION:
            var_SetInteger( p_intf->p_libvlc, "key-action",
                    ACTIONID_JUMP_BACKWARD_SHORT );
            break;
        case SKIP_FW_ACTION:
            var_SetInteger( p_intf->p_libvlc, "key-action",
                    ACTIONID_JUMP_FORWARD_SHORT );
            break;
        case QUIT_ACTION:
            THEDP->quit();  break;
        case RANDOM_ACTION:
            THEMIM->toggleRandom(); break;
        case INFO_ACTION:
            THEDP->mediaInfoDialog(); break;
        default:
            msg_Dbg( p_intf, "Action: %i", id_action );
            break;
    }
}

void ActionsManager::play()
{
    if( THEPL->current.i_size == 0 )
    {
        /* The playlist is empty, open a file requester */
        THEDP->openFileDialog();
        return;
    }
    THEMIM->togglePlayPause();
}

/**
  * TODO
 * This functions toggle the fullscreen mode
 * If there is no video, it should first activate Visualisations...
 *  This has also to be fixed in enableVideo()
 */
void ActionsManager::fullscreen()
{
    bool fs = var_ToggleBool( THEPL, "fullscreen" );
    vout_thread_t *p_vout = THEMIM->getVout();
    if( p_vout)
    {
        var_SetBool( p_vout, "fullscreen", fs );
        vlc_object_release( p_vout );
    }
}

void ActionsManager::snapshot()
{
    vout_thread_t *p_vout = THEMIM->getVout();
    if( p_vout )
    {
        var_TriggerCallback( p_vout, "video-snapshot" );
        vlc_object_release( p_vout );
    }
}

void ActionsManager::playlist()
{
    if( p_intf->p_sys->p_mi ) p_intf->p_sys->p_mi->togglePlaylist();
}

void ActionsManager::record()
{
    input_thread_t *p_input = THEMIM->getInput();
    if( p_input )
    {
        /* This method won't work fine if the stream can't be cut anywhere */
        var_ToggleBool( p_input, "record" );
#if 0
        else
        {
            /* 'record' access-filter is not loaded, we open Save dialog */
            input_item_t *p_item = input_GetItem( p_input );
            if( !p_item )
                return;

            char *psz = input_item_GetURI( p_item );
            if( psz )
                THEDP->streamingDialog( NULL, qfu(psz), true );
        }
#endif
    }
}

void ActionsManager::frame()
{
    input_thread_t *p_input = THEMIM->getInput();
    if( p_input )
        var_TriggerCallback( p_input, "frame-next" );
}

void ActionsManager::toggleMuteAudio()
{
     aout_ToggleMute( THEPL, NULL );
}

void ActionsManager::AudioUp()
{
    aout_VolumeUp( THEPL, 1, NULL );
}

void ActionsManager::AudioDown()
{
    aout_VolumeDown( THEPL, 1, NULL );
}

<|endoftext|>


<commit_before>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
 */

#include "python_module.h"

namespace kroll
{
	PythonEvaluator::PythonEvaluator() :
		StaticBoundObject("Python.Evaluator")
	{
		SetMethod("canEvaluate", &PythonEvaluator::CanEvaluate);
		SetMethod("evaluate", &PythonEvaluator::Evaluate);
	}

	void PythonEvaluator::CanEvaluate(const ValueList& args, KValueRef result)
	{
		args.VerifyException("canEvaluate", "s");

		result->SetBool(false);
		std::string mimeType = args.GetString(0);
		if (mimeType == "text/python")
		{
			result->SetBool(true);
		}
	}

	void PythonEvaluator::Evaluate(const ValueList& args, KValueRef result)
	{
		PyLockGIL lock;
		args.VerifyException("evaluate", "s s s o");

		//const char *mimeType = args.GetString(0).c_str();
		const char *name = args.GetString(1).c_str();
		std::string code = args.GetString(2);
		KObjectRef windowGlobal = args.GetObject(3);

		// We must unindent the code block to prevent parsing errors.
		PythonEvaluator::UnindentCode(code);

		// Insert all the js global properties into a copy of globals()
		PyObject* mainModule = PyImport_AddModule("__main__");
		PyObject* globals = PyDict_Copy(PyModule_GetDict(mainModule));
		KObjectPropsToDict(windowGlobal, globals);

		// Another way to do this is to use a Python sub-interpreter,
		// but that seems to put us into restricted execution mode
		// sometimes. So we're going to try to isolate the variables
		// in this script by compiling it and supplying our own copy
		// of the globals.
		PyObject* compiled = Py_CompileStringFlags(code.c_str(), name, Py_file_input, NULL);
		if (compiled == NULL)
		{
			Logger *logger = Logger::Get("Python");
			std::string error("An error occured while parsing Python on the page: ");
			error.append(PythonUtils::PythonErrorToString());
			logger->Error(error);

			PyErr_Print();
			Py_DECREF(globals);
			result->SetUndefined();
			return;
		}

		PyObject *returnValue = PyEval_EvalCode((PyCodeObject*) compiled, globals, globals);

		// Clear the error indicator before doing anything else. It might
		// cause a a false positive for errors in other bits of Python.
		// TODO: Logging
		KValueRef kv = Value::Undefined;
		if (returnValue == NULL && PyErr_Occurred())
		{
			Logger *logger = Logger::Get("Python");
			std::string error("An error occured while parsing Python on the page: ");
			error.append(PythonUtils::PythonErrorToString());
			logger->Error(error);

			PyErr_Print();
		}
		else
		{
			KValueRef kv = PythonUtils::ToKrollValue(returnValue);
			Py_DECREF(returnValue);
		}

		// Move all the new variables in globals() to the window context.
		// These are things that are now defined globally in JS.
		DictToKObjectProps(globals, windowGlobal);
		result->SetValue(kv);
	}

	void PythonEvaluator::KObjectPropsToDict(KObjectRef o, PyObject* pyobj)
	{
		PyObject* builtins = PyDict_GetItemString(pyobj, "__builtins__");

		SharedStringList props = o->GetPropertyNames();
		for (size_t i = 0; i < props->size(); i++)
		{
			const char* k = props->at(i)->c_str();

			// Don't override builtin Python properties like open, etc. We *do* want
			// to override the PRODUCT_NAME object though, as each window contains a
			// version of that object with special delegated properties.
			if ((!PyDict_GetItemString(pyobj, k) && !PyObject_HasAttrString(builtins, k))
					|| !strcmp(k, PRODUCT_NAME))
			{
				KValueRef v = o->Get(k);
				PyObject* pv = PythonUtils::ToPyObject(v);
				PyDict_SetItemString(pyobj, k, pv);
				Py_DECREF(pv);
			}
		}
	}

	void PythonEvaluator::DictToKObjectProps(PyObject* dict, KObjectRef o)
	{
		// Avoid compiler warnings
		PyObject *items = PyObject_CallMethod(dict, (char*) "items", NULL);
		if (items == NULL)
			return;

		PyObject *iterator = PyObject_GetIter(items);
		if (iterator == NULL)
			return;

		PyObject *item;
		while ((item = PyIter_Next(iterator)))
		{
			PyObject* k = PyTuple_GetItem(item, 0);
			PyObject* v = PyTuple_GetItem(item, 1);
			std::string sk = PythonUtils::ToString(k);
			if (sk.find("__") != 0)
			{
				KValueRef newValue = PythonUtils::ToKrollValue(v);
				KValueRef existingValue = o->Get(sk.c_str());
				if (!newValue->Equals(existingValue))
				{
					o->Set(sk.c_str(), newValue);
				}
			}
			Py_DECREF(item);
		}
	}

	void PythonEvaluator::UnindentCode(std::string &code)
	{
		// Determine indent width of the code block
		size_t startOffset = code.find_first_not_of("\r\n");  // ignore any newlines at start of block
		size_t blockIndent = code.find_first_not_of(" \t", startOffset) - startOffset;
		if (blockIndent == 0) return;

		std::string dirtyCode = code.substr(startOffset);
		code.clear();

		// Process code line by line unindenting code
		Poco::StringTokenizer lines(dirtyCode, "\n");
		Poco::StringTokenizer::Iterator i;
		for (i = lines.begin(); i != lines.end(); i++)
		{
			std::string line = *i;
			if (line.length() > 0)
			{
				size_t lineIndent = line.find_first_not_of(" \t");
				if (lineIndent < blockIndent)
				{
					// If the line has a smaller indent than the block, warn the user!
					throw ValueException::FromFormat("Indentation error in script: %s", line.c_str());
				}
				code.append(line, blockIndent, line.length() - blockIndent);
			}
			code.append(1, '\n');
		}
	}
}
<commit_msg>Fix the python unidenting code to ignore whitespace only lines.<commit_after>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
 */

#include "python_module.h"

namespace kroll
{
	PythonEvaluator::PythonEvaluator() :
		StaticBoundObject("Python.Evaluator")
	{
		SetMethod("canEvaluate", &PythonEvaluator::CanEvaluate);
		SetMethod("evaluate", &PythonEvaluator::Evaluate);
	}

	void PythonEvaluator::CanEvaluate(const ValueList& args, KValueRef result)
	{
		args.VerifyException("canEvaluate", "s");

		result->SetBool(false);
		std::string mimeType = args.GetString(0);
		if (mimeType == "text/python")
		{
			result->SetBool(true);
		}
	}

	void PythonEvaluator::Evaluate(const ValueList& args, KValueRef result)
	{
		PyLockGIL lock;
		args.VerifyException("evaluate", "s s s o");

		//const char *mimeType = args.GetString(0).c_str();
		const char *name = args.GetString(1).c_str();
		std::string code = args.GetString(2);
		KObjectRef windowGlobal = args.GetObject(3);

		// We must unindent the code block to prevent parsing errors.
		PythonEvaluator::UnindentCode(code);

		// Insert all the js global properties into a copy of globals()
		PyObject* mainModule = PyImport_AddModule("__main__");
		PyObject* globals = PyDict_Copy(PyModule_GetDict(mainModule));
		KObjectPropsToDict(windowGlobal, globals);

		// Another way to do this is to use a Python sub-interpreter,
		// but that seems to put us into restricted execution mode
		// sometimes. So we're going to try to isolate the variables
		// in this script by compiling it and supplying our own copy
		// of the globals.
		PyObject* compiled = Py_CompileStringFlags(code.c_str(), name, Py_file_input, NULL);
		if (compiled == NULL)
		{
			Logger *logger = Logger::Get("Python");
			std::string error("An error occured while parsing Python on the page: ");
			error.append(PythonUtils::PythonErrorToString());
			logger->Error(error);

			PyErr_Print();
			Py_DECREF(globals);
			result->SetUndefined();
			return;
		}

		PyObject *returnValue = PyEval_EvalCode((PyCodeObject*) compiled, globals, globals);

		// Clear the error indicator before doing anything else. It might
		// cause a a false positive for errors in other bits of Python.
		// TODO: Logging
		KValueRef kv = Value::Undefined;
		if (returnValue == NULL && PyErr_Occurred())
		{
			Logger *logger = Logger::Get("Python");
			std::string error("An error occured while parsing Python on the page: ");
			error.append(PythonUtils::PythonErrorToString());
			logger->Error(error);

			PyErr_Print();
		}
		else
		{
			KValueRef kv = PythonUtils::ToKrollValue(returnValue);
			Py_DECREF(returnValue);
		}

		// Move all the new variables in globals() to the window context.
		// These are things that are now defined globally in JS.
		DictToKObjectProps(globals, windowGlobal);
		result->SetValue(kv);
	}

	void PythonEvaluator::KObjectPropsToDict(KObjectRef o, PyObject* pyobj)
	{
		PyObject* builtins = PyDict_GetItemString(pyobj, "__builtins__");

		SharedStringList props = o->GetPropertyNames();
		for (size_t i = 0; i < props->size(); i++)
		{
			const char* k = props->at(i)->c_str();

			// Don't override builtin Python properties like open, etc. We *do* want
			// to override the PRODUCT_NAME object though, as each window contains a
			// version of that object with special delegated properties.
			if ((!PyDict_GetItemString(pyobj, k) && !PyObject_HasAttrString(builtins, k))
					|| !strcmp(k, PRODUCT_NAME))
			{
				KValueRef v = o->Get(k);
				PyObject* pv = PythonUtils::ToPyObject(v);
				PyDict_SetItemString(pyobj, k, pv);
				Py_DECREF(pv);
			}
		}
	}

	void PythonEvaluator::DictToKObjectProps(PyObject* dict, KObjectRef o)
	{
		// Avoid compiler warnings
		PyObject *items = PyObject_CallMethod(dict, (char*) "items", NULL);
		if (items == NULL)
			return;

		PyObject *iterator = PyObject_GetIter(items);
		if (iterator == NULL)
			return;

		PyObject *item;
		while ((item = PyIter_Next(iterator)))
		{
			PyObject* k = PyTuple_GetItem(item, 0);
			PyObject* v = PyTuple_GetItem(item, 1);
			std::string sk = PythonUtils::ToString(k);
			if (sk.find("__") != 0)
			{
				KValueRef newValue = PythonUtils::ToKrollValue(v);
				KValueRef existingValue = o->Get(sk.c_str());
				if (!newValue->Equals(existingValue))
				{
					o->Set(sk.c_str(), newValue);
				}
			}
			Py_DECREF(item);
		}
	}

	void PythonEvaluator::UnindentCode(std::string &code)
	{
		// Determine indent width of the code block
		size_t startOffset = code.find_first_not_of("\r\n");  // ignore any newlines at start of block
		size_t blockIndent = code.find_first_not_of(" \t", startOffset) - startOffset;
		if (blockIndent == 0) return;

		std::string dirtyCode = code.substr(startOffset);
		code.clear();

		// Process code line by line unindenting code
		Poco::StringTokenizer lines(dirtyCode, "\n");
		Poco::StringTokenizer::Iterator i;
		for (i = lines.begin(); i != lines.end(); i++)
		{
			std::string line = *i;
			if (line.length() > 0)
			{
				size_t lineIndent = line.find_first_not_of(" \t");

				if (lineIndent == std::string::npos)
				{
					// Allow lines with only whitespace to pass through.
					code.append(line);
				}
				else if (lineIndent < blockIndent)
				{
					// If the line has a smaller indent than the block, warn the user!
					throw ValueException::FromFormat("Indentation error in script: %s", line.c_str());
				}
				else
				{
					code.append(line, blockIndent, line.length() - blockIndent);
				}
			}
			code.append(1, '\n');
		}
	}
}
<|endoftext|>


<commit_before>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
 */

#include "python_module.h"

	SharedValue PythonEvaluator::Call(const ValueList& args)
	{
		if (args.size() != 3
			|| !args.at(1)->IsString()
			|| !args.at(2)->IsObject())
		{
			return Value::Undefined;
		}

		// Normalize tabs and convert line-feeds
		std::string code = args[1]->ToString();
		PythonEvaluator::StripLeadingWhitespace(code);
		PythonEvaluator::ConvertLineEndings(code);

		// Each script has it's own sub-interpreter
		PyThreadState* previous_state = PyThreadState_Get();
		PyThreadState* ts = Py_NewInterpreter();
		PyThreadState_Swap(ts);

		// Insert all the global properties into __builtins__
		SharedKObject window_global = args.at(2)->ToObject();
		PyObject* main_module = PyImport_AddModule("__main__");
		PyObject* globals = PyModule_GetDict(main_module);
		PyObject* builtins = PyDict_GetItemString(globals, "__builtins__");
		KObjectPropsToDict(window_global, builtins);

		// Run the script and retrieve the locals()
		PyObject *return_value = PyRun_String(
			code.c_str(),
			Py_file_input,
			globals,
			globals);
		PyObject* locals = PyRun_String("locals()", Py_eval_input, globals, globals);

		// Move all the new variables in locals() to  the
		// window context. These are things that are now defined.
		DictToKObjectProps(locals, window_global);

		/* TODO: Logging */
		SharedValue kv = Value::Undefined;
		if (return_value == NULL && PyErr_Occurred())
		{
			std::cout << "An error occured while parsing Python on the page: " << std::endl;
			PyErr_Print();
		}
		else
		{
			SharedValue kv = PythonUtils::ToKrollValue(return_value);
			Py_DECREF(return_value);
		}

		// Switch back to the global thread state
		PyThreadState_Swap(previous_state);

		return kv;
	}

	void PythonEvaluator::KObjectPropsToDict(SharedKObject o, PyObject* pyobj)
	{
		SharedStringList props = o->GetPropertyNames();
		for (size_t i = 0; i < props->size(); i++)
		{
			const char* k = props->at(i)->c_str();
			SharedValue v = o->Get(k);
			PyObject* pv = PythonUtils::ToPyObject(v);
			PyObject_SetAttrString(pyobj, k, pv);
			Py_DECREF(pv);
		}
	}

	void PythonEvaluator::DictToKObjectProps(PyObject* dict, SharedKObject o)
	{
		// Avoid compiler warnings
		PyObject *items = PyObject_CallMethod(dict, (char*) "items", NULL);
		if (items == NULL)
			return;

		PyObject *iterator = PyObject_GetIter(items);
		if (iterator == NULL)
			return;

		PyObject *item;
		while ((item = PyIter_Next(iterator))) {
			PyObject* k = PyTuple_GetItem(item, 0);
			PyObject* v = PyTuple_GetItem(item, 1);
			std::string sk = PythonUtils::ToString(k);

			if (sk.find("__") != 0)
			{
				SharedValue kv = PythonUtils::ToKrollValue(v);
				o->Set(sk.c_str(), kv);
			}
			Py_DECREF(item);
		}
	}

	void PythonEvaluator::Set(const char *name, SharedValue value)
	{
	}

	SharedValue PythonEvaluator::Get(const char *name)
	{
		return Value::Undefined;
	}

	SharedStringList PythonEvaluator::GetPropertyNames()
	{
		return SharedStringList();
	}

	void PythonEvaluator::StripLeadingWhitespace(std::string &code)
	{
		size_t startpos = code.find_first_not_of(" \t\n");
		if (std::string::npos != startpos)
			code.replace(0, startpos, "");
	}

	void PythonEvaluator::ConvertLineEndings(std::string &code)
	{
		std::string::size_type loc = code.find("\r\n");
		while (loc != std::string::npos)
		{
			code.replace(loc, 2, "\n");
			loc = code.find("\r\n");
		}
	}
<commit_msg>TI-203: Don't override Python builtins in Python Evaluator<commit_after>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
 */

#include "python_module.h"

	SharedValue PythonEvaluator::Call(const ValueList& args)
	{
		if (args.size() != 3
			|| !args.at(1)->IsString()
			|| !args.at(2)->IsObject())
		{
			return Value::Undefined;
		}

		// Normalize tabs and convert line-feeds
		std::string code = args[1]->ToString();
		PythonEvaluator::StripLeadingWhitespace(code);
		PythonEvaluator::ConvertLineEndings(code);

		// Each script has it's own sub-interpreter
		PyThreadState* previous_state = PyThreadState_Get();
		PyThreadState* ts = Py_NewInterpreter();
		PyThreadState_Swap(ts);

		// Insert all the global properties into __builtins__
		SharedKObject window_global = args.at(2)->ToObject();
		PyObject* main_module = PyImport_AddModule("__main__");
		PyObject* globals = PyModule_GetDict(main_module);
		PyObject* builtins = PyDict_GetItemString(globals, "__builtins__");
		KObjectPropsToDict(window_global, builtins);

		// Run the script and retrieve the locals()
		PyObject *return_value = PyRun_String(
			code.c_str(),
			Py_file_input,
			globals,
			globals);
		PyObject* locals = PyRun_String("locals()", Py_eval_input, globals, globals);

		// Move all the new variables in locals() to  the
		// window context. These are things that are now defined.
		DictToKObjectProps(locals, window_global);

		/* TODO: Logging */
		SharedValue kv = Value::Undefined;
		if (return_value == NULL && PyErr_Occurred())
		{
			std::cout << "An error occured while parsing Python on the page: " << std::endl;
			PyErr_Print();
		}
		else
		{
			SharedValue kv = PythonUtils::ToKrollValue(return_value);
			Py_DECREF(return_value);
		}

		// Switch back to the global thread state
		PyThreadState_Swap(previous_state);

		return kv;
	}

	void PythonEvaluator::KObjectPropsToDict(SharedKObject o, PyObject* pyobj)
	{
		SharedStringList props = o->GetPropertyNames();
		for (size_t i = 0; i < props->size(); i++)
		{
			const char* k = props->at(i)->c_str();
			if (!PyObject_HasAttrString(pyobj, k))
			{
				SharedValue v = o->Get(k);
				PyObject* pv = PythonUtils::ToPyObject(v);
				PyObject_SetAttrString(pyobj, k, pv);
				Py_DECREF(pv);
			}
		}
	}

	void PythonEvaluator::DictToKObjectProps(PyObject* dict, SharedKObject o)
	{
		// Avoid compiler warnings
		PyObject *items = PyObject_CallMethod(dict, (char*) "items", NULL);
		if (items == NULL)
			return;

		PyObject *iterator = PyObject_GetIter(items);
		if (iterator == NULL)
			return;

		PyObject *item;
		while ((item = PyIter_Next(iterator))) {
			PyObject* k = PyTuple_GetItem(item, 0);
			PyObject* v = PyTuple_GetItem(item, 1);
			std::string sk = PythonUtils::ToString(k);

			if (sk.find("__") != 0)
			{
				SharedValue kv = PythonUtils::ToKrollValue(v);
				o->Set(sk.c_str(), kv);
			}
			Py_DECREF(item);
		}
	}

	void PythonEvaluator::Set(const char *name, SharedValue value)
	{
	}

	SharedValue PythonEvaluator::Get(const char *name)
	{
		return Value::Undefined;
	}

	SharedStringList PythonEvaluator::GetPropertyNames()
	{
		return SharedStringList();
	}

	void PythonEvaluator::StripLeadingWhitespace(std::string &code)
	{
		size_t startpos = code.find_first_not_of(" \t\n");
		if (std::string::npos != startpos)
			code.replace(0, startpos, "");
	}

	void PythonEvaluator::ConvertLineEndings(std::string &code)
	{
		std::string::size_type loc = code.find("\r\n");
		while (loc != std::string::npos)
		{
			code.replace(loc, 2, "\n");
			loc = code.find("\r\n");
		}
	}
<|endoftext|>


<commit_before>//
// Visualization of Gaussians in 2D, using GLUT
//

//
//
// Plan
// - Submit an array of 2D information matrices
// and an array of x, y means
// - Render an array summing an exp of them exp(x)
//

#include <Eigen/Dense>

#include <GL/freeglut.h>

#include <cuda_gl_interop.h>
#include <cuda_profiler_api.h>
#include <cuda_runtime.h>
#include <driver_functions.h>
#include <vector_functions.h>
#include <vector_types.h>

#include <cstdio>
#include <cstdlib>

#include <helper_cuda.h>
#include <helper_math.h>

#include <cuda_gl_interop.h>
#include <helper_gl.h>

template <typename Derived> using EigStdVector = std::vector<Derived, Eigen::aligned_allocator<Derived>>;

void render_kernel(dim3             gridSize,
                   dim3             blockSize,
                   uint *           d_output,
                   uint             imageW,
                   uint             imageH,
                   float            scale,
                   float2           view_center,
                   Eigen::Vector2f *means,
                   Eigen::Matrix2f *information_matrices,
                   int              N,
                   float            normalization,
                   float            tstep);

int iDivUp(int a, int b) {
  return (a % b != 0) ? (a / b + 1) : (a / b);
}

struct State {
  float2 view_center      = make_float2(0.0, 0.0);
  float2 prev_view_center = make_float2(0.0, 0.0);
  float2 prev_mouse_pos   = make_float2(0.0, 0.0);

  // OpenGL pixel buffer object
  GLuint pbo = 0;

  // OpenGL texture object
  GLuint tex = 0;

  // CUDA Graphics Resource (to transfer PBO)
  struct cudaGraphicsResource *cuda_pbo_resource;

  // Image render dimensions
  uint width  = 512;
  uint height = 512;

  float scale = 1.0;

  dim3 blockSize = dim3(16, 16);
  dim3 gridSize  = dim3(iDivUp(width, blockSize.x), iDivUp(height, blockSize.y));

  //
  // Rendering paramters
  //
  float       time_step    = 0.0;
  float       direction    = 1.0;
  const float time_spacing = 0.005;
  const float min_time     = 0.5;

  //
  // Distribution paramters
  //
  EigStdVector<Eigen::Vector2f> means;
  EigStdVector<Eigen::Matrix2f> information_matrices;
  float                         normalization = 1.0;

  Eigen::Vector2f *d_means;
  Eigen::Matrix2f *d_covariances;

} gstate;

void initGL(int *argc, char **argv) {
  // initialize GLUT callback functions
  glutInit(argc, argv);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
  glutInitWindowSize(gstate.width, gstate.height);
  glutCreateWindow("CUDA volume rendering");

  if (!isGLVersionSupported(2, 0) || !areGLExtensionsSupported("GL_ARB_pixel_buffer_object")) {
    printf("Required OpenGL extensions are missing.");
    exit(EXIT_SUCCESS);
  }
}

void initPixelBuffer() {
  if (gstate.pbo) {
    // unregister this buffer object from CUDA C
    checkCudaErrors(cudaGraphicsUnregisterResource(gstate.cuda_pbo_resource));

    // delete old buffer
    glDeleteBuffers(1, &(gstate.pbo));
    glDeleteTextures(1, &(gstate.tex));
  }

  // create pixel buffer object for display
  glGenBuffers(1, &(gstate.pbo));
  glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, gstate.pbo);
  glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, gstate.width * gstate.height * sizeof(GLubyte) * 4, 0, GL_STREAM_DRAW_ARB);
  glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

  // register this buffer object with CUDA
  checkCudaErrors(
      cudaGraphicsGLRegisterBuffer(&(gstate.cuda_pbo_resource), gstate.pbo, cudaGraphicsMapFlagsWriteDiscard));

  // create texture for display
  glGenTextures(1, &(gstate.tex));
  glBindTexture(GL_TEXTURE_2D, gstate.tex);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, gstate.width, gstate.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glBindTexture(GL_TEXTURE_2D, 0);
}

void send_parameters(const EigStdVector<Eigen::Vector2f> &means,
                     const EigStdVector<Eigen::Matrix2f> &information_matrices) {
  const int n = means.size();

  checkCudaErrors(cudaMalloc((void **)&(gstate.d_means), sizeof(Eigen::Vector2f) * n));
  checkCudaErrors(cudaMalloc((void **)&(gstate.d_covariances), sizeof(Eigen::Matrix2f) * n));

  checkCudaErrors(cudaMemcpy(gstate.d_means, means.data(), sizeof(Eigen::Vector2f) * n, cudaMemcpyHostToDevice));
  checkCudaErrors(cudaMemcpy(gstate.d_covariances, information_matrices.data(), sizeof(Eigen::Matrix2f) * n,
                             cudaMemcpyHostToDevice));
}

float compute_eta(const EigStdVector<Eigen::Vector2f> &means,
                  const EigStdVector<Eigen::Matrix2f> &information_matrices) {
  float sum_norm = 0.0;
  for (size_t k = 0; k < means.size(); ++k) {
    const float norm = sqrt((2.0f * 3.14f / information_matrices[k].determinant()));
    sum_norm += norm;
  }
  return sum_norm;
}
void render() {
  uint *d_output;
  checkCudaErrors(cudaGraphicsMapResources(1, &(gstate.cuda_pbo_resource), 0));

  size_t num_bytes;
  checkCudaErrors(cudaGraphicsResourceGetMappedPointer((void **)&d_output, &num_bytes, gstate.cuda_pbo_resource));

  checkCudaErrors(cudaMemset(d_output, 0, gstate.width * gstate.height * 4));

  // Create performance metrics
  cudaEvent_t start, stop;
  cudaEventCreate(&start);
  cudaEventCreate(&stop);

  cudaEventRecord(start);

  if (gstate.time_step >= 1.0) {
    gstate.direction = -1.0;
  } else if (gstate.time_step <= gstate.min_time) {
    gstate.direction = 1.0;
  }
  gstate.time_step += gstate.time_spacing * gstate.direction;
  std::cout << gstate.time_step << std::endl;

  // Render the acutal image
  render_kernel(gstate.gridSize, gstate.blockSize, d_output, gstate.width, gstate.height, gstate.scale,
                gstate.view_center, gstate.d_means, gstate.d_covariances, gstate.information_matrices.size(),
                gstate.normalization, gstate.time_step);

  cudaEventRecord(stop);
  cudaEventSynchronize(stop);

  float milliseconds = 0;
  cudaEventElapsedTime(&milliseconds, start, stop);

  checkCudaErrors(cudaGraphicsUnmapResources(1, &(gstate.cuda_pbo_resource), 0));
}

// display results using OpenGL (called by GLUT)
void display() {
  // use OpenGL to build view matrix
  GLfloat modelView[16];
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  glGetFloatv(GL_MODELVIEW_MATRIX, modelView);
  glPopMatrix();
  render();

  // Display results
  glClear(GL_COLOR_BUFFER_BIT);
  glDisable(GL_DEPTH_TEST);
  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

  //
  // Prepare render to texture
  //
  glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, gstate.pbo);
  glBindTexture(GL_TEXTURE_2D, gstate.tex);
  glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, gstate.width, gstate.height, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

  //
  // Draw the texture on the simplest quad
  //
  // Draw textured quad
  glEnable(GL_TEXTURE_2D);
  glBegin(GL_QUADS);

  // This is just a quad that occupies the whole screen
  glTexCoord2f(0, 0);
  glVertex2f(-1, -1);
  glTexCoord2f(1, 0);
  glVertex2f(1, -1);
  glTexCoord2f(1, 1);
  glVertex2f(1, 1);
  glTexCoord2f(0, 1);
  glVertex2f(-1, 1);

  glEnd();

  glDisable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, 0);

  //
  // And it's over
  //

  glutSwapBuffers();
  glutReportErrors();
}

void idle() {
  glutPostRedisplay();
}

void motion(int x, int y) {
  float2 mouse_pos = make_float2(x, y);

  float2 delta_pos = (mouse_pos - gstate.prev_mouse_pos) / (gstate.height / 2.0);

  gstate.view_center = make_float2(-delta_pos.x, delta_pos.y) + gstate.prev_view_center;

  glutPostRedisplay();
}

void mouse(int button, int state, int x, int y) {
  int mods;

  float2 mouse_pos = make_float2(x, y);
  if (state == GLUT_DOWN) {
    gstate.prev_mouse_pos = mouse_pos;
  } else if (state == GLUT_UP) {
    gstate.prev_view_center = gstate.view_center;
  }

  if ((button == 3) || (button == 4)) // It's a wheel event
  {
    if (state == GLUT_UP)
      return;

    gstate.scale *= (button == 3) ? 0.9 : 1.1;

    // printf("Scroll %s At %d %d\n", (button == 3) ? "Up" : "Down", x, y);
  }

  std::cout << gstate.view_center.x << " , " << gstate.view_center.y << " :: " << gstate.scale << std::endl;
}

void keyboard(unsigned char key, int x, int y) {
  switch (key) {
  case 27:
    glutDestroyWindow(glutGetWindow());
    return;

  case 'f':
    break;

  case 'G':
    std::cout << "Resetting" << std::endl;
    gstate.view_center = make_float2(0.0, 0.0);
    gstate.scale       = 1.0f;
    break;

  case 'q':
  case 'Q':
    std::cout << "Attempting to exit" << std::endl;
    glutDestroyWindow(glutGetWindow());
    return;

  default:
    break;
  }

  glutPostRedisplay();
}

int main(int argc, char **argv) {
#if defined(__linux__)
  setenv("DISPLAY", ":0", 0);
#endif
  std::cout << "Jake cuViewer starting\n" << std::endl;

  //
  // Initialize openGL
  //
  initGL(&argc, argv);

  //
  // Initialize glut
  //
  glutMouseFunc(mouse);
  glutMotionFunc(motion);
  glutDisplayFunc(display);
  glutKeyboardFunc(keyboard);
  glutIdleFunc(idle);

  //
  // Zero the pbo
  //
  initPixelBuffer();

  const int count = 25;
  for (int k = 0; k < count; ++k) {
    const Eigen::Vector2f mean = Eigen::Vector2f::Random() * 5.0;

    const Eigen::Vector2f    diag = (Eigen::Vector2f::Random().array() + 1.25f).matrix();
    const float              rand = Eigen::Vector2f::Random()(0);
    const Eigen::Rotation2Df rot  = Eigen::Rotation2Df(rand);
    const Eigen::Matrix2f    cov  = rot * diag.asDiagonal() * rot.inverse();
    gstate.means.emplace_back(mean);
    gstate.information_matrices.emplace_back(cov);
  }
  send_parameters(gstate.means, gstate.information_matrices);
  const float eta      = compute_eta(gstate.means, gstate.information_matrices);
  gstate.normalization = static_cast<float>(count) / eta;

  glutMainLoop();
}
<commit_msg>Move comments around in cuda gaussians<commit_after>//
// Visualization of Gaussians in 2D, using GLUT
//

//
//
// Plan
// - Submit an array of 2D information matrices
// and an array of x, y means
// - Render an array summing an exp of them exp(x)
//

#include <Eigen/Dense>

#include <GL/freeglut.h>

#include <cuda_gl_interop.h>
#include <cuda_profiler_api.h>
#include <cuda_runtime.h>
#include <driver_functions.h>
#include <vector_functions.h>
#include <vector_types.h>

#include <cstdio>
#include <cstdlib>

#include <helper_cuda.h>
#include <helper_math.h>

#include <cuda_gl_interop.h>
#include <helper_gl.h>

template <typename Derived> using EigStdVector = std::vector<Derived, Eigen::aligned_allocator<Derived>>;

void render_kernel(dim3             gridSize,
                   dim3             blockSize,
                   uint *           d_output,
                   uint             imageW,
                   uint             imageH,
                   float            scale,
                   float2           view_center,
                   Eigen::Vector2f *means,
                   Eigen::Matrix2f *information_matrices,
                   int              N,
                   float            normalization,
                   float            tstep);

int iDivUp(int a, int b) {
  return (a % b != 0) ? (a / b + 1) : (a / b);
}

struct State {
  float2 view_center      = make_float2(0.0, 0.0);
  float2 prev_view_center = make_float2(0.0, 0.0);
  float2 prev_mouse_pos   = make_float2(0.0, 0.0);

  // OpenGL pixel buffer object
  GLuint pbo = 0;

  // OpenGL texture object
  GLuint tex = 0;

  // CUDA Graphics Resource (to transfer PBO)
  struct cudaGraphicsResource *cuda_pbo_resource;

  // Image render dimensions
  uint width  = 512;
  uint height = 512;

  float scale = 1.0;

  dim3 blockSize = dim3(16, 16);
  dim3 gridSize  = dim3(iDivUp(width, blockSize.x), iDivUp(height, blockSize.y));

  //
  // Rendering paramters
  //
  float       time_step    = 0.0;
  float       direction    = 1.0;
  const float time_spacing = 0.005;
  const float min_time     = 0.5;

  //
  // Distribution paramters
  //
  EigStdVector<Eigen::Vector2f> means;
  EigStdVector<Eigen::Matrix2f> information_matrices;
  float                         normalization = 1.0;

  Eigen::Vector2f *d_means;
  Eigen::Matrix2f *d_covariances;

} gstate;

void initGL(int *argc, char **argv) {
  // initialize GLUT callback functions
  glutInit(argc, argv);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
  glutInitWindowSize(gstate.width, gstate.height);
  glutCreateWindow("CUDA volume rendering");

  if (!isGLVersionSupported(2, 0) || !areGLExtensionsSupported("GL_ARB_pixel_buffer_object")) {
    printf("Required OpenGL extensions are missing.");
    exit(EXIT_SUCCESS);
  }
}

void initPixelBuffer() {
  if (gstate.pbo) {
    // unregister this buffer object from CUDA C
    checkCudaErrors(cudaGraphicsUnregisterResource(gstate.cuda_pbo_resource));

    // delete old buffer
    glDeleteBuffers(1, &(gstate.pbo));
    glDeleteTextures(1, &(gstate.tex));
  }

  // create pixel buffer object for display
  glGenBuffers(1, &(gstate.pbo));
  glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, gstate.pbo);
  glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, gstate.width * gstate.height * sizeof(GLubyte) * 4, 0, GL_STREAM_DRAW_ARB);
  glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

  // register this buffer object with CUDA
  checkCudaErrors(
      cudaGraphicsGLRegisterBuffer(&(gstate.cuda_pbo_resource), gstate.pbo, cudaGraphicsMapFlagsWriteDiscard));

  // create texture for display
  glGenTextures(1, &(gstate.tex));
  glBindTexture(GL_TEXTURE_2D, gstate.tex);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, gstate.width, gstate.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glBindTexture(GL_TEXTURE_2D, 0);
}

void send_parameters(const EigStdVector<Eigen::Vector2f> &means,
                     const EigStdVector<Eigen::Matrix2f> &information_matrices) {
  const int n = means.size();

  checkCudaErrors(cudaMalloc((void **)&(gstate.d_means), sizeof(Eigen::Vector2f) * n));
  checkCudaErrors(cudaMalloc((void **)&(gstate.d_covariances), sizeof(Eigen::Matrix2f) * n));

  checkCudaErrors(cudaMemcpy(gstate.d_means, means.data(), sizeof(Eigen::Vector2f) * n, cudaMemcpyHostToDevice));
  checkCudaErrors(cudaMemcpy(gstate.d_covariances, information_matrices.data(), sizeof(Eigen::Matrix2f) * n,
                             cudaMemcpyHostToDevice));
}

float compute_eta(const EigStdVector<Eigen::Vector2f> &means,
                  const EigStdVector<Eigen::Matrix2f> &information_matrices) {
  float sum_norm = 0.0;
  for (size_t k = 0; k < means.size(); ++k) {
    const float norm = sqrt((2.0f * 3.14f / information_matrices[k].determinant()));
    sum_norm += norm;
  }
  return sum_norm;
}
void render() {
  uint *d_output;
  checkCudaErrors(cudaGraphicsMapResources(1, &(gstate.cuda_pbo_resource), 0));

  size_t num_bytes;
  checkCudaErrors(cudaGraphicsResourceGetMappedPointer((void **)&d_output, &num_bytes, gstate.cuda_pbo_resource));

  checkCudaErrors(cudaMemset(d_output, 0, gstate.width * gstate.height * 4));

  // Create performance metrics
  cudaEvent_t start, stop;
  cudaEventCreate(&start);
  cudaEventCreate(&stop);

  cudaEventRecord(start);

  if (gstate.time_step >= 1.0) {
    gstate.direction = -1.0;
  } else if (gstate.time_step <= gstate.min_time) {
    gstate.direction = 1.0;
  }
  gstate.time_step += gstate.time_spacing * gstate.direction;
  std::cout << gstate.time_step << std::endl;

  // Render the acutal image
  render_kernel(gstate.gridSize, gstate.blockSize, d_output, gstate.width, gstate.height, gstate.scale,
                gstate.view_center, gstate.d_means, gstate.d_covariances, gstate.information_matrices.size(),
                gstate.normalization, gstate.time_step);

  cudaEventRecord(stop);
  cudaEventSynchronize(stop);

  float milliseconds = 0;
  cudaEventElapsedTime(&milliseconds, start, stop);

  checkCudaErrors(cudaGraphicsUnmapResources(1, &(gstate.cuda_pbo_resource), 0));
}

// display results using OpenGL (called by GLUT)
void display() {
  // use OpenGL to build view matrix
  GLfloat modelView[16];
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  glGetFloatv(GL_MODELVIEW_MATRIX, modelView);
  glPopMatrix();
  render();

  // Display results
  glClear(GL_COLOR_BUFFER_BIT);
  glDisable(GL_DEPTH_TEST);
  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

  //
  // Prepare render to texture
  //
  glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, gstate.pbo);
  glBindTexture(GL_TEXTURE_2D, gstate.tex);
  glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, gstate.width, gstate.height, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

  //
  // Draw the texture on the simplest quad
  //
  // Draw textured quad
  glEnable(GL_TEXTURE_2D);
  glBegin(GL_QUADS);

  // This is just a quad that occupies the whole screen
  glTexCoord2f(0, 0);
  glVertex2f(-1, -1);
  glTexCoord2f(1, 0);
  glVertex2f(1, -1);
  glTexCoord2f(1, 1);
  glVertex2f(1, 1);
  glTexCoord2f(0, 1);
  glVertex2f(-1, 1);

  glEnd();

  glDisable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, 0);

  //
  // And it's over
  //

  glutSwapBuffers();
  glutReportErrors();
}

void idle() {
  glutPostRedisplay();
}

void motion(int x, int y) {
  float2 mouse_pos = make_float2(x, y);

  float2 delta_pos = (mouse_pos - gstate.prev_mouse_pos) / (gstate.height / 2.0);

  gstate.view_center = make_float2(-delta_pos.x, delta_pos.y) + gstate.prev_view_center;

  glutPostRedisplay();
}

void mouse(int button, int state, int x, int y) {
  int mods;

  float2 mouse_pos = make_float2(x, y);
  if (state == GLUT_DOWN) {
    gstate.prev_mouse_pos = mouse_pos;
  } else if (state == GLUT_UP) {
    gstate.prev_view_center = gstate.view_center;
  }

  // It's a wheel event
  if ((button == 3) || (button == 4))
  {
    if (state == GLUT_UP)
      return;

    gstate.scale *= (button == 3) ? 0.9 : 1.1;
  }

  std::cout << gstate.view_center.x << " , " << gstate.view_center.y << " :: " << gstate.scale << std::endl;
}

void keyboard(unsigned char key, int x, int y) {
  switch (key) {
  case 27:
    glutDestroyWindow(glutGetWindow());
    return;

  case 'f':
    break;

  case 'G':
    std::cout << "Resetting" << std::endl;
    gstate.view_center = make_float2(0.0, 0.0);
    gstate.scale       = 1.0f;
    break;

  case 'q':
  case 'Q':
    std::cout << "Attempting to exit" << std::endl;
    glutDestroyWindow(glutGetWindow());
    return;

  default:
    break;
  }

  glutPostRedisplay();
}

int main(int argc, char **argv) {
#if defined(__linux__)
  setenv("DISPLAY", ":0", 0);
#endif
  std::cout << "Jake cuViewer starting\n" << std::endl;

  //
  // Initialize openGL
  //
  initGL(&argc, argv);

  //
  // Initialize glut
  //
  glutMouseFunc(mouse);
  glutMotionFunc(motion);
  glutDisplayFunc(display);
  glutKeyboardFunc(keyboard);
  glutIdleFunc(idle);

  //
  // Zero the pbo
  //
  initPixelBuffer();

  const int count = 25;
  for (int k = 0; k < count; ++k) {
    const Eigen::Vector2f mean = Eigen::Vector2f::Random() * 5.0;

    const Eigen::Vector2f    diag = (Eigen::Vector2f::Random().array() + 1.25f).matrix();
    const float              rand = Eigen::Vector2f::Random()(0);
    const Eigen::Rotation2Df rot  = Eigen::Rotation2Df(rand);
    const Eigen::Matrix2f    cov  = rot * diag.asDiagonal() * rot.inverse();
    gstate.means.emplace_back(mean);
    gstate.information_matrices.emplace_back(cov);
  }
  send_parameters(gstate.means, gstate.information_matrices);
  const float eta      = compute_eta(gstate.means, gstate.information_matrices);
  gstate.normalization = static_cast<float>(count) / eta;

  glutMainLoop();
}
<|endoftext|>


<commit_before>#pragma once

#include <unordered_map>
#include "base/singleton.hpp"
#include "sub_invoke.hpp"

namespace czrpc
{
namespace client
{

class sub_router
{
    DEFINE_SINGLETON(sub_router);
public:
    sub_router() = default;

    template<typename Function>
    void bind(const std::string& protocol, const Function& func)
    {
        check_bind(protocol);
        bind_non_member_func(protocol, func);
    }

    template<typename Function, typename Self>
    void bind(const std::string& protocol, const Function& func, Self* self)
    {
        check_bind(protocol);
        bind_member_func(protocol, func, self);
    }

    void unbind(const std::string& protocol)
    {
        std::lock_guard<std::mutex> lock(map_mutex_);
        invoker_map_.erase(protocol);
    }

    bool is_bind(const std::string& protocol)
    {
        std::lock_guard<std::mutex> lock(map_mutex_);
        auto iter = invoker_map_.find(protocol);
        if (iter != invoker_map_.end())
        {
            return true;
        }
        return false;
    }

    template<typename Function>
    void bind_raw(const std::string& protocol, const Function& func)
    {
        check_bind_raw(protocol);
        bind_non_member_func_raw(protocol, func);
    }

    template<typename Function, typename Self>
    void bind_raw(const std::string& protocol, const Function& func, Self* self)
    {
        check_bind_raw(protocol);
        bind_member_func_raw(protocol, func, self);
    }

    void unbind_raw(const std::string& protocol)
    {
        std::lock_guard<std::mutex> lock(raw_map_mutex_);
        invoker_raw_map_.erase(protocol);
    }

    bool is_bind_raw(const std::string& protocol)
    {
        std::lock_guard<std::mutex> lock(raw_map_mutex_);
        auto iter = invoker_raw_map_.find(protocol);
        if (iter != invoker_raw_map_.end())
        {
            return true;
        }
        return false;
    }

    bool route_raw(const std::string& protocol, const std::string& req)
    {
        std::lock_guard<std::mutex> lock(raw_map_mutex_);
        auto iter = invoker_raw_map_.find(protocol);
        if (iter != invoker_raw_map_.end())
        {
            iter->second(req);
            return true;
        }
        return false;
    }

    bool route(const std::string& protocol, const std::string& message_name, const std::string& req)
    {
        std::lock_guard<std::mutex> lock(map_mutex_);
        auto iter = invoker_map_.find(protocol);
        if (iter != invoker_map_.end())
        {
            iter->second(message_name, req);
            return true;
        }
        return false;
    }

    std::vector<std::string> get_all_topic()
    {
        std::vector<std::string> topic_vec;

        std::unique_lock<std::mutex> lock(map_mutex_);
        for (auto& invoker : invoker_map_)
        {
            topic_vec.emplace_back(invoker.first);
        }
        lock.unlock();

        std::unique_lock<std::mutex> raw_lock(raw_map_mutex_);
        for (auto& invoker : invoker_raw_map_)
        {
            topic_vec.emplace_back(invoker.first);
        }
        raw_lock.unlock();

        return std::move(topic_vec);
    }

private:
    template<typename Function>
    void bind_non_member_func(const std::string& protocol, const Function& func)
    {
        std::lock_guard<std::mutex> lock(map_mutex_);
        invoker_map_.emplace(protocol, sub_invoker_function{ std::bind(&invoker<Function>::apply, func, std::placeholders::_1) });
    }

    template<typename Function, typename Self>
    void bind_member_func(const std::string& protocol, const Function& func, Self* self)
    {
        std::lock_guard<std::mutex> lock(map_mutex_);
        invoker_map_.emplace(protocol, sub_invoker_function{ std::bind(&invoker<Function>::template apply_member<Self>, func, self, std::placeholders::_1) });
    }

    template<typename Function>
    void bind_non_member_func_raw(const std::string& protocol, const Function& func)
    {
        std::lock_guard<std::mutex> lock(raw_map_mutex_);
        invoker_raw_map_.emplace(protocol, sub_invoker_function_raw{ std::bind(&invoker_raw<Function>::apply, func, std::placeholders::_1) });
    }

    template<typename Function, typename Self>
    void bind_member_func_raw(const std::string& protocol, const Function& func, Self* self)
    {
        std::lock_guard<std::mutex> lock(raw_map_mutex_);
        invoker_raw_map_.emplace(protocol, sub_invoker_function_raw{ std::bind(&invoker_raw<Function>::template apply_member<Self>, func, self, std::placeholders::_1) });
    }

    void check_bind(const std::string& protocol)
    {
        if (is_bind(protocol))
        {
            throw std::runtime_error(protocol + " was binded");
        }
    }

    void check_bind_raw(const std::string& protocol)
    {
        if (is_bind_raw(protocol))
        {
            throw std::runtime_error(protocol + " was binded");
        }
    }

private:
    std::unordered_map<std::string, sub_invoker_function> invoker_map_;
    std::unordered_map<std::string, sub_invoker_function_raw> invoker_raw_map_;
    std::mutex map_mutex_;
    std::mutex raw_map_mutex_;
};

}
}

<commit_msg>update router<commit_after>#pragma once

#include "base/table/threadsafe_unordered_map.hpp"
#include "base/singleton.hpp"
#include "sub_invoke.hpp"

using namespace czrpc::base::table;

namespace czrpc
{
namespace client
{

class sub_router
{
    DEFINE_SINGLETON(sub_router);
public:
    sub_router() = default;

    template<typename Function>
    void bind(const std::string& protocol, const Function& func)
    {
        route_map_.replace(protocol, sub_invoker_function{ std::bind(&invoker<Function>::apply, func, std::placeholders::_1) });
    }

    template<typename Function, typename Self>
    void bind(const std::string& protocol, const Function& func, Self* self)
    {
        route_map_.replace(protocol, sub_invoker_function{ std::bind(&invoker<Function>::template apply_member<Self>, func, self, std::placeholders::_1) });
    }

    template<typename Function>
    void bind_raw(const std::string& protocol, const Function& func)
    {
        route_raw_map_.replace(protocol, sub_invoker_function_raw{ std::bind(&invoker_raw<Function>::apply, func, std::placeholders::_1) });
    }

    template<typename Function, typename Self>
    void bind_raw(const std::string& protocol, const Function& func, Self* self)
    {
        route_raw_map_.replace(protocol, sub_invoker_function_raw{ std::bind(&invoker_raw<Function>::template apply_member<Self>, func, self, std::placeholders::_1) });
    }

    void unbind(const std::string& protocol)
    {
        route_map_.erase(protocol);
    }

    bool is_bind(const std::string& protocol)
    {
        return route_map_.exists(protocol);
    }

    void unbind_raw(const std::string& protocol)
    {
        route_raw_map_.erase(protocol);
    }

    bool is_bind_raw(const std::string& protocol)
    {
        return route_raw_map_.exists(protocol);
    }

    bool route_raw(const std::string& protocol, const std::string& req)
    {
        sub_invoker_function_raw func;
        if (route_raw_map_.find(protocol, func))
        {
            func(req);
            return true;
        }
        return false;
    }

    bool route(const std::string& protocol, const std::string& message_name, const std::string& req)
    {
        sub_invoker_function func;
        if (route_map_.find(protocol, func))
        {
            func(message_name, req);
            return true;
        }
        return false;
    }

    std::vector<std::string> get_all_topic()
    {
        std::vector<std::string> topic_vec;

        route_map_.for_each([&](const std::string& protocol, const sub_invoker_function&)
        {
            topic_vec.emplace_back(protocol);
        });

        route_raw_map_.for_each([&](const std::string& protocol, const sub_invoker_function_raw&)
        {
            topic_vec.emplace_back(protocol);
        });

        return std::move(topic_vec);
    }

private:
    threadsafe_unordered_map<std::string, sub_invoker_function> route_map_;
    threadsafe_unordered_map<std::string, sub_invoker_function_raw> route_raw_map_;
};

}
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2017, The DART development contributors
 * All rights reserved.
 *
 * The list of contributors can be found at:
 *   https://github.com/dartsim/dart/blob/master/LICENSE
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   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.
 */

#ifndef DART_COMMON_NAMEMANAGER_HPP_
#define DART_COMMON_NAMEMANAGER_HPP_

#include <map>
#include <string>

namespace dart {
namespace common {

/// \brief class NameManager
///
/// Typical usage:
/// \code{.cpp}
/// using namespace dart;
///
/// NameManager<BodyNode*> nameMgr;
///
/// BodyNode* bodyNode = new BodyNode();
/// std::string name = "Link";
///
/// if (!nameMgr.hasName(name)
///   nameMgr.addName(name, bodyNode);  // "Link"
/// else
///   name = nameMgr.issueNewNameAndAdd(name, bodyNode);  // "Link1"
///
/// bodyNode->setName(name);
/// \endcode
template <typename T>
class NameManager
{
public:
  /// Constructor
  NameManager(const std::string& _managerName = "default",
              const std::string& _defaultName = "default");

  /// Destructor
  virtual ~NameManager() = default;

  /// Set a new pattern for name generation.
  ///
  /// Use %s to indicate the base name and use %d to indicate where the number
  /// belongs. The pattern must contain both a %s and a %d.
  ///
  /// Examples:
  /// "%s(%d)" : name -> name(1) -> name(2)
  /// "%d-%s" : name -> 1-name -> 2-name
  ///
  /// returns false if the pattern was invalid (i.e. did not contain b
  /// oth %s and %d)
  bool setPattern(const std::string& _newPattern);

  /// Issue new unique combined name of given base name and number suffix
  std::string issueNewName(const std::string& _name) const;

  /// Call issueNewName() and add the result to the map
  std::string issueNewNameAndAdd(const std::string& _name, const T& _obj);

  /// Add an object to the map
  bool addName(const std::string& _name, const T& _obj);

  /// Remove an object from the Manager based on its name
  bool removeName(const std::string& _name);

  /// Remove an object from the Manager based on reverse lookup
  bool removeObject(const T& _obj);

  /// Remove _name using the forward lookup and _obj using the reverse lookup.
  /// This will allow you to add _obj under the name _name without any conflicts
  void removeEntries(const std::string& _name, const T& _obj);

  /// Clear all the objects
  void clear();

  /// Return true if the name is contained
  bool hasName(const std::string& _name) const;

  /// Return true if the object is contained
  bool hasObject(const T& _obj) const;

  /// Get the number of the objects currently stored by the NameManager
  std::size_t getCount() const;

  /// Get object by given name
  /// \param[in] _name
  ///   Name of the requested object
  /// \return
  ///   The object if it exists, or nullptr if it does not exist
  T getObject(const std::string& _name) const;

  /// Use a reverse lookup to get the name that the manager has _obj listed
  /// under. Returns an empty string if it is not in the list.
  std::string getName(const T& _obj) const;

  /// Change the name of a currently held object. This will do nothing if the
  /// object is already using _newName or if the object is not held by this
  /// NameManager.
  ///
  /// If the object is held, its new name is returned (which might
  /// be different than _newName if there was a duplicate naming conflict). If
  /// the object is not held, an empty string will be returned.
  std::string changeObjectName(const T& _obj, const std::string& _newName);

  /// Set the name that will be provided to objects passed in with an empty
  /// string for a name
  void setDefaultName(const std::string& _defaultName);

  /// Get the name that will be provided to objects passed in with an empty
  /// string for a name
  const std::string& getDefaultName() const;

  /// Set the name of this NameManager so that it can be printed in error reports
  void setManagerName(const std::string& _managerName);

  /// Get the name of this NameManager
  const std::string& getManagerName() const;

protected:
  /// Name of this NameManager. This is used to report errors.
  std::string mManagerName;

  /// Map of objects that have been added to the NameManager
  std::map<std::string, T> mMap;

  /// Reverse map of objects that have been added to the NameManager
  std::map<T, std::string> mReverseMap;

  /// String which will be used as a name for any object which is passed in with
  /// an empty string name
  std::string mDefaultName;

  /// Internal variable used to arrange the text when resolving duplicate names
  bool mNameBeforeNumber;

  /// The chunk of text that gets prepended to a duplicate name
  std::string mPrefix;

  /// The chunk of text that comes between a duplicate name and its duplication
  /// number
  std::string mInfix;

  /// The chunk of text that gets appended to a duplicate name
  std::string mAffix;
};

} // namespace common
} // namespace dart

#include "dart/common/detail/NameManager.hpp"

#endif // DART_COMMON_NAMEMANAGER_HPP_
<commit_msg>Fix typo<commit_after>/*
 * Copyright (c) 2011-2017, The DART development contributors
 * All rights reserved.
 *
 * The list of contributors can be found at:
 *   https://github.com/dartsim/dart/blob/master/LICENSE
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   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.
 */

#ifndef DART_COMMON_NAMEMANAGER_HPP_
#define DART_COMMON_NAMEMANAGER_HPP_

#include <map>
#include <string>

namespace dart {
namespace common {

/// \brief class NameManager
///
/// Typical usage:
/// \code{.cpp}
/// using namespace dart;
///
/// NameManager<BodyNode*> nameMgr;
///
/// BodyNode* bodyNode = new BodyNode();
/// std::string name = "Link";
///
/// if (!nameMgr.hasName(name))
///   nameMgr.addName(name, bodyNode);  // "Link"
/// else
///   name = nameMgr.issueNewNameAndAdd(name, bodyNode);  // "Link1"
///
/// bodyNode->setName(name);
/// \endcode
template <typename T>
class NameManager
{
public:
  /// Constructor
  NameManager(const std::string& _managerName = "default",
              const std::string& _defaultName = "default");

  /// Destructor
  virtual ~NameManager() = default;

  /// Set a new pattern for name generation.
  ///
  /// Use %s to indicate the base name and use %d to indicate where the number
  /// belongs. The pattern must contain both a %s and a %d.
  ///
  /// Examples:
  /// "%s(%d)" : name -> name(1) -> name(2)
  /// "%d-%s" : name -> 1-name -> 2-name
  ///
  /// returns false if the pattern was invalid (i.e. did not contain b
  /// oth %s and %d)
  bool setPattern(const std::string& _newPattern);

  /// Issue new unique combined name of given base name and number suffix
  std::string issueNewName(const std::string& _name) const;

  /// Call issueNewName() and add the result to the map
  std::string issueNewNameAndAdd(const std::string& _name, const T& _obj);

  /// Add an object to the map
  bool addName(const std::string& _name, const T& _obj);

  /// Remove an object from the Manager based on its name
  bool removeName(const std::string& _name);

  /// Remove an object from the Manager based on reverse lookup
  bool removeObject(const T& _obj);

  /// Remove _name using the forward lookup and _obj using the reverse lookup.
  /// This will allow you to add _obj under the name _name without any conflicts
  void removeEntries(const std::string& _name, const T& _obj);

  /// Clear all the objects
  void clear();

  /// Return true if the name is contained
  bool hasName(const std::string& _name) const;

  /// Return true if the object is contained
  bool hasObject(const T& _obj) const;

  /// Get the number of the objects currently stored by the NameManager
  std::size_t getCount() const;

  /// Get object by given name
  /// \param[in] _name
  ///   Name of the requested object
  /// \return
  ///   The object if it exists, or nullptr if it does not exist
  T getObject(const std::string& _name) const;

  /// Use a reverse lookup to get the name that the manager has _obj listed
  /// under. Returns an empty string if it is not in the list.
  std::string getName(const T& _obj) const;

  /// Change the name of a currently held object. This will do nothing if the
  /// object is already using _newName or if the object is not held by this
  /// NameManager.
  ///
  /// If the object is held, its new name is returned (which might
  /// be different than _newName if there was a duplicate naming conflict). If
  /// the object is not held, an empty string will be returned.
  std::string changeObjectName(const T& _obj, const std::string& _newName);

  /// Set the name that will be provided to objects passed in with an empty
  /// string for a name
  void setDefaultName(const std::string& _defaultName);

  /// Get the name that will be provided to objects passed in with an empty
  /// string for a name
  const std::string& getDefaultName() const;

  /// Set the name of this NameManager so that it can be printed in error reports
  void setManagerName(const std::string& _managerName);

  /// Get the name of this NameManager
  const std::string& getManagerName() const;

protected:
  /// Name of this NameManager. This is used to report errors.
  std::string mManagerName;

  /// Map of objects that have been added to the NameManager
  std::map<std::string, T> mMap;

  /// Reverse map of objects that have been added to the NameManager
  std::map<T, std::string> mReverseMap;

  /// String which will be used as a name for any object which is passed in with
  /// an empty string name
  std::string mDefaultName;

  /// Internal variable used to arrange the text when resolving duplicate names
  bool mNameBeforeNumber;

  /// The chunk of text that gets prepended to a duplicate name
  std::string mPrefix;

  /// The chunk of text that comes between a duplicate name and its duplication
  /// number
  std::string mInfix;

  /// The chunk of text that gets appended to a duplicate name
  std::string mAffix;
};

} // namespace common
} // namespace dart

#include "dart/common/detail/NameManager.hpp"

#endif // DART_COMMON_NAMEMANAGER_HPP_
<|endoftext|>


<commit_before>#ifndef _SNARKFRONT_SHA_224_HPP_
#define _SNARKFRONT_SHA_224_HPP_

#include <array>
#include <cstdint>
#include "Alg.hpp"
#include "Alg_uint.hpp"
#include "AST.hpp"
#include "BitwiseAST.hpp"
#include "BitwiseINT.hpp"
#include "Lazy.hpp"
#include "SHA_256.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// SHA-224
//

template <typename T, typename MSG, typename U, typename F>
class SHA_224 : public SHA_256<T, MSG, U, F>
{
public:
    typedef T WordType;
    typedef U ByteType;

    typedef std::array<T, 16> MsgType;
    typedef std::array<T, 7> DigType;
    typedef std::array<U, 16 * 4> PreType;

    SHA_224()
        : m_setDigest(false)
    {}

    // overrides base class SHA-256
    const std::array<T, 7>& digest() {
        if (m_setDigest) {
            for (std::size_t i = 0; i < 7; ++i) {
                m_Hleft224[i] = this->m_H[i];
            }

            m_setDigest = false;
        }

        return m_Hleft224;
    }

    // overrides base class SHA-256
    virtual void initHashValue() {
        // set initial hash value (NIST FIPS 180-4 section 5.3.2)
        const std::array<std::uint32_t, 8> a {
            0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
            0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 };

        for (std::size_t i = 0; i < 8; ++i) {
            this->m_H[i] = F::constant(a[i]);
        }
    }

    virtual void afterHash() {
        m_setDigest = true;
    }

private:
    // truncated 224-bit message digest
    std::array<T, 7> m_Hleft224;

    bool m_setDigest;
};

////////////////////////////////////////////////////////////////////////////////
// typedefs
//

namespace zk {
    template <typename FR> using
    SHA224 = SHA_224<AST_Var<Alg_uint32<FR>>,
                     Lazy<AST_Var<Alg_uint32<FR>>, std::uint32_t>,
                     AST_Var<Alg_uint8<FR>>,
                     SHA_Functions<AST_Node<Alg_uint32<FR>>,
                                   AST_Op<Alg_uint32<FR>>,
                                   BitwiseAST<Alg_uint32<FR>>>>;
} // namespace zk

namespace eval {
    typedef SHA_224<std::uint32_t,
                    std::uint32_t,
                    std::uint8_t,
                    SHA_Functions<std::uint32_t,
                                  std::uint32_t,
                                  BitwiseINT<std::uint32_t>>>
        SHA224;
} // namespace eval

} // namespace snarkfront

#endif
<commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_SHA_224_HPP_
#define _SNARKFRONT_SHA_224_HPP_

#include <array>
#include <cstdint>

#include <snarkfront/Alg.hpp>
#include <snarkfront/Alg_uint.hpp>
#include <snarkfront/AST.hpp>
#include <snarkfront/BitwiseAST.hpp>
#include <snarkfront/BitwiseINT.hpp>
#include <snarkfront/Lazy.hpp>
#include <snarkfront/SHA_256.hpp>

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// SHA-224
//

template <typename T, typename MSG, typename U, typename F>
class SHA_224 : public SHA_256<T, MSG, U, F>
{
public:
    typedef T WordType;
    typedef U ByteType;

    typedef std::array<T, 16> MsgType;
    typedef std::array<T, 7> DigType;
    typedef std::array<U, 16 * 4> PreType;

    SHA_224()
        : m_setDigest(false)
    {}

    // overrides base class SHA-256
    const std::array<T, 7>& digest() {
        if (m_setDigest) {
            for (std::size_t i = 0; i < 7; ++i) {
                m_Hleft224[i] = this->m_H[i];
            }

            m_setDigest = false;
        }

        return m_Hleft224;
    }

    // overrides base class SHA-256
    virtual void initHashValue() {
        // set initial hash value (NIST FIPS 180-4 section 5.3.2)
        const std::array<std::uint32_t, 8> a {
            0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
            0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 };

        for (std::size_t i = 0; i < 8; ++i) {
            this->m_H[i] = F::constant(a[i]);
        }
    }

    virtual void afterHash() {
        m_setDigest = true;
    }

private:
    // truncated 224-bit message digest
    std::array<T, 7> m_Hleft224;

    bool m_setDigest;
};

////////////////////////////////////////////////////////////////////////////////
// typedefs
//

namespace zk {
    template <typename FR> using
    SHA224 = SHA_224<AST_Var<Alg_uint32<FR>>,
                     Lazy<AST_Var<Alg_uint32<FR>>, std::uint32_t>,
                     AST_Var<Alg_uint8<FR>>,
                     SHA_Functions<AST_Node<Alg_uint32<FR>>,
                                   AST_Op<Alg_uint32<FR>>,
                                   BitwiseAST<Alg_uint32<FR>>>>;
} // namespace zk

namespace eval {
    typedef SHA_224<std::uint32_t,
                    std::uint32_t,
                    std::uint8_t,
                    SHA_Functions<std::uint32_t,
                                  std::uint32_t,
                                  BitwiseINT<std::uint32_t>>>
        SHA224;
} // namespace eval

} // namespace snarkfront

#endif
<|endoftext|>