<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: textcharacterproperties.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/drawingml/textcharacterproperties.hxx"

#include "oox/helper/propertyset.hxx"
#include "oox/core/namespaces.hxx"
#include "tokens.hxx"

using rtl::OUString;
using namespace ::oox::core;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;

namespace oox { namespace drawingml {

TextCharacterProperties::TextCharacterProperties()
: maCharColorPtr( new Color() )
, maUnderlineColorPtr( new Color() )
, maHighlightColorPtr( new Color() )
{
}
TextCharacterProperties::~TextCharacterProperties()
{
}
void TextCharacterProperties::apply( const TextCharacterPropertiesPtr& rSourceTextCharacterPropertiesPtr )
{
    maTextCharacterPropertyMap.insert( rSourceTextCharacterPropertiesPtr->maTextCharacterPropertyMap.begin(), rSourceTextCharacterPropertiesPtr->maTextCharacterPropertyMap.end() );
    maHyperlinkPropertyMap.insert( rSourceTextCharacterPropertiesPtr->maHyperlinkPropertyMap.begin(), rSourceTextCharacterPropertiesPtr->maHyperlinkPropertyMap.end() );
    ColorPtr rSourceCharColor( rSourceTextCharacterPropertiesPtr->getCharColor() );
    if ( rSourceCharColor->isUsed() )
        maCharColorPtr = rSourceCharColor;
    ColorPtr rSourceHighlightColor( rSourceTextCharacterPropertiesPtr->getHighlightColor() );
    if ( rSourceHighlightColor->isUsed() )
        maHighlightColorPtr = rSourceHighlightColor;
    ColorPtr rSourceUnderlineColor( rSourceTextCharacterPropertiesPtr->getUnderlineColor() );
    if ( rSourceUnderlineColor->isUsed() )
        maUnderlineColorPtr = rSourceUnderlineColor;
    Any& rHasUnderline = rSourceTextCharacterPropertiesPtr->getHasUnderline();
    if ( rHasUnderline.hasValue() )
        maHasUnderline = rHasUnderline;
    Any& rUnderlineLineFollowText = rSourceTextCharacterPropertiesPtr->getUnderlineLineFollowText();
    if ( rUnderlineLineFollowText.hasValue() )
        maUnderlineLineFollowText = rUnderlineLineFollowText;
    Any& rUnderlineFillFollowText = rSourceTextCharacterPropertiesPtr->getUnderlineFillFollowText();
    if ( rUnderlineFillFollowText.hasValue() )
        maUnderlineFillFollowText = rUnderlineFillFollowText;
}
void TextCharacterProperties::pushToPropSet( const ::oox::core::XmlFilterBase& rFilterBase, const Reference < XPropertySet > & xPropSet ) const
{
//  maTextCharacterPropertyMap.dump_debug("TextCharacter props");

    PropertySet aPropSet( xPropSet );
    aPropSet.setProperties( maTextCharacterPropertyMap );
    if ( maCharColorPtr->isUsed() )
    {
        const rtl::OUString sCharColor( CREATE_OUSTRING( "CharColor" ) );
        aPropSet.setProperty( sCharColor, maCharColorPtr->getColor( rFilterBase ) );
    }

    sal_Bool bHasUnderline = sal_False;
    sal_Bool bUnderlineFillFollowText = sal_False;
    maHasUnderline >>= bHasUnderline;
    maUnderlineFillFollowText >>= bUnderlineFillFollowText;
    if( bHasUnderline )
    {
        if( maUnderlineColorPtr.get() && !bUnderlineFillFollowText )
        {
            const rtl::OUString sCharUnderlineColor( CREATE_OUSTRING( "CharUnderlineColor" ) );
            aPropSet.setProperty( sCharUnderlineColor, maUnderlineColorPtr->getColor( rFilterBase ) );
            const rtl::OUString sCharUnderlineHasColor( CREATE_OUSTRING( "CharUnderlineHasColor" ) );
            aPropSet.setProperty( sCharUnderlineHasColor, Any( sal_True ) );
        }
    }
}

void TextCharacterProperties::pushToUrlFieldPropSet( const Reference < XPropertySet > & xPropSet ) const
{
    PropertySet aPropSet( xPropSet );
    aPropSet.setProperties( maHyperlinkPropertyMap );
}

float TextCharacterProperties::getCharacterSize( float fDefault ) const
{
    const rtl::OUString sCharHeight( CREATE_OUSTRING( "CharHeight" ) );
    float fCharHeight = 0;
    const Any* pAny = maTextCharacterPropertyMap.getPropertyValue( sCharHeight );
    if ( pAny && ( *pAny >>= fCharHeight ) )
        return fCharHeight;
    else
        return fDefault;
}

} }
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.5.6); FILE MERGED 2008/06/20 14:24:47 dr 1.5.6.3: resolve theme font names, e.g. '+mj-lt' or '+mn-ea' 2008/06/20 11:58:16 dr 1.5.6.2: line/fill/character properties rework; first steps of chart text formatting and rotation import; make line arrow import work 2008/05/27 10:40:35 dr 1.5.6.1: joined changes from CWS xmlfilter05<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: textcharacterproperties.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/drawingml/textcharacterproperties.hxx"
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/awt/FontSlant.hpp>
#include <com/sun/star/awt/FontWeight.hpp>
#include "oox/helper/helper.hxx"
#include "oox/helper/propertyset.hxx"
#include "oox/drawingml/drawingmltypes.hxx"
#include "tokens.hxx"

using ::rtl::OUString;
using ::oox::core::XmlFilterBase;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;

namespace oox {
namespace drawingml {

// ============================================================================

void TextCharacterProperties::assignUsed( const TextCharacterProperties& rSourceProps )
{
    // overwrite all properties exisiting in rSourceProps
    maHyperlinkPropertyMap.insert( rSourceProps.maHyperlinkPropertyMap.begin(), rSourceProps.maHyperlinkPropertyMap.end() );
    maLatinFont.assignIfUsed( rSourceProps.maLatinFont );
    maAsianFont.assignIfUsed( rSourceProps.maAsianFont );
    maComplexFont.assignIfUsed( rSourceProps.maComplexFont );
    maSymbolFont.assignIfUsed( rSourceProps.maSymbolFont );
    maCharColor.assignIfUsed( rSourceProps.maCharColor );
    maHighlightColor.assignIfUsed( rSourceProps.maHighlightColor );
    maUnderlineColor.assignIfUsed( rSourceProps.maUnderlineColor );
    moHeight.assignIfUsed( rSourceProps.moHeight );
    moUnderline.assignIfUsed( rSourceProps.moUnderline );
    moStrikeout.assignIfUsed( rSourceProps.moStrikeout );
    moCaseMap.assignIfUsed( rSourceProps.moCaseMap );
    moBold.assignIfUsed( rSourceProps.moBold );
    moItalic.assignIfUsed( rSourceProps.moItalic );
    moUnderlineLineFollowText.assignIfUsed( rSourceProps.moUnderlineLineFollowText );
    moUnderlineFillFollowText.assignIfUsed( rSourceProps.moUnderlineFillFollowText );
}

void TextCharacterProperties::pushToPropMap( PropertyMap& rPropMap, const XmlFilterBase& rFilter ) const
{
    OUString aFontName;
    sal_Int16 nFontPitch = 0;
    sal_Int16 nFontFamily = 0;

    if( maLatinFont.getFontData( aFontName, nFontPitch, nFontFamily, rFilter ) )
    {
        rPropMap[ CREATE_OUSTRING( "CharFontName" ) ] <<= aFontName;
        rPropMap[ CREATE_OUSTRING( "CharFontPitch" ) ] <<= nFontPitch;
        rPropMap[ CREATE_OUSTRING( "CharFontFamily" ) ] <<= nFontFamily;
    }

    if( maAsianFont.getFontData( aFontName, nFontPitch, nFontFamily, rFilter ) )
    {
        rPropMap[ CREATE_OUSTRING( "CharFontNameAsian" ) ] <<= aFontName;
        rPropMap[ CREATE_OUSTRING( "CharFontPitchAsian" ) ] <<= nFontFamily;
        rPropMap[ CREATE_OUSTRING( "CharFontFamilyAsian" ) ] <<= nFontPitch;
    }

    if( maComplexFont.getFontData( aFontName, nFontPitch, nFontFamily, rFilter ) )
    {
        rPropMap[ CREATE_OUSTRING( "CharFontNameComplex" ) ] <<= aFontName;
        rPropMap[ CREATE_OUSTRING( "CharFontPitchComplex" ) ] <<= nFontPitch;
        rPropMap[ CREATE_OUSTRING( "CharFontFamilyComplex" ) ] <<= nFontFamily;
    }

    // symbol font not supported

    if( maCharColor.isUsed() )
        rPropMap[ CREATE_OUSTRING( "CharColor" ) ] <<= maCharColor.getColor( rFilter );

    if( moLang.has() && (moLang.get().getLength() > 0) )
    {
        lang::Locale aLocale;
        sal_Int32 nSepPos = moLang.get().indexOf( sal_Unicode( '-' ), 0 );
        if ( nSepPos >= 0 )
        {
            aLocale.Language = moLang.get().copy( 0, nSepPos );
            aLocale.Country = moLang.get().copy( nSepPos + 1 );
        }
        else
        {
            aLocale.Language = moLang.get();
        }
        rPropMap[ CREATE_OUSTRING( "CharLocale" ) ] <<= aLocale;
        rPropMap[ CREATE_OUSTRING( "CharLocaleAsian" ) ] <<= aLocale;
        rPropMap[ CREATE_OUSTRING( "CharLocaleComplex" ) ] <<= aLocale;
    }

    if( moHeight.has() )
    {
        float fHeight = GetFontHeight( moHeight.get() );
        rPropMap[ CREATE_OUSTRING( "CharHeight" ) ] <<= fHeight;
        rPropMap[ CREATE_OUSTRING( "CharHeightAsian" ) ] <<= fHeight;
        rPropMap[ CREATE_OUSTRING( "CharHeightComplex" ) ] <<= fHeight;
    }

    rPropMap[ CREATE_OUSTRING( "CharUnderline" ) ] <<= GetFontUnderline( moUnderline.get( XML_none ) );
    rPropMap[ CREATE_OUSTRING( "CharStrikeout" ) ] <<= GetFontStrikeout( moStrikeout.get( XML_noStrike ) );
    rPropMap[ CREATE_OUSTRING( "CharCaseMap" ) ] <<= GetCaseMap( moCaseMap.get( XML_none ) );

    float fWeight = moBold.get( false ) ? awt::FontWeight::BOLD : awt::FontWeight::NORMAL;
    rPropMap[ CREATE_OUSTRING( "CharWeight" ) ] <<= fWeight;
    rPropMap[ CREATE_OUSTRING( "CharWeightAsian" ) ] <<= fWeight;
    rPropMap[ CREATE_OUSTRING( "CharWeightComplex" ) ] <<= fWeight;

    awt::FontSlant eSlant = moItalic.get( false ) ? awt::FontSlant_ITALIC : awt::FontSlant_NONE;
    rPropMap[ CREATE_OUSTRING( "CharPosture" ) ] <<= eSlant;
    rPropMap[ CREATE_OUSTRING( "CharPostureAsian" ) ] <<= eSlant;
    rPropMap[ CREATE_OUSTRING( "CharPostureComplex" ) ] <<= eSlant;

    bool bUnderlineFillFollowText = moUnderlineFillFollowText.get( false );
    if( moUnderline.has() && maUnderlineColor.isUsed() && !bUnderlineFillFollowText )
    {
        rPropMap[ CREATE_OUSTRING( "CharUnderlineHasColor" ) ] <<= true;
        rPropMap[ CREATE_OUSTRING( "CharUnderlineColor" ) ] <<= maUnderlineColor.getColor( rFilter );
    }
}

void TextCharacterProperties::pushToPropSet( PropertySet& rPropSet, const XmlFilterBase& rFilter ) const
{
    PropertyMap aPropMap;
    pushToPropMap( aPropMap, rFilter );
    rPropSet.setProperties( aPropMap );
}

float TextCharacterProperties::getCharHeightPoints( float fDefault ) const
{
    return moHeight.has() ? GetFontHeight( moHeight.get() ) : fDefault;
}

// ============================================================================

} // namespace drawingml
} // namespace oox

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 Daniel Nicoletti <dantti12@gmail.com>
 *
 * 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 Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
#include "enginerequest.h"

#include "common.h"

#include <Cutelyst/response_p.h>
#include <Cutelyst/Context>

#include <QLoggingCategory>
Q_LOGGING_CATEGORY(CUTELYST_ENGINEREQUEST, "cutelyst.engine_request")

using namespace Cutelyst;

EngineRequest::EngineRequest()
{

}

EngineRequest::~EngineRequest()
{
    delete body;
    delete context;
}

void EngineRequest::finalizeBody()
{
    Response *response = context->response();

    if (!(status & EngineRequest::Chunked)) {
        QIODevice *body = response->bodyDevice();

        if (body) {
            body->seek(0);
            char block[64 * 1024];
            while (!body->atEnd()) {
                qint64 in = body->read(block, sizeof(block));
                if (in <= 0) {
                    break;
                }

                if (write(block, in) != in) {
                    qCWarning(CUTELYST_ENGINEREQUEST) << "Failed to write body";
                    break;
                }
            }
        } else {
            const QByteArray bodyByteArray = response->body();
            write(bodyByteArray.constData(), bodyByteArray.size());
        }
    } else if (!(status & EngineRequest::ChunkedDone)) {
        // Write the final '0' chunk
        doWrite("0\r\n\r\n", 5);
    }
}

void EngineRequest::finalizeError()
{
    Response *res = context->response();

    res->setContentType(QStringLiteral("text/html; charset=utf-8"));

    QByteArray body;

    // Trick IE. Old versions of IE would display their own error page instead
    // of ours if we'd give it less than 512 bytes.
    body.reserve(512);

    body.append(context->errors().join(QLatin1Char('\n')).toUtf8());

    res->setBody(body);

    // Return 500
    res->setStatus(Response::InternalServerError);
}

void EngineRequest::finalize()
{
    if (context->error()) {
        finalizeError();
    }

    if (!(status & EngineRequest::FinalizedHeaders) && !finalizeHeaders()) {
        return;
    }

    finalizeBody();
}

void EngineRequest::finalizeCookies()
{
    Response *res = context->response();
    Headers &headers = res->headers();
    const auto cookies = res->cookies();
    for (const QNetworkCookie &cookie : cookies) {
        headers.pushHeader(QStringLiteral("SET_COOKIE"), QString::fromLatin1(cookie.toRawForm()));
    }
}

bool EngineRequest::finalizeHeaders()
{
    Response *response = context->response();
    Headers &headers = response->headers();

    // Fix missing content length
    if (headers.contentLength() < 0) {
        qint64 size = response->size();
        if (size >= 0) {
            headers.setContentLength(size);
        }
    }

    finalizeCookies();

    // Done
    status |= EngineRequest::FinalizedHeaders;
    return writeHeaders(response->status(), headers);
}

qint64 EngineRequest::write(const char *data, qint64 len)
{
    if (!(status & EngineRequest::Chunked)) {
        return doWrite(data, len);
    } else if (!(status & EngineRequest::ChunkedDone)) {
        const QByteArray chunkSize = QByteArray::number(len, 16).toUpper();
        QByteArray chunk;
        chunk.reserve(len + chunkSize.size() + 4);
        chunk.append(chunkSize).append("\r\n", 2)
                .append(data, len).append("\r\n", 2);

        qint64 retWrite = doWrite(chunk.data(), chunk.size());

        // Flag if we wrote an empty chunk
        if (!len) {
            status |= EngineRequest::ChunkedDone;
        }

        return retWrite == chunk.size() ? len : -1;
    }
    return -1;
}

bool EngineRequest::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol)
{
    if (status & EngineRequest::FinalizedHeaders) {
        return false;
    }

    if (webSocketHandshakeDo(key, origin, protocol)) {
        status |= EngineRequest::FinalizedHeaders;
        return true;
    }

    return false;
}

bool EngineRequest::webSocketSendTextMessage(const QString &message)
{
    Q_UNUSED(message)
    return false;
}

bool EngineRequest::webSocketSendBinaryMessage(const QByteArray &message)
{
    Q_UNUSED(message)
    return false;
}

bool EngineRequest::webSocketSendPing(const QByteArray &payload)
{
    Q_UNUSED(payload)
    return false;
}

bool EngineRequest::webSocketClose(quint16 code, const QString &reason)
{
    Q_UNUSED(code)
    Q_UNUSED(reason)
    return false;
}

void EngineRequest::processingFinished()
{
}

bool EngineRequest::webSocketHandshakeDo(const QString &key, const QString &origin, const QString &protocol)
{
    Q_UNUSED(key)
    Q_UNUSED(origin)
    Q_UNUSED(protocol)
    return false;
}

#include "moc_enginerequest.cpp"
<commit_msg>core: Reduce response scope<commit_after>/*
 * Copyright (C) 2017 Daniel Nicoletti <dantti12@gmail.com>
 *
 * 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 Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
#include "enginerequest.h"

#include "common.h"

#include <Cutelyst/response_p.h>
#include <Cutelyst/Context>

#include <QLoggingCategory>
Q_LOGGING_CATEGORY(CUTELYST_ENGINEREQUEST, "cutelyst.engine_request")

using namespace Cutelyst;

EngineRequest::EngineRequest()
{

}

EngineRequest::~EngineRequest()
{
    delete body;
    delete context;
}

void EngineRequest::finalizeBody()
{
    if (!(status & EngineRequest::Chunked)) {
        Response *response = context->response();
        QIODevice *body = response->bodyDevice();

        if (body) {
            body->seek(0);
            char block[64 * 1024];
            while (!body->atEnd()) {
                qint64 in = body->read(block, sizeof(block));
                if (in <= 0) {
                    break;
                }

                if (write(block, in) != in) {
                    qCWarning(CUTELYST_ENGINEREQUEST) << "Failed to write body";
                    break;
                }
            }
        } else {
            const QByteArray bodyByteArray = response->body();
            write(bodyByteArray.constData(), bodyByteArray.size());
        }
    } else if (!(status & EngineRequest::ChunkedDone)) {
        // Write the final '0' chunk
        doWrite("0\r\n\r\n", 5);
    }
}

void EngineRequest::finalizeError()
{
    Response *res = context->response();

    res->setContentType(QStringLiteral("text/html; charset=utf-8"));

    QByteArray body;

    // Trick IE. Old versions of IE would display their own error page instead
    // of ours if we'd give it less than 512 bytes.
    body.reserve(512);

    body.append(context->errors().join(QLatin1Char('\n')).toUtf8());

    res->setBody(body);

    // Return 500
    res->setStatus(Response::InternalServerError);
}

void EngineRequest::finalize()
{
    if (context->error()) {
        finalizeError();
    }

    if (!(status & EngineRequest::FinalizedHeaders) && !finalizeHeaders()) {
        return;
    }

    finalizeBody();
}

void EngineRequest::finalizeCookies()
{
    Response *res = context->response();
    Headers &headers = res->headers();
    const auto cookies = res->cookies();
    for (const QNetworkCookie &cookie : cookies) {
        headers.pushHeader(QStringLiteral("SET_COOKIE"), QString::fromLatin1(cookie.toRawForm()));
    }
}

bool EngineRequest::finalizeHeaders()
{
    Response *response = context->response();
    Headers &headers = response->headers();

    // Fix missing content length
    if (headers.contentLength() < 0) {
        qint64 size = response->size();
        if (size >= 0) {
            headers.setContentLength(size);
        }
    }

    finalizeCookies();

    // Done
    status |= EngineRequest::FinalizedHeaders;
    return writeHeaders(response->status(), headers);
}

qint64 EngineRequest::write(const char *data, qint64 len)
{
    if (!(status & EngineRequest::Chunked)) {
        return doWrite(data, len);
    } else if (!(status & EngineRequest::ChunkedDone)) {
        const QByteArray chunkSize = QByteArray::number(len, 16).toUpper();
        QByteArray chunk;
        chunk.reserve(len + chunkSize.size() + 4);
        chunk.append(chunkSize).append("\r\n", 2)
                .append(data, len).append("\r\n", 2);

        qint64 retWrite = doWrite(chunk.data(), chunk.size());

        // Flag if we wrote an empty chunk
        if (!len) {
            status |= EngineRequest::ChunkedDone;
        }

        return retWrite == chunk.size() ? len : -1;
    }
    return -1;
}

bool EngineRequest::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol)
{
    if (status & EngineRequest::FinalizedHeaders) {
        return false;
    }

    if (webSocketHandshakeDo(key, origin, protocol)) {
        status |= EngineRequest::FinalizedHeaders;
        return true;
    }

    return false;
}

bool EngineRequest::webSocketSendTextMessage(const QString &message)
{
    Q_UNUSED(message)
    return false;
}

bool EngineRequest::webSocketSendBinaryMessage(const QByteArray &message)
{
    Q_UNUSED(message)
    return false;
}

bool EngineRequest::webSocketSendPing(const QByteArray &payload)
{
    Q_UNUSED(payload)
    return false;
}

bool EngineRequest::webSocketClose(quint16 code, const QString &reason)
{
    Q_UNUSED(code)
    Q_UNUSED(reason)
    return false;
}

void EngineRequest::processingFinished()
{
}

bool EngineRequest::webSocketHandshakeDo(const QString &key, const QString &origin, const QString &protocol)
{
    Q_UNUSED(key)
    Q_UNUSED(origin)
    Q_UNUSED(protocol)
    return false;
}

#include "moc_enginerequest.cpp"
<|endoftext|>


<commit_before>#ifndef ALEPH_COMPLEXES_FLANN_HH__
#define ALEPH_COMPLEXES_FLANN_HH__

#include <complexes/NearestNeighbours.hh>

#include <flann/flann.hpp>

namespace aleph
{

namespace complexes
{

template <class Container> class FLANN : public NearestNeighbours< FLANN<Container> >
{
public:
  using ElementType     = typename Container::ElementType;
  using DistanceFunctor = flann::L2<ElementType>;

  FLANN( const Container& container )
    : _container( container )
  {
    _matrix
      = flann::Matrix<ElementType>( container.data(),
                                    container.size(), container.dimension() );

    flann::IndexParams indexParameters
      = flann::KDTreeSingleIndexParams();

    _index
      = new flann::Index<DistanceFunctor>( _matrix, indexParameters );
  }

  ~FLANN()
  {
    delete _index;
  }

private:
  const Container& _container;

  /**
    Copy of container data. This makes interfacing with FLANN easier, at
    the expense of having large storage costs.
  */

  flann::Matrix<ElementType> _matrix;

  /** Index structure for queries. TODO: Make configurable/generic. */
  flann::Index<DistanceFunctor>* _index = nullptr;
};

}

}

#endif
<commit_msg>Basic radius search capabilities for FLANN wrapper<commit_after>#ifndef ALEPH_COMPLEXES_FLANN_HH__
#define ALEPH_COMPLEXES_FLANN_HH__

#include <complexes/NearestNeighbours.hh>

#include <flann/flann.hpp>

#include <algorithm>
#include <vector>

namespace aleph
{

namespace complexes
{

template <class Container> class FLANN : public NearestNeighbours< FLANN<Container> >
{
public:
  using IndexType       = std::size_t;
  using ElementType     = typename Container::ElementType;

  // TODO: Make configurable...
  using DistanceFunctor = flann::L2<ElementType>;

  FLANN( const Container& container )
    : _container( container )
  {
    _matrix
      = flann::Matrix<ElementType>( container.data(),
                                    container.size(), container.dimension() );

    flann::IndexParams indexParameters
      = flann::KDTreeSingleIndexParams();

    _index
      = new flann::Index<DistanceFunctor>( _matrix, indexParameters );
  }

  ~FLANN()
  {
    delete _index;
  }

  void radiusSearch( ElementType radius,
                     std::vector< std::vector<IndexType> >& indices,
                     std::vector< std::vector<ElementType> >& distances )
  {

    flann::SearchParams searchParameters = flann::SearchParams();
    searchParameters.checks = flann::FLANN_CHECKS_UNLIMITED;

    std::vector< std::vector<int> > internalIndices;

    _index->radiusSearch( _matrix,
                          internalIndices,
                          distances,
                          radius,
                          searchParameters );

    // Perform transformation of indices -------------------------------

    indices.clear();
    indices.resize( _matrix.rows );

    for( std::size_t i = 0; i < internalIndices.size(); i++ )
    {
      indices[i] = std::vector<IndexType>( internalIndices[i].size() );

      std::transform( internalIndices[i].begin(), internalIndices[i].end(),
                      indices[i].begin(),
                      [] ( int j )
                      {
                        return static_cast<IndexType>( j );
                      } );
    }
  }

private:
  const Container& _container;

  /**
    Copy of container data. This makes interfacing with FLANN easier, at
    the expense of having large storage costs.
  */

  flann::Matrix<ElementType> _matrix;

  /** Index structure for queries. TODO: Make configurable/generic. */
  flann::Index<DistanceFunctor>* _index = nullptr;
};

}

}

#endif
<|endoftext|>


<commit_before>#include "ruby.h"
#include <osl/state/simpleState.h>
#include <osl/handicap.h>
#include <iostream>

using namespace osl;

void
rb_SimpleState_free(state::SimpleState* ptr)
{
  ptr->~SimpleState();
  ruby_xfree(ptr);
}

static VALUE
rb_SimpleState_allocate(VALUE self)
{
  void* p = ruby_xmalloc(sizeof(state::SimpleState));
  return Data_Wrap_Struct(self, NULL, rb_SimpleState_free, p);
}

static VALUE
rb_SimpleState_initialize(VALUE self)
{
  state::SimpleState* p;
  Data_Get_Struct(self, state::SimpleState, p);
  new (p) state::SimpleState(HIRATE);
  return Qnil;
}

static VALUE
rb_SimpleState_show(VALUE self)
{
  state::SimpleState* p;
  Data_Get_Struct(self, state::SimpleState, p);
  std::cout << *p << std::endl;
  return Qnil;
}

#ifdef __cplusplus
extern "C" {
#endif
void
Init_simpleState(VALUE mState)
{
  VALUE cSimpleState;
  cSimpleState = rb_define_class_under(mState, "SimpleState", rb_cObject);
  rb_define_alloc_func(cSimpleState, rb_SimpleState_allocate);
  rb_define_private_method(cSimpleState, "initialize", RUBY_METHOD_FUNC(rb_SimpleState_initialize), 0);
  rb_define_method(cSimpleState, "show", RUBY_METHOD_FUNC(rb_SimpleState_show), 0);
}
#ifdef __cplusplus
} /* extern "C" */
#endif
<commit_msg>Use "new" style instead of "initialize" style<commit_after>#include "ruby.h"
#include <osl/state/simpleState.h>
#include <osl/handicap.h>
#include <iostream>

using namespace osl;

void
rb_SimpleState_free(state::SimpleState* ptr)
{
  ptr->~SimpleState();
  ruby_xfree(ptr);
}

static VALUE
rb_SimpleState_s_new(VALUE self)
{
  state::SimpleState* p = new state::SimpleState(HIRATE);
  return Data_Wrap_Struct(self, NULL, rb_SimpleState_free, p);
}

static VALUE
rb_SimpleState_show(VALUE self)
{
  state::SimpleState* p;
  Data_Get_Struct(self, state::SimpleState, p);
  std::cout << *p << std::endl;
  return Qnil;
}

#ifdef __cplusplus
extern "C" {
#endif
void
Init_simpleState(VALUE mState)
{
  VALUE cSimpleState;
  cSimpleState = rb_define_class_under(mState, "SimpleState", rb_cObject);
  rb_define_alloc_func(cSimpleState, rb_SimpleState_allocate);
  rb_define_singleton_method(cSimpleState, "new", RUBY_METHOD_FUNC(rb_SimpleState_s_new), 0);
  rb_define_method(cSimpleState, "show", RUBY_METHOD_FUNC(rb_SimpleState_show), 0);
}
#ifdef __cplusplus
} /* extern "C" */
#endif
<|endoftext|>


<commit_before>/*!
 * \file static_resource.cpp
 * \brief file static_resource.cpp
 *
 * Copyright 2016 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#include <fastuidraw/util/util.hpp>
#include <map>
#include <vector>

#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/reference_counted.hpp>
#include <fastuidraw/util/static_resource.hpp>

#include "../private/util_private.hpp"

namespace
{
  class resource_hoard:fastuidraw::noncopyable
  {
  public:
    std::map<std::string, std::vector<uint8_t> > m_data;
    fastuidraw::mutex m_mutex;
  };

  static
  resource_hoard&
  hoard(void)
  {
    static resource_hoard R;
    return R;
  }
}

void
fastuidraw::
generate_static_resource(const char *presource_label, const_c_array<uint8_t> pvalue)
{
  std::string sresource_label(presource_label);
  std::vector<uint8_t> svalue(pvalue.begin(), pvalue.end());
  hoard().m_mutex.lock();
  FASTUIDRAWassert(hoard().m_data.find(sresource_label) == hoard().m_data.end());
  hoard().m_data[sresource_label] = svalue;
  hoard().m_mutex.unlock();
}

fastuidraw::const_c_array<uint8_t>
fastuidraw::
fetch_static_resource(const char *presource_label)
{
  const_c_array<uint8_t> return_value;
  std::string sresource_label(presource_label);
  std::map<std::string, std::vector<uint8_t> >::const_iterator iter;

  hoard().m_mutex.lock();
  iter = hoard().m_data.find(sresource_label);
  if(iter != hoard().m_data.end())
    {
      return_value = make_c_array(iter->second);
    }
  hoard().m_mutex.unlock();
  return return_value;
}

///////////////////////////////////////
// fastuidraw::static_resource methods
fastuidraw::static_resource::
static_resource(const char *resource_label, const_c_array<uint8_t> value)
{
  generate_static_resource(resource_label, value);
}
<commit_msg>fastuidraw/util: add missing include <string><commit_after>/*!
 * \file static_resource.cpp
 * \brief file static_resource.cpp
 *
 * Copyright 2016 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#include <fastuidraw/util/util.hpp>
#include <map>
#include <vector>
#include <string>

#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/reference_counted.hpp>
#include <fastuidraw/util/static_resource.hpp>

#include "../private/util_private.hpp"

namespace
{
  class resource_hoard:fastuidraw::noncopyable
  {
  public:
    std::map<std::string, std::vector<uint8_t> > m_data;
    fastuidraw::mutex m_mutex;
  };

  static
  resource_hoard&
  hoard(void)
  {
    static resource_hoard R;
    return R;
  }
}

void
fastuidraw::
generate_static_resource(const char *presource_label, const_c_array<uint8_t> pvalue)
{
  std::string sresource_label(presource_label);
  std::vector<uint8_t> svalue(pvalue.begin(), pvalue.end());
  hoard().m_mutex.lock();
  FASTUIDRAWassert(hoard().m_data.find(sresource_label) == hoard().m_data.end());
  hoard().m_data[sresource_label] = svalue;
  hoard().m_mutex.unlock();
}

fastuidraw::const_c_array<uint8_t>
fastuidraw::
fetch_static_resource(const char *presource_label)
{
  const_c_array<uint8_t> return_value;
  std::string sresource_label(presource_label);
  std::map<std::string, std::vector<uint8_t> >::const_iterator iter;

  hoard().m_mutex.lock();
  iter = hoard().m_data.find(sresource_label);
  if(iter != hoard().m_data.end())
    {
      return_value = make_c_array(iter->second);
    }
  hoard().m_mutex.unlock();
  return return_value;
}

///////////////////////////////////////
// fastuidraw::static_resource methods
fastuidraw::static_resource::
static_resource(const char *resource_label, const_c_array<uint8_t> value)
{
  generate_static_resource(resource_label, value);
}
<|endoftext|>


<commit_before>#ifndef SOLAIRE_ISTREAM_HPP
#define SOLAIRE_ISTREAM_HPP

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

// Contact :
// Email             : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP

/*!
	\file IStream.hpp
	\brief
	\author
	Created			: Adam Smith
	Last modified	: Adam Smith
	\date
	Created			: 20th November 2015
	Last Modified	: 12th January 2016
*/

#include <cstdint>
#include "Solaire/Core/ModuleHeader.hpp"

namespace Solaire {

	SOLAIRE_EXPORT_INTERFACE IStream {
    private:
        virtual uint8_t SOLAIRE_EXPORT_CALL readU8() throw() = 0;
        virtual uint16_t SOLAIRE_EXPORT_CALL readU16() throw() = 0;
        virtual uint32_t SOLAIRE_EXPORT_CALL readU32() throw() = 0;
        virtual uint64_t SOLAIRE_EXPORT_CALL readU64() throw() = 0;
        virtual int8_t SOLAIRE_EXPORT_CALL readI8() throw() = 0;
        virtual int16_t SOLAIRE_EXPORT_CALL readI16() throw() = 0;
        virtual int32_t SOLAIRE_EXPORT_CALL readI32() throw() = 0;
        virtual int64_t SOLAIRE_EXPORT_CALL readI64() throw() = 0;
        virtual float SOLAIRE_EXPORT_CALL readF() throw() = 0;
        virtual double SOLAIRE_EXPORT_CALL readD() throw() = 0;
        virtual char SOLAIRE_EXPORT_CALL readC() throw() = 0;
    public:
        virtual SOLAIRE_EXPORT_CALL ~IStream(){}

        virtual void SOLAIRE_EXPORT_CALL read(void* const, const uint32_t) throw() = 0;
        virtual bool SOLAIRE_EXPORT_CALL isOffsetable() const throw() = 0;
        virtual int32_t SOLAIRE_EXPORT_CALL getOffset() const throw() = 0;
        virtual bool SOLAIRE_EXPORT_CALL setOffset(const int32_t) throw() = 0;
        virtual bool SOLAIRE_EXPORT_CALL end() const throw() = 0;

        SOLAIRE_FORCE_INLINE IStream& operator>>(uint8_t& aValue) throw() {
            aValue = readU8();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(uint16_t& aValue) throw() {
            aValue = readU16();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(uint32_t& aValue) throw() {
            aValue = readU32();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(uint64_t& aValue) throw() {
            aValue = readU64();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(int8_t& aValue) throw() {
            aValue = readI8();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(int16_t& aValue) throw() {
            aValue = readI16();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(int32_t& aValue) throw() {
            aValue = readI32();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(int64_t& aValue) throw() {
            aValue = readI64();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(float& aValue) throw() {
            aValue = readF();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(double& aValue) throw() {
            aValue = readD();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(char& aValue) throw() {
            aValue = readC();
            return *this;
        }
    };

}

#endif
<commit_msg>Added helper functions to IStream<commit_after>#ifndef SOLAIRE_ISTREAM_HPP
#define SOLAIRE_ISTREAM_HPP

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

// Contact :
// Email             : solairelibrary@mail.com
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP

/*!
	\file IStream.hpp
	\brief
	\author
	Created			: Adam Smith
	Last modified	: Adam Smith
	\date
	Created			: 20th November 2015
	Last Modified	: 12th January 2016
*/

#include <cstdint>
#include "Solaire/Core/ModuleHeader.hpp"

namespace Solaire {

	SOLAIRE_EXPORT_INTERFACE IStream {
    private:
        virtual uint8_t SOLAIRE_EXPORT_CALL readU8() throw() = 0;
        virtual uint16_t SOLAIRE_EXPORT_CALL readU16() throw() = 0;
        virtual uint32_t SOLAIRE_EXPORT_CALL readU32() throw() = 0;
        virtual uint64_t SOLAIRE_EXPORT_CALL readU64() throw() = 0;
        virtual int8_t SOLAIRE_EXPORT_CALL readI8() throw() = 0;
        virtual int16_t SOLAIRE_EXPORT_CALL readI16() throw() = 0;
        virtual int32_t SOLAIRE_EXPORT_CALL readI32() throw() = 0;
        virtual int64_t SOLAIRE_EXPORT_CALL readI64() throw() = 0;
        virtual float SOLAIRE_EXPORT_CALL readF() throw() = 0;
        virtual double SOLAIRE_EXPORT_CALL readD() throw() = 0;
        virtual char SOLAIRE_EXPORT_CALL readC() throw() = 0;
    public:
        virtual SOLAIRE_EXPORT_CALL ~IStream(){}

        virtual void SOLAIRE_EXPORT_CALL read(void* const, const uint32_t) throw() = 0;
        virtual bool SOLAIRE_EXPORT_CALL isOffsetable() const throw() = 0;
        virtual int32_t SOLAIRE_EXPORT_CALL getOffset() const throw() = 0;
        virtual bool SOLAIRE_EXPORT_CALL setOffset(const int32_t) throw() = 0;
        virtual bool SOLAIRE_EXPORT_CALL end() const throw() = 0;

        SOLAIRE_FORCE_INLINE IStream& operator>>(uint8_t& aValue) throw() {
            aValue = readU8();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(uint16_t& aValue) throw() {
            aValue = readU16();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(uint32_t& aValue) throw() {
            aValue = readU32();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(uint64_t& aValue) throw() {
            aValue = readU64();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(int8_t& aValue) throw() {
            aValue = readI8();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(int16_t& aValue) throw() {
            aValue = readI16();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(int32_t& aValue) throw() {
            aValue = readI32();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(int64_t& aValue) throw() {
            aValue = readI64();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(float& aValue) throw() {
            aValue = readF();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(double& aValue) throw() {
            aValue = readD();
            return *this;
        }

        SOLAIRE_FORCE_INLINE IStream& operator>>(char& aValue) throw() {
            aValue = readC();
            return *this;
        }

        template<class T>
        SOLAIRE_FORCE_INLINE T peak() throw() {
            const int32_t offset = this->getOffset();
            T tmp;
            *this >> tmp;
            this->setOffset(offset);
            return tmp;
        }

        template<class T>
        SOLAIRE_FORCE_INLINE bool ignore() throw() {
            T tmp;
            *this >> tmp;
            return true;
        }
    };

}

#endif
<|endoftext|>


<commit_before><commit_msg>Implement all remaining arithmetic operations.<commit_after><|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  A brief class that handles reading input from a configuration text file   //
//  based on root's TEnv format, i.e. key-value pairs, and shamelessly stolen //
//  from the HGamAnalysisTools package.                                       //
//                                                                            //
//  Author: Dag Gillberg                                                      //
//  Appropriator: Andrew Hard                                                 //
//  Email: ahard@cern.ch                                                      //
//  Date: 03/08/2015                                                          //
//                                                                            //
//  Config:                                                                   //
//    class to read settings from text files                                  //
//    relies on root's TEnv                                                   //
//                                                                            //
//  Usage:                                                                    //
//    Config settings("Hgamma.config");                                       //
//    TString gamContainerName = settings.getStr("PhotonContainer");          //
//    TString elContainerName  = settings.getStr("ElectronContainer");        //
//    vector<TString> systShifts = settings.getStrV("Systematics");           //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#include "Config.h"

/**
   Class constructor.
*/
Config::Config(TString fileName) {
  addFile(fileName);
}

/**
   Ensures that there is a value in the database assocated with key if not,
   abort with error message
*/
void Config::ensureDefined(TString key) {
  if (!isDefined(key)) {
    std::cout << "HG::Config no value found for " << key << std::endl;
    exit(0);
  }
}

/**
   returns true if the key is defined
*/
bool Config::isDefined(TString key) {
  return m_env.Defined(key);
}

/**
   Access a string value from the config database. Exception thrown if no entry exist.
*/
TString Config::getStr(TString key, bool expand) {
  ensureDefined(key);
  if (!expand) return m_env.GetValue(key,"");
  else return gSystem->ExpandPathName(m_env.GetValue(key,""));
}

/**
   Access a string value from the config database. Default value used if no entry exist.
*/
TString Config::getStr(TString key, TString dflt) {
  return m_env.GetValue(key, dflt);
}

/**
   Access an integer from the config database. Default value used if no entry exist.
*/
int Config::getInt(TString key) {
  ensureDefined(key);
  return m_env.GetValue(key,-99);
}

/**
   Access an integer from the config database. Exception thrown if no entry exist.
*/
int Config::getInt(TString key, int dflt) {
  return m_env.GetValue(key,dflt);
}

/**
   Access a boolean from the config database. Default value used if no entry exist
*/
bool Config::getBool(TString key, bool dflt) {
  return m_env.GetValue(key,dflt);
}

/**
   Access a boolean from the config database. Exception thrown if no entry exist.
*/
bool Config::getBool(TString key) {
  ensureDefined(key); return getBool(key,false);
}

/**
   Access a real number from the config database
*/
double Config::getNum(TString key) {
  ensureDefined(key);
  return m_env.GetValue(key,-99.0);
}

/**
   Access a vector of doubles from the config database
*/
double Config::getNum(TString key, double dflt) {
  return m_env.GetValue(key, dflt);
}

/**
   Access a vector of strings from the config database
*/
std::vector<TString> Config::getStrV(TString key) {
  ensureDefined(key);
  return vectorize(m_env.GetValue(key,"")," \t");
}

std::vector<double> Config::getNumV(TString key) {
  ensureDefined(key);
  return vectorizeNum(m_env.GetValue(key,"")," \t");
}

/**
   Prints the TEnv database to screen.
*/
void Config::printDB() {
  TIter next(m_env.GetTable());
  while (TEnvRec *er = (TEnvRec*) next()) {
    printf("  %-60s%s\n", Form("%s:", er->GetName()), er->GetValue());
  }
}

/**
   Add more user specified settings.
*/
void Config::addFile(TString fileName) {
  TString path(fileName);
  if (!fileExist(path) || path == "") {
    std::cout << "Cannot find settings file " << fileName
	      << "\n  also searched in " << path << std::endl;
    exit(0);
  }
  // settings read in by files should not overwrite values set by setValue()
  TEnv env;
  int status = env.ReadFile(path.Data(),EEnvLevel(0));
  if (status != 0) {
    std::cout << "Cannot read settings file " << fileName << std::endl;
    exit(0);
  }
  TIter next(env.GetTable());
  while (TEnvRec *er = (TEnvRec*) next()) {
    if (!isDefined(er->GetName())) {
      setValue(er->GetName(), er->GetValue());
    }
  }
}

/**
   Set value
*/
void Config::setValue(TString key, TString value) {
  m_env.SetValue(key,value);
}

std::vector<TString> Config::vectorize(TString str, TString sep) {
  std::vector<TString> result;
    TObjArray *strings = str.Tokenize(sep.Data());
    if (strings->GetEntries()==0) { delete strings; return result; }
    TIter istr(strings);
    while (TObjString* os=(TObjString*)istr()) {
      // the number sign and everything after is treated as a comment
      if (os->GetString()[0]=='#') break;
      result.push_back(os->GetString());
    }
    delete strings;
    return result;
  }

  // convert a text line containing a list of numbers to a vector<double>
std::vector<double> Config::vectorizeNum(TString str, TString sep) {
  std::vector<double> result; std::vector<TString> vecS = vectorize(str,sep);
    for (uint i=0;i<vecS.size();++i)
      result.push_back(atof(vecS[i]));
    return result;
  }

// checks if a given file or directory exist
bool Config::fileExist(TString fn) {
  return !(gSystem->AccessPathName(fn.Data()));
}
<commit_msg>Updating config class<commit_after>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  A brief class that handles reading input from a configuration text file   //
//  based on root's TEnv format, i.e. key-value pairs, and shamelessly stolen //
//  from the HGamAnalysisTools package.                                       //
//                                                                            //
//  Author: Dag Gillberg                                                      //
//  Appropriator: Andrew Hard                                                 //
//  Email: ahard@cern.ch                                                      //
//  Date: 03/08/2015                                                          //
//                                                                            //
//  Config:                                                                   //
//    class to read settings from text files                                  //
//    relies on root's TEnv                                                   //
//                                                                            //
//  Usage:                                                                    //
//    Config settings("Hgamma.config");                                       //
//    TString gamContainerName = settings.getStr("PhotonContainer");          //
//    TString elContainerName  = settings.getStr("ElectronContainer");        //
//    vector<TString> systShifts = settings.getStrV("Systematics");           //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#include "Config.h"

/**
   Class constructor.
*/
Config::Config(TString fileName) {
  addFile(fileName);
}

/**
   Ensures that there is a value in the database assocated with key if not,
   abort with error message
*/
void Config::ensureDefined(TString key) {
  if (!isDefined(key)) {
    std::cout << "Config: no value found for " << key << std::endl;
    exit(0);
  }
}

/**
   returns true if the key is defined
*/
bool Config::isDefined(TString key) {
  return m_env.Defined(key);
}

/**
   Access a string value from the config database. Exception thrown if no entry exist.
*/
TString Config::getStr(TString key, bool expand) {
  ensureDefined(key);
  if (!expand) return m_env.GetValue(key,"");
  else return gSystem->ExpandPathName(m_env.GetValue(key,""));
}

/**
   Access a string value from the config database. Default value used if no entry exist.
*/
TString Config::getStr(TString key, TString dflt) {
  return m_env.GetValue(key, dflt);
}

/**
   Access an integer from the config database. Default value used if no entry exist.
*/
int Config::getInt(TString key) {
  ensureDefined(key);
  return m_env.GetValue(key,-99);
}

/**
   Access an integer from the config database. Exception thrown if no entry exist.
*/
int Config::getInt(TString key, int dflt) {
  return m_env.GetValue(key,dflt);
}

/**
   Access a boolean from the config database. Default value used if no entry exist
*/
bool Config::getBool(TString key, bool dflt) {
  return m_env.GetValue(key,dflt);
}

/**
   Access a boolean from the config database. Exception thrown if no entry exist.
*/
bool Config::getBool(TString key) {
  ensureDefined(key); return getBool(key,false);
}

/**
   Access a real number from the config database
*/
double Config::getNum(TString key) {
  ensureDefined(key);
  return m_env.GetValue(key,-99.0);
}

/**
   Access a vector of doubles from the config database
*/
double Config::getNum(TString key, double dflt) {
  return m_env.GetValue(key, dflt);
}

/**
   Access a vector of strings from the config database
*/
std::vector<TString> Config::getStrV(TString key) {
  ensureDefined(key);
  return vectorize(m_env.GetValue(key,"")," \t");
}

std::vector<double> Config::getNumV(TString key) {
  ensureDefined(key);
  return vectorizeNum(m_env.GetValue(key,"")," \t");
}

/**
   Prints the TEnv database to screen.
*/
void Config::printDB() {
  TIter next(m_env.GetTable());
  while (TEnvRec *er = (TEnvRec*) next()) {
    printf("  %-60s%s\n", Form("%s:", er->GetName()), er->GetValue());
  }
}

/**
   Add more user specified settings.
*/
void Config::addFile(TString fileName) {
  TString path(fileName);
  if (!fileExist(path) || path == "") {
    std::cout << "Cannot find settings file " << fileName
	      << "\n  also searched in " << path << std::endl;
    exit(0);
  }
  // settings read in by files should not overwrite values set by setValue()
  TEnv env;
  int status = env.ReadFile(path.Data(),EEnvLevel(0));
  if (status != 0) {
    std::cout << "Cannot read settings file " << fileName << std::endl;
    exit(0);
  }
  TIter next(env.GetTable());
  while (TEnvRec *er = (TEnvRec*) next()) {
    if (!isDefined(er->GetName())) {
      setValue(er->GetName(), er->GetValue());
    }
  }
}

/**
   Set value
*/
void Config::setValue(TString key, TString value) {
  m_env.SetValue(key,value);
}

std::vector<TString> Config::vectorize(TString str, TString sep) {
  std::vector<TString> result;
    TObjArray *strings = str.Tokenize(sep.Data());
    if (strings->GetEntries()==0) { delete strings; return result; }
    TIter istr(strings);
    while (TObjString* os=(TObjString*)istr()) {
      // the number sign and everything after is treated as a comment
      if (os->GetString()[0]=='#') break;
      result.push_back(os->GetString());
    }
    delete strings;
    return result;
  }

  // convert a text line containing a list of numbers to a vector<double>
std::vector<double> Config::vectorizeNum(TString str, TString sep) {
  std::vector<double> result; std::vector<TString> vecS = vectorize(str,sep);
    for (uint i=0;i<vecS.size();++i)
      result.push_back(atof(vecS[i]));
    return result;
  }

// checks if a given file or directory exist
bool Config::fileExist(TString fn) {
  return !(gSystem->AccessPathName(fn.Data()));
}
<|endoftext|>


<commit_before>/*****************************************************************\
           __
          / /
		 / /                     __  __
		/ /______    _______    / / / / ________   __       __
	   / ______  \  /_____  \  / / / / / _____  | / /      / /
	  / /      | / _______| / / / / / / /____/ / / /      / /
	 / /      / / / _____  / / / / / / _______/ / /      / /
	/ /      / / / /____/ / / / / / / |______  / |______/ /
   /_/      /_/ |________/ / / / /  \_______/  \_______  /
                          /_/ /_/                     / /
			                                         / /
		       High Level Game Framework            /_/

  ---------------------------------------------------------------

  Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.
  This file is subject to the terms of halley_license.txt.

\*****************************************************************/

#include "halley/text/string_converter.h"
#ifdef _WIN32
#include "halley/support/exception.h"

#pragma warning(disable: 6387)
#include "os_win32.h"

#include <iostream>
#include <winuser.h>
#include <Lmcons.h>
#include <Shlobj.h>
#include <fcntl.h>
#include <io.h>
#include <comutil.h>
#include <objbase.h>
#include <atlbase.h>

#pragma comment(lib, "wbemuuid.lib")
//#pragma comment(lib, "comsupp.lib")
#pragma comment(lib, "comsuppw.lib")

using namespace Halley;

Halley::OSWin32::OSWin32()
	: pLoc(nullptr)
	, pSvc(nullptr)
{
	// From http://msdn.microsoft.com/en-us/library/aa389762(v=VS.85).aspx
	// "Creating a WMI Application Using C++"

	try {
		// Initialize COM
		HRESULT hr;
		hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
		if (FAILED(hr)) throw Exception("Unable to initialize COM.");
		hr = CoInitializeSecurity(nullptr, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE, nullptr);
		if (FAILED(hr)) throw Exception("Unable to initialize COM security.");

		// Initialize WMI
		hr = CoCreateInstance(CLSID_WbemAdministrativeLocator, nullptr, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast<void**>(&pLoc));
		if (FAILED(hr)) throw Exception("Unable to obtain locator");
		//hr = pLoc->ConnectServer(BSTR(L"ROOT\\DEFAULT"), nullptr, nullptr, 0, 0, 0, 0, &pSvc);
		hr = pLoc->ConnectServer( L"root\\cimv2", nullptr, nullptr, nullptr, WBEM_FLAG_CONNECT_USE_MAX_WAIT, nullptr, nullptr, &pSvc);
		if (FAILED(hr)) throw Exception("Unable to connect to WMI service");

		// Set security on WMI connection
		hr = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE);
		if (FAILED(hr)) throw Exception("Unable to set WMI security");
	} catch (std::exception& e) {
		std::cout << "Exception initializing COM/WMI: " << e.what() << std::endl;
		pSvc = nullptr;
		pLoc = nullptr;
	} catch (...) {
		std::cout << "Unknown exception initializing COM/WMI.";
		pSvc = nullptr;
		pLoc = nullptr;
	}

	// Load icon
	HINSTANCE handle = ::GetModuleHandle(nullptr);
	icon = ::LoadIcon(handle, "IDI_MAIN_ICON");
}

Halley::OSWin32::~OSWin32()
{
	if (pSvc) {
		pSvc->Release();
		pLoc->Release();
		CoUninitialize();
	}
}

static String getCOMError(int hr)
{
	IErrorInfo* info;
	HRESULT hr2 = GetErrorInfo(0, &info);
	if (FAILED(hr2)) return "Failed getting COM error.";
	BSTR str;
	info->GetDescription(&str);
	_bstr_t tmp(str);
	return "\"" + String(LPCSTR(tmp)) + "\", code 0x"+ toString(hr, 16);
}

Halley::String Halley::OSWin32::runWMIQuery(String query, String parameter) const
{
	// See:
	// http://www.codeproject.com/KB/system/UsingWMI.aspx
	// http://www.codeproject.com/KB/system/Using_WMI_in_Visual_C__.aspx

	if (pSvc) {
		try {
			HRESULT hr;
			CComPtr<IEnumWbemClassObject> enumerator;
			BSTR lang = CComBSTR(L"WQL");
			BSTR q = CComBSTR(query.c_str());
			hr = pSvc->ExecQuery(lang, q, WBEM_FLAG_FORWARD_ONLY, nullptr, &enumerator);
			if (FAILED(hr)) throw Exception("Error running WMI query: "+getCOMError(hr));

			ULONG retcnt;
			CComPtr<IWbemClassObject> result;
			hr = enumerator->Next(WBEM_INFINITE, 1L, &result, &retcnt);
			if (retcnt == 0) return "Unknown";
			if (FAILED(hr)) throw Exception("Error obtaining WMI enumeration");

			_variant_t var_val;
			hr = result->Get(parameter.getUTF16().c_str(), 0, &var_val, nullptr, nullptr);
			if (FAILED(hr)) throw Exception("Error retrieving name from WMI query result");

			if (var_val.vt == VT_NULL) {
				return "";
			} else {
				return String(static_cast<const char*>(_bstr_t(var_val)));
			}
		} catch (std::exception& e) {
			std::cout << "Exception running WMI query: " << e.what() << std::endl;
		} catch (...) {
			std::cout << "Unknown exception running WMI query." << std::endl;
		}
	}
	return "Unknown";
}

struct MonitorInfo {
public:
	int n;
	int x, y, w, h;
};

BOOL CALLBACK onMonitorInfo(HMONITOR /*hMonitor*/, HDC /*hdcMonitor*/, LPRECT lprcMonitor, LPARAM dwData)
{
	MonitorInfo* info = reinterpret_cast<MonitorInfo*>(dwData);
	info->n++;
	info->x = lprcMonitor->left;
	info->y = lprcMonitor->top;
	info->w = lprcMonitor->right - lprcMonitor->left;
	info->h = lprcMonitor->bottom - lprcMonitor->top;
	return (info->n != 2);
}

void OSWin32::loadWindowIcon(HWND hwnd)
{
	if (icon != nullptr) {
		::SetClassLongPtr(hwnd, GCLP_HICON, reinterpret_cast<LONG_PTR>(icon));
		::SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(icon));
	}
}

void OSWin32::onWindowCreated(void* window)
{
	loadWindowIcon(reinterpret_cast<HWND>(window));
}

void Halley::OSWin32::createLogConsole(String winTitle)
{
	AllocConsole();
	SetConsoleTitle(winTitle.c_str());

	// Icon
	HWND con = GetConsoleWindow();
	loadWindowIcon(con);

	// Position console
	MonitorInfo info;
	info.n = 0;
	EnumDisplayMonitors(nullptr, nullptr, onMonitorInfo, LPARAM(&info));
	if (info.n > 1) {
		RECT rect;
		GetWindowRect(con, &rect);
		int w = rect.right - rect.left;
		int h = info.h;
		//MoveWindow(con, (info.w - w)/2 + info.x, (info.h - h)/2 + info.h, w, h, true);
		SetWindowPos(con, HWND_TOP, (info.w - w)/2 + info.x, (info.h - h)/2 + info.y, w, h, 0);
	}
}

void OSWin32::initializeConsole()
{
	// From http://stackoverflow.com/a/25927081/546712
	// Redirect the CRT standard input, output, and error handles to the console
#pragma warning(push)
#pragma warning(disable: 4996)
	freopen("CONIN$", "r", stdin);
	freopen("CONOUT$", "w", stdout);
	freopen("CONOUT$", "w", stderr);
#pragma warning(pop)

	//Clear the error state for each of the C++ standard stream objects. We need to do this, as
	//attempts to access the standard streams before they refer to a valid target will cause the
	//iostream objects to enter an error state. In versions of Visual Studio after 2005, this seems
	//to always occur during startup regardless of whether anything has been read from or written to
	//the console or not.
	std::wcout.clear();
	std::cout.clear();
	std::wcerr.clear();
	std::cerr.clear();
	std::wcin.clear();
	std::cin.clear();
}

Halley::ComputerData Halley::OSWin32::getComputerData()
{
	ComputerData data;

	TCHAR chrComputerName[MAX_COMPUTERNAME_LENGTH + 1];
	DWORD dwBufferSize = MAX_COMPUTERNAME_LENGTH + 1;
	if (GetComputerName(chrComputerName, &dwBufferSize)) data.computerName = String(chrComputerName);

	TCHAR name[UNLEN + 1];
	DWORD dwBufferSize2 = UNLEN + 1;
	if (GetUserName(name, &dwBufferSize2)) data.userName = String(name);

	String os = runWMIQuery("SELECT * FROM Win32_OperatingSystem", "Caption");
	String servPack = runWMIQuery("SELECT * FROM Win32_OperatingSystem", "CSDVersion");
	String osArch = "Unknown";
	if (!os.contains("Windows XP") && !os.contains("2003") && !os.contains("2000")) osArch = runWMIQuery("SELECT * FROM Win32_OperatingSystem", "OSArchitecture");
	data.osName = os.trimBoth();
	if (osArch != "Unknown") data.osName += " " + osArch.trimBoth();
	if (servPack != "Unknown") data.osName += " " + servPack.trimBoth();
	data.cpuName = runWMIQuery("SELECT * FROM Win32_Processor", "Name");
	data.gpuName = runWMIQuery("SELECT * FROM Win32_DisplayConfiguration", "DeviceName");
	data.RAM = runWMIQuery("SELECT * FROM Win32_OperatingSystem", "TotalVisibleMemorySize").toInteger64() * 1024;

	return data;
}

Halley::String Halley::OSWin32::getUserDataDir()
{
	TCHAR path[MAX_PATH];
	SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, path);
	return String(path) + "\\";
}

Path OSWin32::parseProgramPath(const String&)
{
	HMODULE hModule = GetModuleHandleW(nullptr);
	WCHAR path[MAX_PATH];
	GetModuleFileNameW(hModule, path, MAX_PATH);
	String programPath(path);
	return Path(programPath).parentPath() / ".";
}

void Halley::OSWin32::setConsoleColor(int foreground, int background)
{
	if (foreground == -1) {
		foreground = 7;
	}
	if (background == -1) {
		background = 0;
	}

	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleTextAttribute(hConsole, WORD(foreground | (background << 4)));
}

static bool hasDirectory(const Path& directory) {
    DWORD res = GetFileAttributesW(directory.getString().getUTF16().c_str());
    return res != INVALID_FILE_ATTRIBUTES && (res & FILE_ATTRIBUTE_DIRECTORY) != 0;
}

void OSWin32::createDirectories(const Path& path)
{
	size_t n = path.getNumberPaths();
	for (size_t i = 1; i < n; ++i) {
		Path curPath = path.getFront(i);
		if (!hasDirectory(curPath)) {
			if (!CreateDirectoryW(curPath.getString().getUTF16().c_str(), 0)) {
				throw Exception("Unable to create directory: " + curPath + " (trying to make " + path + ")");
			}
		}
	}
}

int OSWin32::runCommand(String command)
{
	char buffer[1024];
	strcpy_s(buffer, 1024, command.c_str());
	buffer[command.size()] = 0;

	STARTUPINFO si;
    PROCESS_INFORMATION pi;
	DWORD exitCode = -2;

	memset(&si, 0, sizeof(STARTUPINFO));
	memset(&pi, 0, sizeof(PROCESS_INFORMATION));

	if (!CreateProcessA(nullptr, buffer, nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi)) {
		return -1;
	}
	WaitForSingleObject(pi.hProcess, INFINITE);
	GetExitCodeProcess(pi.hProcess, &exitCode);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	return int(exitCode);
}

#endif
<commit_msg>Don't create console window when spawning console programs.<commit_after>/*****************************************************************\
           __
          / /
		 / /                     __  __
		/ /______    _______    / / / / ________   __       __
	   / ______  \  /_____  \  / / / / / _____  | / /      / /
	  / /      | / _______| / / / / / / /____/ / / /      / /
	 / /      / / / _____  / / / / / / _______/ / /      / /
	/ /      / / / /____/ / / / / / / |______  / |______/ /
   /_/      /_/ |________/ / / / /  \_______/  \_______  /
                          /_/ /_/                     / /
			                                         / /
		       High Level Game Framework            /_/

  ---------------------------------------------------------------

  Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.
  This file is subject to the terms of halley_license.txt.

\*****************************************************************/

#include "halley/text/string_converter.h"
#ifdef _WIN32
#include "halley/support/exception.h"

#pragma warning(disable: 6387)
#include "os_win32.h"

#include <iostream>
#include <winuser.h>
#include <Lmcons.h>
#include <Shlobj.h>
#include <fcntl.h>
#include <io.h>
#include <comutil.h>
#include <objbase.h>
#include <atlbase.h>

#pragma comment(lib, "wbemuuid.lib")
//#pragma comment(lib, "comsupp.lib")
#pragma comment(lib, "comsuppw.lib")

using namespace Halley;

Halley::OSWin32::OSWin32()
	: pLoc(nullptr)
	, pSvc(nullptr)
{
	// From http://msdn.microsoft.com/en-us/library/aa389762(v=VS.85).aspx
	// "Creating a WMI Application Using C++"

	try {
		// Initialize COM
		HRESULT hr;
		hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
		if (FAILED(hr)) throw Exception("Unable to initialize COM.");
		hr = CoInitializeSecurity(nullptr, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE, nullptr);
		if (FAILED(hr)) throw Exception("Unable to initialize COM security.");

		// Initialize WMI
		hr = CoCreateInstance(CLSID_WbemAdministrativeLocator, nullptr, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast<void**>(&pLoc));
		if (FAILED(hr)) throw Exception("Unable to obtain locator");
		//hr = pLoc->ConnectServer(BSTR(L"ROOT\\DEFAULT"), nullptr, nullptr, 0, 0, 0, 0, &pSvc);
		hr = pLoc->ConnectServer( L"root\\cimv2", nullptr, nullptr, nullptr, WBEM_FLAG_CONNECT_USE_MAX_WAIT, nullptr, nullptr, &pSvc);
		if (FAILED(hr)) throw Exception("Unable to connect to WMI service");

		// Set security on WMI connection
		hr = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE);
		if (FAILED(hr)) throw Exception("Unable to set WMI security");
	} catch (std::exception& e) {
		std::cout << "Exception initializing COM/WMI: " << e.what() << std::endl;
		pSvc = nullptr;
		pLoc = nullptr;
	} catch (...) {
		std::cout << "Unknown exception initializing COM/WMI.";
		pSvc = nullptr;
		pLoc = nullptr;
	}

	// Load icon
	HINSTANCE handle = ::GetModuleHandle(nullptr);
	icon = ::LoadIcon(handle, "IDI_MAIN_ICON");
}

Halley::OSWin32::~OSWin32()
{
	if (pSvc) {
		pSvc->Release();
		pLoc->Release();
		CoUninitialize();
	}
}

static String getCOMError(int hr)
{
	IErrorInfo* info;
	HRESULT hr2 = GetErrorInfo(0, &info);
	if (FAILED(hr2)) return "Failed getting COM error.";
	BSTR str;
	info->GetDescription(&str);
	_bstr_t tmp(str);
	return "\"" + String(LPCSTR(tmp)) + "\", code 0x"+ toString(hr, 16);
}

Halley::String Halley::OSWin32::runWMIQuery(String query, String parameter) const
{
	// See:
	// http://www.codeproject.com/KB/system/UsingWMI.aspx
	// http://www.codeproject.com/KB/system/Using_WMI_in_Visual_C__.aspx

	if (pSvc) {
		try {
			HRESULT hr;
			CComPtr<IEnumWbemClassObject> enumerator;
			BSTR lang = CComBSTR(L"WQL");
			BSTR q = CComBSTR(query.c_str());
			hr = pSvc->ExecQuery(lang, q, WBEM_FLAG_FORWARD_ONLY, nullptr, &enumerator);
			if (FAILED(hr)) throw Exception("Error running WMI query: "+getCOMError(hr));

			ULONG retcnt;
			CComPtr<IWbemClassObject> result;
			hr = enumerator->Next(WBEM_INFINITE, 1L, &result, &retcnt);
			if (retcnt == 0) return "Unknown";
			if (FAILED(hr)) throw Exception("Error obtaining WMI enumeration");

			_variant_t var_val;
			hr = result->Get(parameter.getUTF16().c_str(), 0, &var_val, nullptr, nullptr);
			if (FAILED(hr)) throw Exception("Error retrieving name from WMI query result");

			if (var_val.vt == VT_NULL) {
				return "";
			} else {
				return String(static_cast<const char*>(_bstr_t(var_val)));
			}
		} catch (std::exception& e) {
			std::cout << "Exception running WMI query: " << e.what() << std::endl;
		} catch (...) {
			std::cout << "Unknown exception running WMI query." << std::endl;
		}
	}
	return "Unknown";
}

struct MonitorInfo {
public:
	int n;
	int x, y, w, h;
};

BOOL CALLBACK onMonitorInfo(HMONITOR /*hMonitor*/, HDC /*hdcMonitor*/, LPRECT lprcMonitor, LPARAM dwData)
{
	MonitorInfo* info = reinterpret_cast<MonitorInfo*>(dwData);
	info->n++;
	info->x = lprcMonitor->left;
	info->y = lprcMonitor->top;
	info->w = lprcMonitor->right - lprcMonitor->left;
	info->h = lprcMonitor->bottom - lprcMonitor->top;
	return (info->n != 2);
}

void OSWin32::loadWindowIcon(HWND hwnd)
{
	if (icon != nullptr) {
		::SetClassLongPtr(hwnd, GCLP_HICON, reinterpret_cast<LONG_PTR>(icon));
		::SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(icon));
	}
}

void OSWin32::onWindowCreated(void* window)
{
	loadWindowIcon(reinterpret_cast<HWND>(window));
}

void Halley::OSWin32::createLogConsole(String winTitle)
{
	AllocConsole();
	SetConsoleTitle(winTitle.c_str());

	// Icon
	HWND con = GetConsoleWindow();
	loadWindowIcon(con);

	// Position console
	MonitorInfo info;
	info.n = 0;
	EnumDisplayMonitors(nullptr, nullptr, onMonitorInfo, LPARAM(&info));
	if (info.n > 1) {
		RECT rect;
		GetWindowRect(con, &rect);
		int w = rect.right - rect.left;
		int h = info.h;
		//MoveWindow(con, (info.w - w)/2 + info.x, (info.h - h)/2 + info.h, w, h, true);
		SetWindowPos(con, HWND_TOP, (info.w - w)/2 + info.x, (info.h - h)/2 + info.y, w, h, 0);
	}
}

void OSWin32::initializeConsole()
{
	// From http://stackoverflow.com/a/25927081/546712
	// Redirect the CRT standard input, output, and error handles to the console
#pragma warning(push)
#pragma warning(disable: 4996)
	freopen("CONIN$", "r", stdin);
	freopen("CONOUT$", "w", stdout);
	freopen("CONOUT$", "w", stderr);
#pragma warning(pop)

	//Clear the error state for each of the C++ standard stream objects. We need to do this, as
	//attempts to access the standard streams before they refer to a valid target will cause the
	//iostream objects to enter an error state. In versions of Visual Studio after 2005, this seems
	//to always occur during startup regardless of whether anything has been read from or written to
	//the console or not.
	std::wcout.clear();
	std::cout.clear();
	std::wcerr.clear();
	std::cerr.clear();
	std::wcin.clear();
	std::cin.clear();
}

Halley::ComputerData Halley::OSWin32::getComputerData()
{
	ComputerData data;

	TCHAR chrComputerName[MAX_COMPUTERNAME_LENGTH + 1];
	DWORD dwBufferSize = MAX_COMPUTERNAME_LENGTH + 1;
	if (GetComputerName(chrComputerName, &dwBufferSize)) data.computerName = String(chrComputerName);

	TCHAR name[UNLEN + 1];
	DWORD dwBufferSize2 = UNLEN + 1;
	if (GetUserName(name, &dwBufferSize2)) data.userName = String(name);

	String os = runWMIQuery("SELECT * FROM Win32_OperatingSystem", "Caption");
	String servPack = runWMIQuery("SELECT * FROM Win32_OperatingSystem", "CSDVersion");
	String osArch = "Unknown";
	if (!os.contains("Windows XP") && !os.contains("2003") && !os.contains("2000")) osArch = runWMIQuery("SELECT * FROM Win32_OperatingSystem", "OSArchitecture");
	data.osName = os.trimBoth();
	if (osArch != "Unknown") data.osName += " " + osArch.trimBoth();
	if (servPack != "Unknown") data.osName += " " + servPack.trimBoth();
	data.cpuName = runWMIQuery("SELECT * FROM Win32_Processor", "Name");
	data.gpuName = runWMIQuery("SELECT * FROM Win32_DisplayConfiguration", "DeviceName");
	data.RAM = runWMIQuery("SELECT * FROM Win32_OperatingSystem", "TotalVisibleMemorySize").toInteger64() * 1024;

	return data;
}

Halley::String Halley::OSWin32::getUserDataDir()
{
	TCHAR path[MAX_PATH];
	SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, path);
	return String(path) + "\\";
}

Path OSWin32::parseProgramPath(const String&)
{
	HMODULE hModule = GetModuleHandleW(nullptr);
	WCHAR path[MAX_PATH];
	GetModuleFileNameW(hModule, path, MAX_PATH);
	String programPath(path);
	return Path(programPath).parentPath() / ".";
}

void Halley::OSWin32::setConsoleColor(int foreground, int background)
{
	if (foreground == -1) {
		foreground = 7;
	}
	if (background == -1) {
		background = 0;
	}

	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleTextAttribute(hConsole, WORD(foreground | (background << 4)));
}

static bool hasDirectory(const Path& directory) {
    DWORD res = GetFileAttributesW(directory.getString().getUTF16().c_str());
    return res != INVALID_FILE_ATTRIBUTES && (res & FILE_ATTRIBUTE_DIRECTORY) != 0;
}

void OSWin32::createDirectories(const Path& path)
{
	size_t n = path.getNumberPaths();
	for (size_t i = 1; i < n; ++i) {
		Path curPath = path.getFront(i);
		if (!hasDirectory(curPath)) {
			if (!CreateDirectoryW(curPath.getString().getUTF16().c_str(), 0)) {
				throw Exception("Unable to create directory: " + curPath + " (trying to make " + path + ")");
			}
		}
	}
}

int OSWin32::runCommand(String command)
{
	char buffer[1024];
	strcpy_s(buffer, 1024, command.c_str());
	buffer[command.size()] = 0;

	STARTUPINFO si;
    PROCESS_INFORMATION pi;
	DWORD exitCode = -2;

	memset(&si, 0, sizeof(STARTUPINFO));
	memset(&pi, 0, sizeof(PROCESS_INFORMATION));

	if (!CreateProcessA(nullptr, buffer, nullptr, nullptr, false, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) {
		return -1;
	}
	WaitForSingleObject(pi.hProcess, INFINITE);
	GetExitCodeProcess(pi.hProcess, &exitCode);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	return int(exitCode);
}

#endif
<|endoftext|>


<commit_before>#include <iostream>

#include "sash/sash.hpp"
#include "sash/libedit_backend.hpp" // our backend
#include "sash/variables_engine.hpp"

using namespace std;

int main()
{
  using char_iter = string::const_iterator;
  using sash::command_result;
  sash::sash<sash::libedit_backend>::type cli;
  string line;
  auto mptr = cli.mode_add("default", "SASH> ", sash::color::blue);
  cli.mode_push("default");
  cli.add_preprocessor(sash::variables_engine<>::create());
  bool done = false;
  mptr->add_all({
    {
      "quit", "terminates the whole thing",
      [&](string& err, char_iter first, char_iter last) -> command_result
      {
        if (first == last)
        {
          done = true;
          return sash::executed;
        }
        err = "quit: to many arguments (none expected)";
        return sash::no_command;
      }
    },
    {
      "echo", "prints its arguments",
      [](string&, char_iter first, char_iter last) -> command_result
      {
        copy(first, last, ostream_iterator<char>(cout));
        cout << endl;
        return sash::executed;
      }
    },
    {
      "help", "prints this text",
      [&](string& err, char_iter first, char_iter last) -> command_result
      {
        if (first == last)
        {
          // doin' it complicated!
          std::string cmd = "echo ";
          cmd += cli.current_mode().help();
          return cli.process(cmd);
        }
        err = "help: to many arguments (none expected)";
        return sash::no_command;
      }
    }});
  while (!done)
  {
    cli.read_line(line);
    switch (cli.process(line))
    {
      default:
        break;
      case sash::nop:
        break;
      case sash::executed:
        cli.append_to_history(line);
        break;
      case sash::no_command:
        cout << cli.last_error() << endl;
        break;
    }
  }
}
<commit_msg>Print errors in red in the simple shell example<commit_after>#include <iostream>

#include "sash/sash.hpp"
#include "sash/libedit_backend.hpp" // our backend
#include "sash/variables_engine.hpp"

using namespace std;

int main()
{
  using char_iter = string::const_iterator;
  using sash::command_result;
  sash::sash<sash::libedit_backend>::type cli;
  string line;
  auto mptr = cli.mode_add("default", "SASH> ", sash::color::blue);
  cli.mode_push("default");
  cli.add_preprocessor(sash::variables_engine<>::create());
  bool done = false;
  mptr->add_all({
    {
      "quit", "terminates the whole thing",
      [&](string& err, char_iter first, char_iter last) -> command_result
      {
        if (first == last)
        {
          done = true;
          return sash::executed;
        }
        err = "quit: to many arguments (none expected)";
        return sash::no_command;
      }
    },
    {
      "echo", "prints its arguments",
      [](string&, char_iter first, char_iter last) -> command_result
      {
        copy(first, last, ostream_iterator<char>(cout));
        cout << endl;
        return sash::executed;
      }
    },
    {
      "help", "prints this text",
      [&](string& err, char_iter first, char_iter last) -> command_result
      {
        if (first == last)
        {
          // doin' it complicated!
          std::string cmd = "echo ";
          cmd += cli.current_mode().help();
          return cli.process(cmd);
        }
        err = "help: to many arguments (none expected)";
        return sash::no_command;
      }
    }});
  while (!done)
  {
    cli.read_line(line);
    switch (cli.process(line))
    {
      default:
        break;
      case sash::nop:
        break;
      case sash::executed:
        cli.append_to_history(line);
        break;
      case sash::no_command:
        cout << sash::color::red
             << cli.last_error()
             << sash::color::reset
             << endl;
        break;
    }
  }
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	１２×１２漢字フォント・クラス
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "ff12a/src/ff.h"

// #include "common/format.hpp"

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	漢字フォント・クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint8_t CASH_SIZE>
	class kfont12 {

		struct kanji_cash {
			uint16_t	code;
			uint8_t		bitmap[18];
		};
		kanji_cash cash_[CASH_SIZE];
		uint8_t cash_idx_;

		bool	mount_;

		static uint16_t sjis_to_liner_(uint16_t sjis)
		{
			uint16_t code;
			uint8_t up = sjis >> 8;
			uint8_t lo = sjis & 0xff;
			if(0x81 <= up && up <= 0x9f) {
				code = up - 0x81;
			} else if(0xe0 <= up && up <= 0xef) {
				code = (0x9f + 1 - 0x81) + up - 0xe0;
			} else {
				return 0xffff;
			}
			uint16_t loa = (0x7e + 1 - 0x40) + (0xfc + 1 - 0x80);
			if(0x40 <= lo && lo <= 0x7e) {
				code *= loa;
				code += lo - 0x40;
			} else if(0x80 <= lo && lo <= 0xfc) {
				code *= loa;
				code += 0x7e + 1 - 0x40;
				code += lo - 0x80;
			} else {
				return 0xffff;
			}
			return code;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		kfont12() : cash_idx_(0), mount_(false) {
			for(uint8_t i = 0; i < CASH_SIZE; ++i) {
				cash_[i].code = 0;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	文字の横幅
		*/
		//-----------------------------------------------------------------//
		static const int8_t width = 12;

		//-----------------------------------------------------------------//
		/*!
			@brief	文字の高さ
		*/
		//-----------------------------------------------------------------//
		static const int8_t height = 12;

		//-----------------------------------------------------------------//
		/*!
			@brief	マウント状態の設定
		*/
		//-----------------------------------------------------------------//
		void set_mount(bool f) { mount_ = f; }

		//-----------------------------------------------------------------//
		/*!
			@brief	文字のビットマップを取得
			@param[in]	code	文字コード（unicode）
			@return 文字のビットマップ
		*/
		//-----------------------------------------------------------------//
		const uint8_t* get(uint16_t code) {

			if(code == 0) return nullptr;

			// キャッシュ内検索
			int8_t n = -1;
			for(uint8_t i = 0; i < CASH_SIZE; ++i) {
				if(cash_[i].code == code) {
					return &cash_[i].bitmap[0];
				} else if(cash_[i].code == 0) {
					n = i;
				}
			}
			if(n >= 0) cash_idx_ = n;
			else {
				for(uint8_t i = 0; i < CASH_SIZE; ++i) {
					++cash_idx_;
					if(cash_idx_ >= CASH_SIZE) cash_idx_ = 0;
					if(cash_[cash_idx_].code != 0) {
						break;
					}
				}
			}

			if(!mount_) return nullptr;

			uint32_t lin = sjis_to_liner_(ff_convert(code, 0));

			if(lin == 0xffff) {
				return nullptr;
			}

			FIL fp;
			if(f_open(&fp, "/kfont12.bin", FA_READ) != FR_OK) {
//				utils::format("Open error\n");
				return nullptr;
			}

			if(f_lseek(&fp, lin * 18) != FR_OK) {
				f_close(&fp);
//				utils::format("Seek error\n");
				return nullptr;
			}

			UINT rs;
			if(f_read(&fp, &cash_[cash_idx_].bitmap[0], 18, &rs) != FR_OK) {
				f_close(&fp);
//				utils::format("Read error\n");
				return nullptr;
			}
			cash_[cash_idx_].code = code;

			f_close(&fp);

			return &cash_[cash_idx_].bitmap[0];
		}
	};
}
<commit_msg>update comment<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	１２×１２漢字フォント・クラス
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "ff12a/src/ff.h"

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	漢字フォント・クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint8_t CASH_SIZE>
	class kfont12 {

		struct kanji_cash {
			uint16_t	code;
			uint8_t		bitmap[18];
		};
		kanji_cash cash_[CASH_SIZE];
		uint8_t cash_idx_;

		bool	mount_;

		static uint16_t sjis_to_liner_(uint16_t sjis)
		{
			uint16_t code;
			uint8_t up = sjis >> 8;
			uint8_t lo = sjis & 0xff;
			if(0x81 <= up && up <= 0x9f) {
				code = up - 0x81;
			} else if(0xe0 <= up && up <= 0xef) {
				code = (0x9f + 1 - 0x81) + up - 0xe0;
			} else {
				return 0xffff;
			}
			uint16_t loa = (0x7e + 1 - 0x40) + (0xfc + 1 - 0x80);
			if(0x40 <= lo && lo <= 0x7e) {
				code *= loa;
				code += lo - 0x40;
			} else if(0x80 <= lo && lo <= 0xfc) {
				code *= loa;
				code += 0x7e + 1 - 0x40;
				code += lo - 0x80;
			} else {
				return 0xffff;
			}
			return code;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		kfont12() : cash_idx_(0), mount_(false) {
			for(uint8_t i = 0; i < CASH_SIZE; ++i) {
				cash_[i].code = 0;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	文字の横幅
		*/
		//-----------------------------------------------------------------//
		static const int8_t width = 12;

		//-----------------------------------------------------------------//
		/*!
			@brief	文字の高さ
		*/
		//-----------------------------------------------------------------//
		static const int8_t height = 12;

		//-----------------------------------------------------------------//
		/*!
			@brief	マウント状態の設定
		*/
		//-----------------------------------------------------------------//
		void set_mount(bool f) { mount_ = f; }

		//-----------------------------------------------------------------//
		/*!
			@brief	文字のビットマップを取得
			@param[in]	code	文字コード（unicode）
			@return 文字のビットマップ
		*/
		//-----------------------------------------------------------------//
		const uint8_t* get(uint16_t code) {

			if(code == 0) return nullptr;

			// キャッシュ内検索
			int8_t n = -1;
			for(uint8_t i = 0; i < CASH_SIZE; ++i) {
				if(cash_[i].code == code) {
					return &cash_[i].bitmap[0];
				} else if(cash_[i].code == 0) {
					n = i;
				}
			}
			if(n >= 0) cash_idx_ = n;
			else {
				for(uint8_t i = 0; i < CASH_SIZE; ++i) {
					++cash_idx_;
					if(cash_idx_ >= CASH_SIZE) cash_idx_ = 0;
					if(cash_[cash_idx_].code != 0) {
						break;
					}
				}
			}

			if(!mount_) return nullptr;

			uint32_t lin = sjis_to_liner_(ff_convert(code, 0));

			if(lin == 0xffff) {
				return nullptr;
			}

			FIL fp;
			if(f_open(&fp, "/kfont12.bin", FA_READ) != FR_OK) {
				return nullptr;
			}

			if(f_lseek(&fp, lin * 18) != FR_OK) {
				f_close(&fp);
				return nullptr;
			}

			UINT rs;
			if(f_read(&fp, &cash_[cash_idx_].bitmap[0], 18, &rs) != FR_OK) {
				f_close(&fp);
				return nullptr;
			}
			cash_[cash_idx_].code = code;

			f_close(&fp);

			return &cash_[cash_idx_].bitmap[0];
		}
	};
}
<|endoftext|>