<commit_before>// Copyright 2008 Henry de Valence
//
// 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, see <http://www.gnu.org/licenses/>.

//Mine
#include "worldclock.h"

//Qt
#include <QtGui/QPainter>

//KDE
#include <KDebug>
#include <KDialog>
#include <KConfigGroup>

//Plasma
#include <plasma/theme.h>
#include <plasma/dataengine.h>

//Marble
#include <marble/MarbleMap.h>
#include <marble/SunLocator.h>
#include <marble/ClipPainter.h>

WorldClock::WorldClock(QObject *parent, const QVariantList &args)
    : Plasma::Applet(parent, args),
    m_configDialog(0),
    m_map(0),
    m_sun(0)
{
    setHasConfigurationInterface(true);
    setDrawStandardBackground(true);
    //The applet needs a 2:1 ratio
    //so that the map fits properly
    resize(QSize(400, 200));
}

void WorldClock::init()
{
    KConfigGroup cg = config();

    m_map = new MarbleMap(  );
    m_map->setProjection( Equirectangular );

    m_map->setSize(geometry().size().width(), geometry().size().height());
    //The radius of the map using this projection
    //will always be 1/4 of the desired width.
    m_map->setRadius( (geometry().size().width() / 4 ) );

    //offset so that the date line isn't
    //right on the edge of the map
    //or user choice
    m_map->centerOn( cg.readEntry("rotation", -20), 0 );

    //Set how we want the map to look
    m_map->setMapTheme( "earth/bluemarble/bluemarble.dgml" );
    // &c.
    m_map->setShowCompass( false );
    m_map->setShowScaleBar( false );
    m_map->setShowGrid( false );
    m_map->setShowPlaces( false );
    m_map->setShowCities( true );
    m_map->setShowOtherPlaces( false );
    m_map->setShowRelief( true );
    m_map->setShowIceLayer( true );
    //Radius*4 = width
    m_map->setRadius( 100 );

    //Set up the Sun to draw night/day shadow
    m_sun = m_map->sunLocator();
    m_sun->setShow(true);
    m_sun->setCitylights(true);
    if(cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) == Qt::Checked)
         m_sun->setCentered(true);
    m_sun->update();
    m_map->updateSun();

    //We need to zoom the map every time we change size
    connect(this, SIGNAL(geometryChanged()), this, SLOT(resizeMap()));
}

WorldClock::~WorldClock()
{
    delete m_configDialog;
}

//We want to redraw the map every 10 mins
//so that the night/day shade is current.
//10 mins is 1/144th of a rotation.
void WorldClock::connectToEngine()
{
    Plasma::DataEngine* timeEngine = dataEngine("time");
    //update every 5 mins
    timeEngine->connectSource("Local", this, 30000, Plasma::AlignToMinute);
}

void WorldClock::resizeMap()
{
    m_map->setSize(geometry().size().width(), geometry().size().height());
    //The radius of the map using this projection
    //will always be 1/4 of the desired width.
    m_map->setRadius( (geometry().size().width() / 4 ) );
    update();
}

void WorldClock::dataUpdated(const QString &name,
                             const Plasma::DataEngine::Data &data)
{
    m_sun->update();
    m_map->updateSun();
    update();
}

void WorldClock::paintInterface(QPainter *p,
                                const QStyleOptionGraphicsItem *option,
                                const QRect &contentsRect)
{
    kDebug() << contentsRect;
    QRect rect = contentsRect;
    //By creating a pixmap and then painting that
    //we avoid an issue where the map is offset
    //from the border of the plasmoid and it looks ugly
    QPixmap pixmap( rect.size() );
    ClipPainter cp( &pixmap , false );
    m_map->paint(cp, rect);
    p->drawPixmap( 0, 0, pixmap );
}

void WorldClock::showConfigurationInterface()
{
    if(m_configDialog == 0) {
         m_configDialog = new KDialog;
	 ui.setupUi(m_configDialog->mainWidget());
	 m_configDialog->setPlainCaption(i18n("Worldclock Applet Configuration"));
         m_configDialog->setButtons(KDialog::Ok | KDialog::Apply |
	                            KDialog::Cancel);

         KConfigGroup cg = config();
         ui.rotationLatLonEdit->setValue(cg.readEntry("rotation", -20));
	 if(cg.readEntry("centersun", static_cast<int>(Qt::Unchecked))
                 == Qt::Checked)
              ui.centerSunCheckBox->setChecked(true);

         connect(m_configDialog, SIGNAL(okClicked()),
	         this, SLOT(configAccepted()));
	 connect(m_configDialog, SIGNAL(applyClicked()),
	         this, SLOT(configAccepted()));
    }

    m_configDialog->show();
}

void WorldClock::configAccepted()
{
    KConfigGroup cg = config();
    if( ui.centerSunCheckBox->checkState() !=
            cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) ) {
	switch(ui.centerSunCheckBox->checkState()) {
	    case Qt::Checked :
	        m_sun->setCentered(true);
		break;
	    default :
	        m_sun->setCentered(false);
		break;
        }
	m_sun->update();
        m_map->updateSun();
        update();
    }
    if( ui.rotationLatLonEdit->value() !=
              cg.readEntry("rotation", -20) ) {
	m_map->centerOn(ui.rotationLatLonEdit->value(), 0);
        update();
    }
    cg.writeEntry("centersun", static_cast<int>(ui.centerSunCheckBox->checkState()));
    cg.writeEntry("rotation", ui.rotationLatLonEdit->value());
}

#include "worldclock.moc"
<commit_msg>Now uses GeoPainter instead of ClipPainter<commit_after>// Copyright 2008 Henry de Valence
//
// 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, see <http://www.gnu.org/licenses/>.

//Mine
#include "worldclock.h"

//Qt
#include <QtGui/QPainter>

//KDE
#include <KDebug>
#include <KDialog>
#include <KConfigGroup>

//Plasma
#include <plasma/theme.h>
#include <plasma/dataengine.h>

//Marble
#include "../lib/MarbleMap.h"
#include "../lib/SunLocator.h"
#include "../lib/ViewParams.h"
#include "../lib/GeoPainter.h"

WorldClock::WorldClock(QObject *parent, const QVariantList &args)
    : Plasma::Applet(parent, args),
    m_configDialog(0),
    m_map(0),
    m_sun(0)
{
    setHasConfigurationInterface(true);
    //The applet needs a 2:1 ratio
    //so that the map fits properly
    resize(QSize(400, 200));
}

void WorldClock::init()
{
    KConfigGroup cg = config();

    m_map = new MarbleMap(  );
    m_map->setProjection( Equirectangular );

    m_map->setSize(geometry().size().width(), geometry().size().height());
    //The radius of the map using this projection
    //will always be 1/4 of the desired width.
    m_map->setRadius( (geometry().size().width() / 4 ) );

    //offset so that the date line isn't
    //right on the edge of the map
    //or user choice
    m_map->centerOn( cg.readEntry("rotation", -20), 0 );

    //Set how we want the map to look
    m_map->setMapTheme( "earth/bluemarble/bluemarble.dgml" );
    // &c.
    m_map->setShowCompass( false );
    m_map->setShowScaleBar( false );
    m_map->setShowGrid( false );
    m_map->setShowPlaces( false );
    m_map->setShowCities( true );
    m_map->setShowOtherPlaces( false );
    m_map->setShowRelief( true );
    m_map->setShowIceLayer( true );
    //Radius*4 = width
    m_map->setRadius( 100 );

    //Set up the Sun to draw night/day shadow
    m_sun = m_map->sunLocator();
    m_sun->setShow(true);
    m_sun->setCitylights(true);
    if(cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) == Qt::Checked)
         m_sun->setCentered(true);
    m_sun->update();
    m_map->updateSun();

    //We need to zoom the map every time we change size
    connect(this, SIGNAL(geometryChanged()), this, SLOT(resizeMap()));
}

WorldClock::~WorldClock()
{
    delete m_configDialog;
}

//We want to redraw the map every 10 mins
//so that the night/day shade is current.
//10 mins is 1/144th of a rotation.
void WorldClock::connectToEngine()
{
    Plasma::DataEngine* timeEngine = dataEngine("time");
    //update every 5 mins
    timeEngine->connectSource("Local", this, 30000, Plasma::AlignToMinute);
}

void WorldClock::resizeMap()
{
    m_map->setSize(geometry().size().width(), geometry().size().height());
    //The radius of the map using this projection
    //will always be 1/4 of the desired width.
    m_map->setRadius( (geometry().size().width() / 4 ) );
    update();
}

void WorldClock::dataUpdated(const QString &name,
                             const Plasma::DataEngine::Data &data)
{
    m_sun->update();
    m_map->updateSun();
    update();
}

void WorldClock::paintInterface(QPainter *p,
                                const QStyleOptionGraphicsItem *option,
                                const QRect &contentsRect)
{
    kDebug() << contentsRect;
    QRect rect = contentsRect;
    //By creating a pixmap and then painting that
    //we avoid an issue where the map is offset
    //from the border of the plasmoid and it looks ugly
    QPixmap pixmap( rect.size() );
    GeoPainter gp( &pixmap, m_map->viewParams()->viewport(), false );
    m_map->paint(gp, rect);
    p->drawPixmap( 0, 0, pixmap );
}

void WorldClock::showConfigurationInterface()
{
    if(m_configDialog == 0) {
         m_configDialog = new KDialog;
	 ui.setupUi(m_configDialog->mainWidget());
	 m_configDialog->setPlainCaption(i18n("Worldclock Applet Configuration"));
         m_configDialog->setButtons(KDialog::Ok | KDialog::Apply |
	                            KDialog::Cancel);

         KConfigGroup cg = config();
         ui.rotationLatLonEdit->setValue(cg.readEntry("rotation", -20));
	 if(cg.readEntry("centersun", static_cast<int>(Qt::Unchecked))
                 == Qt::Checked)
              ui.centerSunCheckBox->setChecked(true);

         connect(m_configDialog, SIGNAL(okClicked()),
	         this, SLOT(configAccepted()));
	 connect(m_configDialog, SIGNAL(applyClicked()),
	         this, SLOT(configAccepted()));
    }

    m_configDialog->show();
}

void WorldClock::configAccepted()
{
    KConfigGroup cg = config();
    if( ui.centerSunCheckBox->checkState() !=
            cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) ) {
	switch(ui.centerSunCheckBox->checkState()) {
	    case Qt::Checked :
	        m_sun->setCentered(true);
		break;
	    default :
	        m_sun->setCentered(false);
		break;
        }
	m_sun->update();
        m_map->updateSun();
        update();
    }
    if( ui.rotationLatLonEdit->value() !=
              cg.readEntry("rotation", -20) ) {
	m_map->centerOn(ui.rotationLatLonEdit->value(), 0);
        update();
    }
    cg.writeEntry("centersun", static_cast<int>(ui.centerSunCheckBox->checkState()));
    cg.writeEntry("rotation", ui.rotationLatLonEdit->value());
}

#include "worldclock.moc"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: splargs.hxx,v $
 * $Revision: 1.7 $
 *
 * 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.
 *
 ************************************************************************/
#ifndef _SPLARGS_HXX
#define _SPLARGS_HXX

#include <i18npool/lang.h>
#include <tools/solar.h>
#include <tools/gen.hxx>
#include <limits.h>       // USHRT_MAX
#include <tools/string.hxx>

class SwTxtNode;
class SwIndex;
class SpellCheck;
class Font;
#include <com/sun/star/linguistic2/XSpellAlternatives.hpp>
#include <com/sun/star/linguistic2/XSpellChecker1.hpp>
#include <com/sun/star/linguistic2/XHyphenatedWord.hpp>

/*************************************************************************
 *                      struct SwArgsBase
 *************************************************************************/

struct SwArgsBase     // used for text conversion (Hangul/Hanja, ...)
{
    SwTxtNode  *pStartNode;
    SwIndex    *pStartIdx;
    SwTxtNode  *pEndNode;
    SwIndex    *pEndIdx;

    SwArgsBase(
            SwTxtNode* pStart, SwIndex& rStart,
            SwTxtNode* pEnd, SwIndex& rEnd )
        : pStartNode( pStart ), pStartIdx( &rStart ),
          pEndNode( pEnd ), pEndIdx( &rEnd )
        {}

    void SetStart(SwTxtNode* pStart, SwIndex& rStart )
    {
        pStartNode = pStart;    pStartIdx = &rStart ;
    }

    void SetEnd( SwTxtNode* pEnd, SwIndex& rEnd  )
    {
        pEndNode = pEnd;        pEndIdx = &rEnd ;
    }
};

/*************************************************************************
 *                      struct SwConversionArgs
 * used for text conversion (Hangul/Hanja, Simplified/Traditional Chinese, ...)
 *************************************************************************/

struct SwConversionArgs : SwArgsBase
{
    rtl::OUString   aConvText;          // convertible text found
    LanguageType    nConvSrcLang;       // (source) language to look for
    LanguageType    nConvTextLang;      // language of aConvText (if the latter one was found)

    // used for chinese translation
    LanguageType    nConvTargetLang;    // target language of text to be changed
    const Font     *pTargetFont;        // target font of text to be changed
    // explicitly enables or disables application of the above two
    sal_Bool        bAllowImplicitChangesForNotConvertibleText;

    SwConversionArgs( LanguageType nLang,
            SwTxtNode* pStart, SwIndex& rStart,
            SwTxtNode* pEnd, SwIndex& rEnd )
        : SwArgsBase( pStart, rStart, pEnd, rEnd ),
          nConvSrcLang( nLang ),
          nConvTextLang( LANGUAGE_NONE ),
          nConvTargetLang( LANGUAGE_NONE ),
          pTargetFont( NULL ),
          bAllowImplicitChangesForNotConvertibleText( sal_False )
        {}
};

/*************************************************************************
 *                      struct SwSpellArgs
 *************************************************************************/

struct SwSpellArgs : SwArgsBase
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 >     xSpeller;

    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellAlternatives > xSpellAlt;

    SwSpellArgs(::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XSpellChecker1 > &rxSplChk,
            SwTxtNode* pStart, SwIndex& rStart,
            SwTxtNode* pEnd, SwIndex& rEnd )
        :   SwArgsBase( pStart, rStart, pEnd, rEnd ),
            xSpeller( rxSplChk )
        {}
};

/*************************************************************************
 *                      class SwInterHyphInfo
 *************************************************************************/

// Parameter-Klasse fuer Hyphenate
// docedt.cxx:  SwDoc::Hyphenate()
// txtedt.cxx:  SwTxtNode::Hyphenate()
// txthyph.cxx: SwTxtFrm::Hyphenate()

class SwInterHyphInfo
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XHyphenatedWord >    xHyphWord;
    const   Point aCrsrPos;
    sal_Bool    bAuto   : 1;
    sal_Bool    bNoLang : 1;
    sal_Bool    bCheck  : 1;
public:
    xub_StrLen nStart;
    xub_StrLen nLen;
    xub_StrLen nWordStart;
    xub_StrLen nWordLen;
    xub_StrLen nHyphPos;
    sal_uInt16 nMinTrail;

    inline SwInterHyphInfo( const Point &rCrsrPos,
                            const sal_uInt16 nStartPos = 0,
                            const sal_uInt16 nLength = USHRT_MAX )
         : aCrsrPos( rCrsrPos ),
           bAuto(sal_False), bNoLang(sal_False), bCheck(sal_False),
           nStart(nStartPos), nLen(nLength),
           nWordStart(0), nWordLen(0),
           nHyphPos(0), nMinTrail(0)
         { }
    inline xub_StrLen GetEnd() const
    { return STRING_LEN == nLen ? nLen : nStart + nLen; }
    inline const Point *GetCrsrPos() const
    { return aCrsrPos.X() || aCrsrPos.Y() ? &aCrsrPos : 0; }
    inline sal_Bool IsCheck() const { return bCheck; }
    inline void SetCheck( const sal_Bool bNew ) { bCheck = bNew; }
    inline void SetNoLang( const sal_Bool bNew ) { bNoLang = bNew; }

    inline void
            SetHyphWord(const ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XHyphenatedWord >  &rxHW)
            { xHyphWord = rxHW; }
    inline ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XHyphenatedWord >
            GetHyphWord() { return xHyphWord; }
};

#endif
<commit_msg>INTEGRATION: CWS tl55 (1.7.50); FILE MERGED 2008/06/26 14:19:58 os 1.7.50.1: i85999 interactive grammar checking<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: splargs.hxx,v $
 * $Revision: 1.8 $
 *
 * 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.
 *
 ************************************************************************/
#ifndef _SPLARGS_HXX
#define _SPLARGS_HXX

#include <i18npool/lang.h>
#include <tools/solar.h>
#include <tools/gen.hxx>
#include <limits.h>       // USHRT_MAX
#include <tools/string.hxx>

class SwTxtNode;
class SwIndex;
class SpellCheck;
class Font;
#include <com/sun/star/linguistic2/XSpellAlternatives.hpp>
#include <com/sun/star/linguistic2/XSpellChecker1.hpp>
#include <com/sun/star/linguistic2/XHyphenatedWord.hpp>

/*************************************************************************
 *                      struct SwArgsBase
 *************************************************************************/

struct SwArgsBase     // used for text conversion (Hangul/Hanja, ...)
{
    SwTxtNode  *pStartNode;
    SwIndex    *pStartIdx;
    SwTxtNode  *pEndNode;
    SwIndex    *pEndIdx;

    SwArgsBase(
            SwTxtNode* pStart, SwIndex& rStart,
            SwTxtNode* pEnd, SwIndex& rEnd )
        : pStartNode( pStart ), pStartIdx( &rStart ),
          pEndNode( pEnd ), pEndIdx( &rEnd )
        {}

    void SetStart(SwTxtNode* pStart, SwIndex& rStart )
    {
        pStartNode = pStart;    pStartIdx = &rStart ;
    }

    void SetEnd( SwTxtNode* pEnd, SwIndex& rEnd  )
    {
        pEndNode = pEnd;        pEndIdx = &rEnd ;
    }
};

/*************************************************************************
 *                      struct SwConversionArgs
 * used for text conversion (Hangul/Hanja, Simplified/Traditional Chinese, ...)
 *************************************************************************/

struct SwConversionArgs : SwArgsBase
{
    rtl::OUString   aConvText;          // convertible text found
    LanguageType    nConvSrcLang;       // (source) language to look for
    LanguageType    nConvTextLang;      // language of aConvText (if the latter one was found)

    // used for chinese translation
    LanguageType    nConvTargetLang;    // target language of text to be changed
    const Font     *pTargetFont;        // target font of text to be changed
    // explicitly enables or disables application of the above two
    sal_Bool        bAllowImplicitChangesForNotConvertibleText;

    SwConversionArgs( LanguageType nLang,
            SwTxtNode* pStart, SwIndex& rStart,
            SwTxtNode* pEnd, SwIndex& rEnd )
        : SwArgsBase( pStart, rStart, pEnd, rEnd ),
          nConvSrcLang( nLang ),
          nConvTextLang( LANGUAGE_NONE ),
          nConvTargetLang( LANGUAGE_NONE ),
          pTargetFont( NULL ),
          bAllowImplicitChangesForNotConvertibleText( sal_False )
        {}
};

/*************************************************************************
 *                      struct SwSpellArgs
 *************************************************************************/

struct SwSpellArgs : SwArgsBase
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 >     xSpeller;

    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellAlternatives > xSpellAlt;

    bool bIsGrammarCheck;

    SwSpellArgs(::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XSpellChecker1 > &rxSplChk,
            SwTxtNode* pStart, SwIndex& rStart,
            SwTxtNode* pEnd, SwIndex& rEnd,
            bool bGrammar )
        :   SwArgsBase( pStart, rStart, pEnd, rEnd ),
            xSpeller( rxSplChk ),
            bIsGrammarCheck( bGrammar )
        {}
};

/*************************************************************************
 *                      class SwInterHyphInfo
 *************************************************************************/

// Parameter-Klasse fuer Hyphenate
// docedt.cxx:  SwDoc::Hyphenate()
// txtedt.cxx:  SwTxtNode::Hyphenate()
// txthyph.cxx: SwTxtFrm::Hyphenate()

class SwInterHyphInfo
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XHyphenatedWord >    xHyphWord;
    const   Point aCrsrPos;
    sal_Bool    bAuto   : 1;
    sal_Bool    bNoLang : 1;
    sal_Bool    bCheck  : 1;
public:
    xub_StrLen nStart;
    xub_StrLen nLen;
    xub_StrLen nWordStart;
    xub_StrLen nWordLen;
    xub_StrLen nHyphPos;
    sal_uInt16 nMinTrail;

    inline SwInterHyphInfo( const Point &rCrsrPos,
                            const sal_uInt16 nStartPos = 0,
                            const sal_uInt16 nLength = USHRT_MAX )
         : aCrsrPos( rCrsrPos ),
           bAuto(sal_False), bNoLang(sal_False), bCheck(sal_False),
           nStart(nStartPos), nLen(nLength),
           nWordStart(0), nWordLen(0),
           nHyphPos(0), nMinTrail(0)
         { }
    inline xub_StrLen GetEnd() const
    { return STRING_LEN == nLen ? nLen : nStart + nLen; }
    inline const Point *GetCrsrPos() const
    { return aCrsrPos.X() || aCrsrPos.Y() ? &aCrsrPos : 0; }
    inline sal_Bool IsCheck() const { return bCheck; }
    inline void SetCheck( const sal_Bool bNew ) { bCheck = bNew; }
    inline void SetNoLang( const sal_Bool bNew ) { bNoLang = bNew; }

    inline void
            SetHyphWord(const ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XHyphenatedWord >  &rxHW)
            { xHyphWord = rxHW; }
    inline ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XHyphenatedWord >
            GetHyphWord() { return xHyphWord; }
};

#endif
<|endoftext|>


<commit_before>/* Copyright (c) 2013-2015 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "Display.h"

#include "DisplayGL.h"
#include "DisplayQt.h"

using namespace QGBA;

#if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY)
Display::Driver Display::s_driver = Display::Driver::OPENGL;
#else
Display::Driver Display::s_driver = Display::Driver::QT;
#endif

Display* Display::create(QWidget* parent) {
#if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY)
	QSurfaceFormat format;
	format.setSwapInterval(1);
	format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
#endif

	switch (s_driver) {
#if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY)
	case Driver::OPENGL:
		format.setVersion(3, 2);
		format.setProfile(QSurfaceFormat::CoreProfile);
		return new DisplayGL(format, parent);
#endif
#ifdef BUILD_GL
	case Driver::OPENGL1:
		format.setVersion(1, 4);
		return new DisplayGL(format, parent);
#endif

	case Driver::QT:
		return new DisplayQt(parent);

	default:
#if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY)
		return new DisplayGL(format, parent);
#else
		return new DisplayQt(parent);
#endif
	}
}

Display::Display(QWidget* parent)
	: QWidget(parent)
{
	setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
	connect(&m_mouseTimer, &QTimer::timeout, this, &Display::hideCursor);
	m_mouseTimer.setSingleShot(true);
	m_mouseTimer.setInterval(MOUSE_DISAPPEAR_TIMER);
	setMouseTracking(true);
}

void Display::resizeEvent(QResizeEvent*) {
	m_messagePainter.resize(size(), m_lockAspectRatio, devicePixelRatio());
}

void Display::lockAspectRatio(bool lock) {
	m_lockAspectRatio = lock;
	m_messagePainter.resize(size(), m_lockAspectRatio, devicePixelRatio());
}

void Display::lockIntegerScaling(bool lock) {
	m_lockIntegerScaling = lock;
}

void Display::interframeBlending(bool lock) {
	m_interframeBlending = lock;
}

void Display::showOSDMessages(bool enable) {
	m_showOSD = enable;
}

void Display::filter(bool filter) {
	m_filter = filter;
}

void Display::showMessage(const QString& message) {
	m_messagePainter.showMessage(message);
	if (!isDrawing()) {
		forceDraw();
	}
}

void Display::mouseMoveEvent(QMouseEvent*) {
	emit showCursor();
	m_mouseTimer.stop();
	m_mouseTimer.start();
}
<commit_msg>Qt: Try GLES 3.0 if using GLES<commit_after>/* Copyright (c) 2013-2015 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "Display.h"

#include "DisplayGL.h"
#include "DisplayQt.h"

using namespace QGBA;

#if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY)
Display::Driver Display::s_driver = Display::Driver::OPENGL;
#else
Display::Driver Display::s_driver = Display::Driver::QT;
#endif

Display* Display::create(QWidget* parent) {
#if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY)
	QSurfaceFormat format;
	format.setSwapInterval(1);
	format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
#endif

	switch (s_driver) {
#if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY)
	case Driver::OPENGL:
		if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES) {
			format.setVersion(3, 0);
		} else {
			format.setVersion(3, 2);
		}
		format.setProfile(QSurfaceFormat::CoreProfile);
		return new DisplayGL(format, parent);
#endif
#ifdef BUILD_GL
	case Driver::OPENGL1:
		format.setVersion(1, 4);
		return new DisplayGL(format, parent);
#endif

	case Driver::QT:
		return new DisplayQt(parent);

	default:
#if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY)
		return new DisplayGL(format, parent);
#else
		return new DisplayQt(parent);
#endif
	}
}

Display::Display(QWidget* parent)
	: QWidget(parent)
{
	setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
	connect(&m_mouseTimer, &QTimer::timeout, this, &Display::hideCursor);
	m_mouseTimer.setSingleShot(true);
	m_mouseTimer.setInterval(MOUSE_DISAPPEAR_TIMER);
	setMouseTracking(true);
}

void Display::resizeEvent(QResizeEvent*) {
	m_messagePainter.resize(size(), m_lockAspectRatio, devicePixelRatio());
}

void Display::lockAspectRatio(bool lock) {
	m_lockAspectRatio = lock;
	m_messagePainter.resize(size(), m_lockAspectRatio, devicePixelRatio());
}

void Display::lockIntegerScaling(bool lock) {
	m_lockIntegerScaling = lock;
}

void Display::interframeBlending(bool lock) {
	m_interframeBlending = lock;
}

void Display::showOSDMessages(bool enable) {
	m_showOSD = enable;
}

void Display::filter(bool filter) {
	m_filter = filter;
}

void Display::showMessage(const QString& message) {
	m_messagePainter.showMessage(message);
	if (!isDrawing()) {
		forceDraw();
	}
}

void Display::mouseMoveEvent(QMouseEvent*) {
	emit showCursor();
	m_mouseTimer.stop();
	m_mouseTimer.start();
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

// Command line was: qdbusxml2cpp -c MApplicationIfProxy -p mapplicationifproxy.h:mapplicationifproxy.cpp com.nokia.MApplicationIf.xml

#include "mapplicationifproxy.h"

MApplicationIfProxy::MApplicationIfProxy(const QString &service, QObject *parent) :
    QDBusAbstractInterface(service, "/org/maemo/m", "com.nokia.MApplicationIf", QDBusConnection::sessionBus(), parent)
{
}

MApplicationIfProxy::~MApplicationIfProxy()
{
}

QDBusPendingReply<> MApplicationIfProxy::close()
{
    return asyncCall(QLatin1String("close"));
}

QDBusPendingReply<> MApplicationIfProxy::exit()
{
    return asyncCall(QLatin1String("exit"));
}

QDBusPendingReply<> MApplicationIfProxy::launch()
{
    return callWithArgumentList(QDBus::BlockWithGui, QLatin1String("launch"), QList<QVariant>());
}

QDBusPendingReply<> MApplicationIfProxy::launch(const QStringList &parameters)
{
    QList<QVariant> argumentList;
    argumentList << qVariantFromValue(parameters);
    return callWithArgumentList(QDBus::BlockWithGui, QLatin1String("launch"), argumentList);
}
<commit_msg>Fixes: NB#143963 - some duiapplicationservice if methods should not cause application to launch<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

// Command line was: qdbusxml2cpp -c MApplicationIfProxy -p mapplicationifproxy.h:mapplicationifproxy.cpp com.nokia.MApplicationIf.xml

#include "mapplicationifproxy.h"

MApplicationIfProxy::MApplicationIfProxy(const QString &service, QObject *parent) :
    QDBusAbstractInterface(service, "/org/maemo/m", "com.nokia.MApplicationIf", QDBusConnection::sessionBus(), parent)
{
}

MApplicationIfProxy::~MApplicationIfProxy()
{
}

QDBusPendingReply<> MApplicationIfProxy::close()
{
    return asyncCall(QLatin1String("close"));
}

QDBusPendingReply<> MApplicationIfProxy::exit()
{
    // here we only do the dbus call, when the interface is valid,
    // i.e. there is a program listening "on the other side" of the
    // dbus connection.
    if ( isValid() )
    {
        return asyncCall(QLatin1String("exit"));
    }
    else
    {
        return QDBusPendingReply<>();
    }
}

QDBusPendingReply<> MApplicationIfProxy::launch()
{
    return callWithArgumentList(QDBus::BlockWithGui, QLatin1String("launch"), QList<QVariant>());
}

QDBusPendingReply<> MApplicationIfProxy::launch(const QStringList &parameters)
{
    QList<QVariant> argumentList;
    argumentList << qVariantFromValue(parameters);
    return callWithArgumentList(QDBus::BlockWithGui, QLatin1String("launch"), argumentList);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: simpleioerrorrequest.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kso $ $Date: 2001-06-19 09:18:27 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_UCB_INTERACTIVEAUGMENTEDIOEXCEPTION_HPP_
#include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp>
#endif

#ifndef _UCBHELPER_SIMPLEIOERRORREQUEST_HXX
#include <ucbhelper/simpleioerrorrequest.hxx>
#endif

using namespace com::sun::star;
using namespace ucbhelper;

//=========================================================================
SimpleIOErrorRequest::SimpleIOErrorRequest(
                const ucb::IOErrorCode eError,
                const uno::Sequence< uno::Any > & rArgs,
                const rtl::OUString & rMessage,
                const uno::Reference< ucb::XCommandProcessor > & xContext )
{
    // Fill request...
    ucb::InteractiveAugmentedIOException aRequest;
    aRequest.Message         = rMessage;
    aRequest.Context         = xContext;
    aRequest.Classification  = task::InteractionClassification_ERROR;
    aRequest.Code            = eError;
    aRequest.Arguments       = rArgs;

    setRequest( uno::makeAny( aRequest ) );

    // Fill continuations...
    uno::Sequence< uno::Reference<
            task::XInteractionContinuation > > aContinuations( 1 );
    aContinuations[ 0 ] = new InteractionAbort( this );

    setContinuations( aContinuations );
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.170); FILE MERGED 2005/09/05 13:14:03 rt 1.6.170.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: simpleioerrorrequest.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 16:42:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_UCB_INTERACTIVEAUGMENTEDIOEXCEPTION_HPP_
#include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp>
#endif

#ifndef _UCBHELPER_SIMPLEIOERRORREQUEST_HXX
#include <ucbhelper/simpleioerrorrequest.hxx>
#endif

using namespace com::sun::star;
using namespace ucbhelper;

//=========================================================================
SimpleIOErrorRequest::SimpleIOErrorRequest(
                const ucb::IOErrorCode eError,
                const uno::Sequence< uno::Any > & rArgs,
                const rtl::OUString & rMessage,
                const uno::Reference< ucb::XCommandProcessor > & xContext )
{
    // Fill request...
    ucb::InteractiveAugmentedIOException aRequest;
    aRequest.Message         = rMessage;
    aRequest.Context         = xContext;
    aRequest.Classification  = task::InteractionClassification_ERROR;
    aRequest.Code            = eError;
    aRequest.Arguments       = rArgs;

    setRequest( uno::makeAny( aRequest ) );

    // Fill continuations...
    uno::Sequence< uno::Reference<
            task::XInteractionContinuation > > aContinuations( 1 );
    aContinuations[ 0 ] = new InteractionAbort( this );

    setContinuations( aContinuations );
}

<|endoftext|>


<commit_before>#include "idt.hpp"
#include <kernel/events.hpp>
#include <kernel/syscalls.hpp>
#include <kprint>
#include <info>
#define RING0_CODE_SEG   0x8

extern "C" {
  extern void unused_interrupt_handler();
  extern void modern_interrupt_handler();
  extern void spurious_intr();
  extern void cpu_enable_panicking();
}

#define IRQ_LINES  Events::NUM_EVENTS
#define INTR_LINES (IRQ_BASE + IRQ_LINES)

namespace x86
{
typedef void (*intr_handler_t)();
typedef void (*except_handler_t)();

struct x86_IDT
{
  IDTDescr entry[INTR_LINES] __attribute__((aligned(16)));

  intr_handler_t get_handler(uint8_t vec);
  void set_handler(uint8_t, intr_handler_t);
  void set_exception_handler(uint8_t, except_handler_t);

  void init();
};
static std::array<x86_IDT, SMP_MAX_CORES> idt;

void idt_initialize_for_cpu(int cpu) {
  idt.at(cpu).init();
}

// A union to be able to extract the lower and upper part of an address
union addr_union {
  uintptr_t whole;
  struct {
    uint16_t lo16;
    uint16_t hi16;
#ifdef ARCH_x86_64
    uint32_t top32;
#endif
  };
};

static void set_intr_entry(
    IDTDescr* idt_entry,
    intr_handler_t func,
    uint8_t  ist,
    uint16_t segment_sel,
    char attributes)
{
  addr_union addr;
  addr.whole           = (uintptr_t) func;
  idt_entry->offset_1  = addr.lo16;
  idt_entry->offset_2  = addr.hi16;
#ifdef ARCH_x86_64
  idt_entry->offset_3  = addr.top32;
#endif
  idt_entry->selector  = segment_sel;
  idt_entry->type_attr = attributes;
#ifdef ARCH_x86_64
  idt_entry->ist       = ist;
  idt_entry->zero2     = 0;
#else
  (void) ist;
  idt_entry->zero      = 0;
#endif
}

intr_handler_t x86_IDT::get_handler(uint8_t vec)
{
  addr_union addr;
  addr.lo16  = entry[vec].offset_1;
  addr.hi16  = entry[vec].offset_2;
#ifdef ARCH_x86_64
  addr.top32 = entry[vec].offset_3;
#endif

  return (intr_handler_t) addr.whole;
}

void x86_IDT::set_handler(uint8_t vec, intr_handler_t func) {
  set_intr_entry(&entry[vec], func, 1, RING0_CODE_SEG, 0x8e);
}
void x86_IDT::set_exception_handler(uint8_t vec, except_handler_t func) {
  set_intr_entry(&entry[vec], (intr_handler_t) func, 2, RING0_CODE_SEG, 0x8e);
}

extern "C" {
  void __cpu_except_0();
  void __cpu_except_1();
  void __cpu_except_2();
  void __cpu_except_3();
  void __cpu_except_4();
  void __cpu_except_5();
  void __cpu_except_6();
  void __cpu_except_7();
  void __cpu_except_8();
  void __cpu_except_9();
  void __cpu_except_10();
  void __cpu_except_11();
  void __cpu_except_12();
  void __cpu_except_13();
  void __cpu_except_14();
  void __cpu_except_15();
  void __cpu_except_16();
  void __cpu_except_17();
  void __cpu_except_18();
  void __cpu_except_19();
  void __cpu_except_20();
  void __cpu_except_30();
}

void x86_IDT::init()
{
  // make sure its all zeroes
  memset(&PER_CPU(idt).entry, 0, sizeof(x86_IDT::entry));

  set_exception_handler(0, __cpu_except_0);
  set_exception_handler(1, __cpu_except_1);
  set_exception_handler(2, __cpu_except_2);
  set_exception_handler(3, __cpu_except_3);
  set_exception_handler(4, __cpu_except_4);
  set_exception_handler(5, __cpu_except_5);
  set_exception_handler(6, __cpu_except_6);
  set_exception_handler(7, __cpu_except_7);
  set_exception_handler(8, __cpu_except_8);
  set_exception_handler(9, __cpu_except_9);
  set_exception_handler(10, __cpu_except_10);
  set_exception_handler(11, __cpu_except_11);
  set_exception_handler(12, __cpu_except_12);
  set_exception_handler(13, __cpu_except_13);
  set_exception_handler(14, __cpu_except_14);
  set_exception_handler(15, __cpu_except_15);
  set_exception_handler(16, __cpu_except_16);
  set_exception_handler(17, __cpu_except_17);
  set_exception_handler(18, __cpu_except_18);
  set_exception_handler(19, __cpu_except_19);
  set_exception_handler(20, __cpu_except_20);
  set_exception_handler(30, __cpu_except_30);

  for (size_t i = 32; i < INTR_LINES - 2; i++) {
    set_handler(i, unused_interrupt_handler);
  }
  // spurious interrupt handler
  set_handler(INTR_LINES - 1, spurious_intr);

  // Load IDT
  IDTR idt_reg;
  idt_reg.limit = INTR_LINES * sizeof(IDTDescr) - 1;
  idt_reg.base = (uintptr_t) &entry[0];
  asm volatile ("lidt %0" : : "m"(idt_reg));
}

} // x86

void __arch_subscribe_irq(uint8_t irq)
{
  assert(irq < IRQ_LINES);
  PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, modern_interrupt_handler);
}
void __arch_install_irq(uint8_t irq, x86::intr_handler_t handler)
{
  assert(irq < IRQ_LINES);
  PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, handler);
}
void __arch_unsubscribe_irq(uint8_t irq)
{
  assert(irq < IRQ_LINES);
  PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, unused_interrupt_handler);
}

/// CPU EXCEPTIONS ///

#define PAGE_FAULT 14

static const char* exception_names[] =
{
  "Divide-by-zero Error",
  "Debug",
  "Non-maskable Interrupt",
  "Breakpoint",
  "Overflow",
  "Bound Range Exceeded",
  "Invalid Opcode",
  "Device Not Available",
  "Double Fault",
  "Reserved",
  "Invalid TSS",
  "Segment Not Present",
  "Stack-Segment Fault",
  "General Protection Fault",
  "Page Fault",
  "Reserved",
  "x87 Floating-point Exception",
  "Alignment Check",
  "Machine Check",
  "SIMD Floating-point Exception",
  "Virtualization Exception",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Security Exception",
  "Reserved"
};

void __cpu_dump_regs(uintptr_t* regs)
{
#if defined(ARCH_x86_64)
# define RIP_REG 16
  // AMD64 CPU registers
  struct desc_table_t {
    uint16_t  limit;
    uintptr_t location;
  } __attribute__((packed))  gdt, idt;
  asm ("sgdtq %0" : : "m" (* &gdt));
  asm ("sidtq %0" : : "m" (* &idt));

  fprintf(stderr, "\n");
  printf("  RAX:  %016lx  R 8:  %016lx\n", regs[0], regs[5]);
  printf("  RBX:  %016lx  R 9:  %016lx\n", regs[1], regs[6]);
  printf("  RCX:  %016lx  R10:  %016lx\n", regs[2], regs[7]);
  printf("  RDX:  %016lx  R11:  %016lx\n", regs[3], regs[8]);
  fprintf(stderr, "\n");

  printf("  RBP:  %016lx  R12:  %016lx\n", regs[4], regs[9]);
  printf("  RSP:  %016lx  R13:  %016lx\n", regs[13], regs[10]);
  printf("  RSI:  %016lx  R14:  %016lx\n", regs[14], regs[11]);
  printf("  RDI:  %016lx  R15:  %016lx\n", regs[15], regs[12]);
  printf("  RIP:  %016lx  FLA:  %016lx\n", regs[16], regs[17]);
  fprintf(stderr, "\n");

  printf("  CR0:  %016lx  CR4:  %016lx\n", regs[18], regs[22]);
  printf("  CR1:  %016lx  CR8:  %016lx\n", regs[19], regs[23]);
  printf("  CR2:  %016lx  GDT:  %016lx (%u)\n", regs[20], gdt.location, gdt.limit);
  printf("  CR3:  %016lx  IDT:  %016lx (%u)\n", regs[21], idt.location, idt.limit);

#elif defined(ARCH_i686)
# define RIP_REG 8
  // i386 CPU registers
  fprintf(stderr, "\n");
  printf("  EAX:  %08x  EBP:  %08x\n", regs[0], regs[4]);
  printf("  EBX:  %08x  ESP:  %08x\n", regs[1], regs[5]);
  printf("  ECX:  %08x  ESI:  %08x\n", regs[2], regs[6]);
  printf("  EDX:  %08x  EDI:  %08x\n", regs[3], regs[7]);

  fprintf(stderr, "\n");
  printf("  EIP:  %08x  EFL:  %08x\n", regs[8], regs[9]);

#else
  #error "Unknown architecture"
#endif
  fprintf(stderr, "\n");
}

extern "C" void double_fault(const char*);

void __page_fault(uintptr_t* regs, uint32_t code) {
  const char* reason = "Protection violation";

  if (not(code & 1))
    reason = "Page not present";

  kprintf("%s, trying to access 0x%lx\n", reason, regs[20]);

  if (code & 2)
    kprintf("Page write failed.\n");
  else
    kprintf("Page read failed.\n");

  if (code & 4)
    kprintf("Privileged page access from user space.\n");

  if (code & 8)
    kprintf("Found bit set in reserved field.\n");

  if (code & 16)
    kprintf("Instruction fetch. XD\n");

  if (code & 32)
    kprintf("Protection key violation.\n");

  if (code & 0x8000)
    kprintf("SGX access violation.\n");
}

extern "C"
__attribute__((noreturn optnone, weak))
void __cpu_exception(uintptr_t* regs, int error, uint32_t code)
{
  cpu_enable_panicking();
  SMP::global_lock();
  kprintf("\n>>>> !!! CPU %u EXCEPTION !!! <<<<\n", SMP::cpu_id());
  kprintf("%s (%d)   EIP  %p   CODE %#x\n",
          exception_names[error], error, (void*) regs[RIP_REG], code);

  if (error == PAGE_FAULT) {
    __page_fault(regs, code);
  }

  __cpu_dump_regs(regs);

  SMP::global_unlock();
  // error message:
  char buffer[64];
  snprintf(buffer, sizeof(buffer), "%s (%d)", exception_names[error], error);
  // normal CPU exception
  if (error != 0x8) {
    // call panic, which will decide what to do next
    panic(buffer);
  }
  else {
    // handle double faults differently
    double_fault(buffer);
  }

  __builtin_unreachable();
}
<commit_msg>x86: Remove optnone from IDT/__cpu_exception<commit_after>#include "idt.hpp"
#include <kernel/events.hpp>
#include <kernel/syscalls.hpp>
#include <kprint>
#include <info>
#define RING0_CODE_SEG   0x8

extern "C" {
  extern void unused_interrupt_handler();
  extern void modern_interrupt_handler();
  extern void spurious_intr();
  extern void cpu_enable_panicking();
}

#define IRQ_LINES  Events::NUM_EVENTS
#define INTR_LINES (IRQ_BASE + IRQ_LINES)

namespace x86
{
typedef void (*intr_handler_t)();
typedef void (*except_handler_t)();

struct x86_IDT
{
  IDTDescr entry[INTR_LINES] __attribute__((aligned(16)));

  intr_handler_t get_handler(uint8_t vec);
  void set_handler(uint8_t, intr_handler_t);
  void set_exception_handler(uint8_t, except_handler_t);

  void init();
};
static std::array<x86_IDT, SMP_MAX_CORES> idt;

void idt_initialize_for_cpu(int cpu) {
  idt.at(cpu).init();
}

// A union to be able to extract the lower and upper part of an address
union addr_union {
  uintptr_t whole;
  struct {
    uint16_t lo16;
    uint16_t hi16;
#ifdef ARCH_x86_64
    uint32_t top32;
#endif
  };
};

static void set_intr_entry(
    IDTDescr* idt_entry,
    intr_handler_t func,
    uint8_t  ist,
    uint16_t segment_sel,
    char attributes)
{
  addr_union addr;
  addr.whole           = (uintptr_t) func;
  idt_entry->offset_1  = addr.lo16;
  idt_entry->offset_2  = addr.hi16;
#ifdef ARCH_x86_64
  idt_entry->offset_3  = addr.top32;
#endif
  idt_entry->selector  = segment_sel;
  idt_entry->type_attr = attributes;
#ifdef ARCH_x86_64
  idt_entry->ist       = ist;
  idt_entry->zero2     = 0;
#else
  (void) ist;
  idt_entry->zero      = 0;
#endif
}

intr_handler_t x86_IDT::get_handler(uint8_t vec)
{
  addr_union addr;
  addr.lo16  = entry[vec].offset_1;
  addr.hi16  = entry[vec].offset_2;
#ifdef ARCH_x86_64
  addr.top32 = entry[vec].offset_3;
#endif

  return (intr_handler_t) addr.whole;
}

void x86_IDT::set_handler(uint8_t vec, intr_handler_t func) {
  set_intr_entry(&entry[vec], func, 1, RING0_CODE_SEG, 0x8e);
}
void x86_IDT::set_exception_handler(uint8_t vec, except_handler_t func) {
  set_intr_entry(&entry[vec], (intr_handler_t) func, 2, RING0_CODE_SEG, 0x8e);
}

extern "C" {
  void __cpu_except_0();
  void __cpu_except_1();
  void __cpu_except_2();
  void __cpu_except_3();
  void __cpu_except_4();
  void __cpu_except_5();
  void __cpu_except_6();
  void __cpu_except_7();
  void __cpu_except_8();
  void __cpu_except_9();
  void __cpu_except_10();
  void __cpu_except_11();
  void __cpu_except_12();
  void __cpu_except_13();
  void __cpu_except_14();
  void __cpu_except_15();
  void __cpu_except_16();
  void __cpu_except_17();
  void __cpu_except_18();
  void __cpu_except_19();
  void __cpu_except_20();
  void __cpu_except_30();
}

void x86_IDT::init()
{
  // make sure its all zeroes
  memset(&PER_CPU(idt).entry, 0, sizeof(x86_IDT::entry));

  set_exception_handler(0, __cpu_except_0);
  set_exception_handler(1, __cpu_except_1);
  set_exception_handler(2, __cpu_except_2);
  set_exception_handler(3, __cpu_except_3);
  set_exception_handler(4, __cpu_except_4);
  set_exception_handler(5, __cpu_except_5);
  set_exception_handler(6, __cpu_except_6);
  set_exception_handler(7, __cpu_except_7);
  set_exception_handler(8, __cpu_except_8);
  set_exception_handler(9, __cpu_except_9);
  set_exception_handler(10, __cpu_except_10);
  set_exception_handler(11, __cpu_except_11);
  set_exception_handler(12, __cpu_except_12);
  set_exception_handler(13, __cpu_except_13);
  set_exception_handler(14, __cpu_except_14);
  set_exception_handler(15, __cpu_except_15);
  set_exception_handler(16, __cpu_except_16);
  set_exception_handler(17, __cpu_except_17);
  set_exception_handler(18, __cpu_except_18);
  set_exception_handler(19, __cpu_except_19);
  set_exception_handler(20, __cpu_except_20);
  set_exception_handler(30, __cpu_except_30);

  for (size_t i = 32; i < INTR_LINES - 2; i++) {
    set_handler(i, unused_interrupt_handler);
  }
  // spurious interrupt handler
  set_handler(INTR_LINES - 1, spurious_intr);

  // Load IDT
  IDTR idt_reg;
  idt_reg.limit = INTR_LINES * sizeof(IDTDescr) - 1;
  idt_reg.base = (uintptr_t) &entry[0];
  asm volatile ("lidt %0" : : "m"(idt_reg));
}

} // x86

void __arch_subscribe_irq(uint8_t irq)
{
  assert(irq < IRQ_LINES);
  PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, modern_interrupt_handler);
}
void __arch_install_irq(uint8_t irq, x86::intr_handler_t handler)
{
  assert(irq < IRQ_LINES);
  PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, handler);
}
void __arch_unsubscribe_irq(uint8_t irq)
{
  assert(irq < IRQ_LINES);
  PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, unused_interrupt_handler);
}

/// CPU EXCEPTIONS ///

#define PAGE_FAULT 14

static const char* exception_names[] =
{
  "Divide-by-zero Error",
  "Debug",
  "Non-maskable Interrupt",
  "Breakpoint",
  "Overflow",
  "Bound Range Exceeded",
  "Invalid Opcode",
  "Device Not Available",
  "Double Fault",
  "Reserved",
  "Invalid TSS",
  "Segment Not Present",
  "Stack-Segment Fault",
  "General Protection Fault",
  "Page Fault",
  "Reserved",
  "x87 Floating-point Exception",
  "Alignment Check",
  "Machine Check",
  "SIMD Floating-point Exception",
  "Virtualization Exception",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Reserved",
  "Security Exception",
  "Reserved"
};

void __cpu_dump_regs(uintptr_t* regs)
{
#if defined(ARCH_x86_64)
# define RIP_REG 16
  // AMD64 CPU registers
  struct desc_table_t {
    uint16_t  limit;
    uintptr_t location;
  } __attribute__((packed))  gdt, idt;
  asm ("sgdtq %0" : : "m" (* &gdt));
  asm ("sidtq %0" : : "m" (* &idt));

  fprintf(stderr, "\n");
  printf("  RAX:  %016lx  R 8:  %016lx\n", regs[0], regs[5]);
  printf("  RBX:  %016lx  R 9:  %016lx\n", regs[1], regs[6]);
  printf("  RCX:  %016lx  R10:  %016lx\n", regs[2], regs[7]);
  printf("  RDX:  %016lx  R11:  %016lx\n", regs[3], regs[8]);
  fprintf(stderr, "\n");

  printf("  RBP:  %016lx  R12:  %016lx\n", regs[4], regs[9]);
  printf("  RSP:  %016lx  R13:  %016lx\n", regs[13], regs[10]);
  printf("  RSI:  %016lx  R14:  %016lx\n", regs[14], regs[11]);
  printf("  RDI:  %016lx  R15:  %016lx\n", regs[15], regs[12]);
  printf("  RIP:  %016lx  FLA:  %016lx\n", regs[16], regs[17]);
  fprintf(stderr, "\n");

  printf("  CR0:  %016lx  CR4:  %016lx\n", regs[18], regs[22]);
  printf("  CR1:  %016lx  CR8:  %016lx\n", regs[19], regs[23]);
  printf("  CR2:  %016lx  GDT:  %016lx (%u)\n", regs[20], gdt.location, gdt.limit);
  printf("  CR3:  %016lx  IDT:  %016lx (%u)\n", regs[21], idt.location, idt.limit);

#elif defined(ARCH_i686)
# define RIP_REG 8
  // i386 CPU registers
  fprintf(stderr, "\n");
  printf("  EAX:  %08x  EBP:  %08x\n", regs[0], regs[4]);
  printf("  EBX:  %08x  ESP:  %08x\n", regs[1], regs[5]);
  printf("  ECX:  %08x  ESI:  %08x\n", regs[2], regs[6]);
  printf("  EDX:  %08x  EDI:  %08x\n", regs[3], regs[7]);

  fprintf(stderr, "\n");
  printf("  EIP:  %08x  EFL:  %08x\n", regs[8], regs[9]);

#else
  #error "Unknown architecture"
#endif
  fprintf(stderr, "\n");
}

extern "C" void double_fault(const char*);

void __page_fault(uintptr_t* regs, uint32_t code) {
  const char* reason = "Protection violation";

  if (not(code & 1))
    reason = "Page not present";

  kprintf("%s, trying to access 0x%lx\n", reason, regs[20]);

  if (code & 2)
    kprintf("Page write failed.\n");
  else
    kprintf("Page read failed.\n");

  if (code & 4)
    kprintf("Privileged page access from user space.\n");

  if (code & 8)
    kprintf("Found bit set in reserved field.\n");

  if (code & 16)
    kprintf("Instruction fetch. XD\n");

  if (code & 32)
    kprintf("Protection key violation.\n");

  if (code & 0x8000)
    kprintf("SGX access violation.\n");
}

extern "C"
__attribute__((noreturn, weak))
void __cpu_exception(uintptr_t* regs, int error, uint32_t code)
{
  cpu_enable_panicking();
  SMP::global_lock();
  kprintf("\n>>>> !!! CPU %u EXCEPTION !!! <<<<\n", SMP::cpu_id());
  kprintf("%s (%d)   EIP  %p   CODE %#x\n",
          exception_names[error], error, (void*) regs[RIP_REG], code);

  if (error == PAGE_FAULT) {
    __page_fault(regs, code);
  }

  __cpu_dump_regs(regs);

  SMP::global_unlock();
  // error message:
  char buffer[64];
  snprintf(buffer, sizeof(buffer), "%s (%d)", exception_names[error], error);
  // normal CPU exception
  if (error != 0x8) {
    // call panic, which will decide what to do next
    panic(buffer);
  }
  else {
    // handle double faults differently
    double_fault(buffer);
  }

  __builtin_unreachable();
}
<|endoftext|>


<commit_before>/*
 * Copyright © 2012, United States Government, as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 * All rights reserved.
 *
 * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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.
 */

/**
 * @file AppEscape_T6.cpp
 * @brief Contains the definition function main() for the Escape T6
 * application.
 * $Id$
 */

// This application
#include "Escape_T6Model.h"
#include "Escape_T6Controller.h"

// This library
#include "core/terrain/tgHillyGround.h"
#include "core/tgModel.h"
#include "core/tgSimViewGraphics.h"
#include "core/tgSimulation.h"
#include "core/tgWorld.h"

// Bullet Physics
#include "LinearMath/btVector3.h"

// The C++ Standard Library
#include <iostream>

tgHillyGround *createGround();
tgWorld *createWorld();
tgSimViewGraphics *createGraphicsView(tgWorld *world);
tgSimView *createView(tgWorld *world);
void simulate(tgSimulation *simulation);

/**
 * Runs a series of episodes.
 * Each episode tests a given control pattern for a given number of steps.
 * The fitness function (reward metric) for this experiment is
 *     the maximum distance from the tensegrity's starting point
 *     at any point during the episode
 * NB: Running episodes and using graphics are mutually exclusive features
 */
int main(int argc, char** argv)
{
    std::cout << "AppEscape_T6" << std::endl;

    // First create the world
    tgWorld *world = createWorld();

    // Second create the view
    //tgSimViewGraphics *view = createGraphicsView(world); // For visual experimenting on one tensegrity
    tgSimView       *view = createView(world);         // For running multiple episodes

    // Third create the simulation
    tgSimulation *simulation = new tgSimulation(*view);

    // Fourth create the models with their controllers and add the models to the simulation
    Escape_T6Model* const model = new Escape_T6Model();

    // Fifth create controller and attach it to the model
    double initialLength = 9; // decimeters
    Escape_T6Controller* const controller = new Escape_T6Controller(initialLength);
    model->attach(controller);

    //Sixth add model (with controller) to simulation
    simulation->addModel(model);

    simulate(simulation);

    //Teardown is handled by delete, so that should be automatic
    return 0;
}

tgHillyGround *createGround() {
    // Determine the angle of the ground in radians. All 0 is flat
    const double yaw = 0.0;
    const double pitch = 0.0;
    const double roll = 0.0;
    const tgHillyGround::Config groundConfig(btVector3(yaw, pitch, roll));
    // the world will delete this
    return new tgHillyGround(groundConfig);
}

tgWorld *createWorld() {
    const tgWorld::Config config(98.1); // gravity, cm/sec^2  Use this to adjust length scale of world.
    // NB: by changing the setting below from 981 to 98.1, we've
    // scaled the world length scale to decimeters not cm.

    tgHillyGround* ground = createGround();
    return new tgWorld(config, ground);
}

/** Use for displaying tensegrities in simulation */
tgSimViewGraphics *createGraphicsView(tgWorld *world) {
    const double timestep_physics = 1.0 / 60.0 / 10.0; // Seconds
    const double timestep_graphics = 1.f /60.f; // Seconds, AKA render rate
    return new tgSimViewGraphics(*world, timestep_physics, timestep_graphics);
}

/** Use for trial episodes of many tensegrities in an experiment */
tgSimView *createView(tgWorld *world) {
    const double timestep_physics = 1.0 / 60.0 / 10.0; // Seconds
    const double timestep_graphics = 1.f /60.f; // Seconds, AKA render rate
    return new tgSimView(*world, timestep_physics, timestep_graphics);
}

/** Run a series of episodes for nSteps each */
void simulate(tgSimulation *simulation) {
    int nEpisodes = 10; // Number of episodes ("trial runs")
    int nSteps = 60000; // Number of steps in each episode
    for (int i=0; i<nEpisodes; i++)
    {
        simulation->run(nSteps);
        simulation->reset();
    }
}

<commit_msg>Added explicit arguments to tgHillyGround constructor call<commit_after>/*
 * Copyright © 2012, United States Government, as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 * All rights reserved.
 *
 * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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.
 */

/**
 * @file AppEscape_T6.cpp
 * @brief Contains the definition function main() for the Escape T6
 * application.
 * $Id$
 */

// This application
#include "Escape_T6Model.h"
#include "Escape_T6Controller.h"

// This library
#include "core/terrain/tgHillyGround.h"
#include "core/tgModel.h"
#include "core/tgSimViewGraphics.h"
#include "core/tgSimulation.h"
#include "core/tgWorld.h"

// Bullet Physics
#include "LinearMath/btVector3.h"

// The C++ Standard Library
#include <iostream>

tgHillyGround *createGround();
tgWorld *createWorld();
tgSimViewGraphics *createGraphicsView(tgWorld *world);
tgSimView *createView(tgWorld *world);
void simulate(tgSimulation *simulation);

/**
 * Runs a series of episodes.
 * Each episode tests a given control pattern for a given number of steps.
 * The fitness function (reward metric) for this experiment is
 *     the maximum distance from the tensegrity's starting point
 *     at any point during the episode
 * NB: Running episodes and using graphics are mutually exclusive features
 */
int main(int argc, char** argv)
{
    std::cout << "AppEscape_T6" << std::endl;

    // First create the world
    tgWorld *world = createWorld();

    // Second create the view
    tgSimViewGraphics *view = createGraphicsView(world); // For visual experimenting on one tensegrity
    //tgSimView       *view = createView(world);         // For running multiple episodes

    // Third create the simulation
    tgSimulation *simulation = new tgSimulation(*view);

    // Fourth create the models with their controllers and add the models to the simulation
    Escape_T6Model* const model = new Escape_T6Model();

    // Fifth create controller and attach it to the model
    double initialLength = 9; // decimeters
    Escape_T6Controller* const controller = new Escape_T6Controller(initialLength);
    model->attach(controller);

    //Sixth add model (with controller) to simulation
    simulation->addModel(model);

    simulate(simulation);

    //Teardown is handled by delete, so that should be automatic
    return 0;
}

tgHillyGround *createGround() {
    // Determine the angle of the ground in radians. All 0 is flat
    const double yaw = 0.0;
    const double pitch = 0.0;
    const double roll = 0.0;
    const btVector3 eulerAngles = btVector3(yaw, pitch, roll);  // Default: (0.0, 0.0, 0.0)
    const double friction = 0.5; // Default: 0.5
    const double restitution = 0.0;  // Default: 0.0
    const btVector3 size = btVector3(500.0, 1.5, 500.0); // Default: (500.0, 1.5, 500.0)
    const btVector3 origin = btVector3(0.0, 0.0, 0.0); // Default: (0.0, 0.0, 0.0)
    const size_t nx = 50; // Default: 50
    const size_t ny = 50; // Default: 50
    const double margin = 0.5; // Default: 0.5
    const double triangleSize = 5.0; // Default: 5.0
    const double waveHeight = 2.0; // Default: 5.0
    const double offset = 0.5; // Default: 0.5
    const tgHillyGround::Config groundConfig(eulerAngles, friction, restitution, size, origin,
                                             nx, ny, margin, triangleSize, waveHeight, offset);
    // the world will delete this
    return new tgHillyGround(groundConfig);
}

tgWorld *createWorld() {
    const tgWorld::Config config(98.1); // gravity, cm/sec^2  Use this to adjust length scale of world.
    // NB: by changing the setting below from 981 to 98.1, we've
    // scaled the world length scale to decimeters not cm.

    tgHillyGround* ground = createGround();
    return new tgWorld(config, ground);
}

/** Use for displaying tensegrities in simulation */
tgSimViewGraphics *createGraphicsView(tgWorld *world) {
    const double timestep_physics = 1.0 / 60.0 / 10.0; // Seconds
    const double timestep_graphics = 1.f /60.f; // Seconds, AKA render rate
    return new tgSimViewGraphics(*world, timestep_physics, timestep_graphics);
}

/** Use for trial episodes of many tensegrities in an experiment */
tgSimView *createView(tgWorld *world) {
    const double timestep_physics = 1.0 / 60.0 / 10.0; // Seconds
    const double timestep_graphics = 1.f /60.f; // Seconds, AKA render rate
    return new tgSimView(*world, timestep_physics, timestep_graphics);
}

/** Run a series of episodes for nSteps each */
void simulate(tgSimulation *simulation) {
    int nEpisodes = 10; // Number of episodes ("trial runs")
    int nSteps = 60000; // Number of steps in each episode
    for (int i=0; i<nEpisodes; i++)
    {
        simulation->run(nSteps);
        simulation->reset();
    }
}

<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <unistd.h>
#include "fnord-base/application.h"
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/random.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/httpconnectionpool.h"
#include "fnord-tsdb/TSDBClient.h"
#include <sensord/SensorSampleFeed.h>
#include <sensord/SensorPushServlet.h>

using namespace fnord;

int main(int argc, const char** argv) {
  Application::init();
  Application::logToStderr();

  cli::FlagParser flags;

  flags.defineFlag(
      "http",
      cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8000",
      "Start the http server on this port",
      "<port>");

  flags.defineFlag(
      "tsdb",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "tsdb addr",
      "<host:port>");

  flags.defineFlag(
      "loglevel",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  thread::EventLoop evloop;
  thread::ThreadPool tp(
      std::unique_ptr<ExceptionHandler>(
          new CatchAndLogExceptionHandler("metricd")));

  http::HTTPConnectionPool http(&evloop);
  tsdb::TSDBClient tsdb(
      StringUtil::format("http://$0/tsdb", flags.getString("tsdb")),
      &http);

  /* set up http server */
  http::HTTPRouter http_router;
  http::HTTPServer http_server(&http_router, &evloop);
  http_server.listen(flags.getInt("http"));
  http_server.stats()->exportStats("/metricd/http");

  sensord::SensorSampleFeed sensor_feed;
  metricdb::SensorServlet sensor_servlet(&sensor_feed);
  http_router.addRouteByPrefixMatch("/sensors", &sensor_servlet);

  //stats::StatsHTTPServlet stats_servlet;
  //http_router.addRouteByPrefixMatch("/stats", &stats_servlet);

  evloop.run();
  return 0;
}

<commit_msg>SensorServlet -> SensorPushServlet<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <unistd.h>
#include "fnord-base/application.h"
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/random.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/httpconnectionpool.h"
#include "fnord-tsdb/TSDBClient.h"
#include <sensord/SensorSampleFeed.h>
#include <sensord/SensorPushServlet.h>

using namespace fnord;

int main(int argc, const char** argv) {
  Application::init();
  Application::logToStderr();

  cli::FlagParser flags;

  flags.defineFlag(
      "http",
      cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8000",
      "Start the http server on this port",
      "<port>");

  flags.defineFlag(
      "tsdb",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "tsdb addr",
      "<host:port>");

  flags.defineFlag(
      "loglevel",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  thread::EventLoop evloop;
  thread::ThreadPool tp(
      std::unique_ptr<ExceptionHandler>(
          new CatchAndLogExceptionHandler("metricd")));

  http::HTTPConnectionPool http(&evloop);
  tsdb::TSDBClient tsdb(
      StringUtil::format("http://$0/tsdb", flags.getString("tsdb")),
      &http);

  /* set up http server */
  http::HTTPRouter http_router;
  http::HTTPServer http_server(&http_router, &evloop);
  http_server.listen(flags.getInt("http"));
  http_server.stats()->exportStats("/metricd/http");

  sensord::SensorSampleFeed sensor_feed;
  metricdb::SensorPushServlet sensor_servlet(&sensor_feed);
  http_router.addRouteByPrefixMatch("/sensors", &sensor_servlet);

  //stats::StatsHTTPServlet stats_servlet;
  //http_router.addRouteByPrefixMatch("/stats", &stats_servlet);

  evloop.run();
  return 0;
}

<|endoftext|>


<commit_before>#include "path/ASPC.h"

using namespace std;

namespace chr
{
  namespace path
  {
    array<float, 256> ASPC::randomBase;
    bool ASPC::randomBaseGenerated = false;

    ASPC::ASPC(vector<glm::vec2> &&polyline)
    :
    polyline(polyline)
    {}

    void ASPC::begin()
    {
      polyline.clear();

      if (!randomBaseGenerated)
      {
        srand(1);

        for (int i = 0; i < randomBase.size(); i++)
        {
          randomBase[i] = rand() / float(RAND_MAX);
        }

        randomBaseGenerated = true;
      }

      randomIndex = 0;
    }

    float ASPC::nextRandom()
    {
      return randomBase[(randomIndex++) % randomBase.size()];
    }

    void ASPC::segment(const glm::vec2 &p0, const glm::vec2 &p1, const glm::vec2 &p2)
    {
      in[0] = p0;
      in[1] = p1;
      in[2] = p2;

      float pt = 0;
      auto p = gamma(pt, in.data());

      float qt = 1;
      auto q = gamma(qt, in.data());

      sample(pt, p, qt, q);
    }

    void ASPC::segment(const glm::vec2 &p0, const glm::vec2 &p1, const glm::vec2 &p2, const glm::vec2 &p3)
    {
      in[0] = p0;
      in[1] = p1;
      in[2] = p2;
      in[3] = p3;

      float pt = 0;
      auto p = gamma(pt, in.data());

      float qt = 1;
      auto q = gamma(qt, in.data());

      sample(pt, p, qt, q);
    }

    void ASPC::sample(float t0, const glm::vec2 &p0, float t1, const glm::vec2 &p1)
    {
      float t = 0.45f + 0.1f * nextRandom();
      float rt = t0 + t * (t1 - t0);
      auto r = gamma(rt, in.data());

      float cross = (p0.x - r.x) * (p1.y - r.y) - (p1.x - r.x) * (p0.y - r.y);

      if (cross * cross < samplingTolerance)
      {
        polyline.push_back(p0);
      }
      else
      {
        sample(t0, p0, rt, r);
        sample(rt, r, t1, p1);
      }
    }
  }
}
<commit_msg>FIXING INCLUDES FOR EMSCRIPTEN<commit_after>#include "path/ASPC.h"

#include <cstdlib>

using namespace std;

namespace chr
{
  namespace path
  {
    array<float, 256> ASPC::randomBase;
    bool ASPC::randomBaseGenerated = false;

    ASPC::ASPC(vector<glm::vec2> &&polyline)
    :
    polyline(polyline)
    {}

    void ASPC::begin()
    {
      polyline.clear();

      if (!randomBaseGenerated)
      {
        srand(1);

        for (int i = 0; i < randomBase.size(); i++)
        {
          randomBase[i] = rand() / float(RAND_MAX);
        }

        randomBaseGenerated = true;
      }

      randomIndex = 0;
    }

    float ASPC::nextRandom()
    {
      return randomBase[(randomIndex++) % randomBase.size()];
    }

    void ASPC::segment(const glm::vec2 &p0, const glm::vec2 &p1, const glm::vec2 &p2)
    {
      in[0] = p0;
      in[1] = p1;
      in[2] = p2;

      float pt = 0;
      auto p = gamma(pt, in.data());

      float qt = 1;
      auto q = gamma(qt, in.data());

      sample(pt, p, qt, q);
    }

    void ASPC::segment(const glm::vec2 &p0, const glm::vec2 &p1, const glm::vec2 &p2, const glm::vec2 &p3)
    {
      in[0] = p0;
      in[1] = p1;
      in[2] = p2;
      in[3] = p3;

      float pt = 0;
      auto p = gamma(pt, in.data());

      float qt = 1;
      auto q = gamma(qt, in.data());

      sample(pt, p, qt, q);
    }

    void ASPC::sample(float t0, const glm::vec2 &p0, float t1, const glm::vec2 &p1)
    {
      float t = 0.45f + 0.1f * nextRandom();
      float rt = t0 + t * (t1 - t0);
      auto r = gamma(rt, in.data());

      float cross = (p0.x - r.x) * (p1.y - r.y) - (p1.x - r.x) * (p0.y - r.y);

      if (cross * cross < samplingTolerance)
      {
        polyline.push_back(p0);
      }
      else
      {
        sample(t0, p0, rt, r);
        sample(rt, r, t1, p1);
      }
    }
  }
}
<|endoftext|>


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

#include <gdk/gdkkeysyms.h>

#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/gfx/rect.h"
#include "ui/views/focus/accelerator_handler.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"

namespace views {

class AcceleratorHandlerGtkTest
    : public testing::Test,
      public WidgetDelegate,
      public ui::AcceleratorTarget {
 public:
  AcceleratorHandlerGtkTest()
      : kMenuAccelerator(ui::VKEY_MENU, false, false, false),
        kHomepageAccelerator(ui::VKEY_HOME, false, false, true),
        content_view_(NULL) {
  }

  virtual void SetUp() {
    window_ = Widget::CreateWindowWithBounds(this, gfx::Rect(0, 0, 500, 500));
    window_->Show();
    FocusManager* focus_manager = window_->GetFocusManager();
    focus_manager->RegisterAccelerator(kMenuAccelerator, this);
    focus_manager->RegisterAccelerator(kHomepageAccelerator, this);
    menu_pressed_ = false;
    home_pressed_ = false;
  }

  virtual void TearDown() {
    window_->Close();

    // Flush the message loop to make application verifiers happy.
    message_loop_.RunAllPending();
  }

  GdkEventKey CreateKeyEvent(GdkEventType type, guint keyval, guint state) {
    GdkEventKey evt;
    memset(&evt, 0, sizeof(evt));
    evt.type = type;
    evt.keyval = keyval;
    // The keyval won't be a "correct" hardware keycode for any real hardware,
    // but the code should never depend on exact hardware keycodes, just the
    // fact that the code for presses and releases of the same key match.
    evt.hardware_keycode = keyval;
    evt.state = state;
    GtkWidget* widget = GTK_WIDGET(window_->GetNativeWindow());
    evt.window = widget->window;
    return evt;
  }

  // AcceleratorTarget implementation.
  virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) {
    if (accelerator == kMenuAccelerator)
      menu_pressed_ = true;
    else if (accelerator == kHomepageAccelerator)
      home_pressed_ = true;
    return true;
  }
  virtual bool CanHandleAccelerators() const {
    return true;
  }

  // WidgetDelegate Implementation.
  virtual View* GetContentsView() {
    if (!content_view_)
      content_view_ = new View();
    return content_view_;
  }
  virtual const views::Widget* GetWidget() const {
    return content_view_->GetWidget();
  }
  virtual views::Widget* GetWidget() {
    return content_view_->GetWidget();
  }

  virtual void InitContentView() {
  }

 protected:
  bool menu_pressed_;
  bool home_pressed_;

 private:
  ui::Accelerator kMenuAccelerator;
  ui::Accelerator kHomepageAccelerator;
  Widget* window_;
  View* content_view_;
  MessageLoopForUI message_loop_;
  DISALLOW_COPY_AND_ASSIGN(AcceleratorHandlerGtkTest);
};

// Test that the homepage accelerator (Alt+Home) is activated on key down
// and that the menu accelerator (Alt) is never activated.
TEST_F(AcceleratorHandlerGtkTest, TestHomepageAccelerator) {
  AcceleratorHandler handler;
  GdkEventKey evt;

  ASSERT_FALSE(menu_pressed_);
  ASSERT_FALSE(home_pressed_);

  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);
  ASSERT_FALSE(home_pressed_);

  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Home, GDK_MOD1_MASK);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);
  ASSERT_TRUE(home_pressed_);

  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Home, GDK_MOD1_MASK);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));
  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);
  ASSERT_TRUE(home_pressed_);
}

// Test that the menu accelerator is activated on key up and not key down.
TEST_F(AcceleratorHandlerGtkTest, TestMenuAccelerator) {
  AcceleratorHandler handler;
  GdkEventKey evt;

  ASSERT_FALSE(menu_pressed_);

  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);

  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_TRUE(menu_pressed_);
}

// Test that the menu accelerator isn't confused by the interaction of the
// Alt and Shift keys. Try the following sequence on Linux:
//   Press Alt
//   Press Shift
//   Release Alt
//   Release Shift
// The key codes for pressing Alt and releasing Alt are different! This
// caused a bug in a previous version of the code, which is now fixed by
// keeping track of hardware keycodes, which are consistent.
TEST_F(AcceleratorHandlerGtkTest, TestAltShiftInteraction) {
  AcceleratorHandler handler;
  GdkEventKey evt;

  ASSERT_FALSE(menu_pressed_);

  // Press Shift.
  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Shift_L, 0);
  evt.hardware_keycode = 0x32;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));
  // Press Alt - but GDK calls this Meta when Shift is also down.
  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Meta_L, 0);
  evt.hardware_keycode = 0x40;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  // Release Shift.
  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Shift_L, 0);
  evt.hardware_keycode = 0x32;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));
  // Release Alt - with Shift not down, the keyval is now Alt, but
  // the hardware keycode is unchanged.
  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0);
  evt.hardware_keycode = 0x40;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);

  // Press Alt by itself.
  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0);
  evt.hardware_keycode = 0x40;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  // This line fails if we don't keep track of hardware keycodes.
  ASSERT_FALSE(menu_pressed_);

  // Release Alt - now this should trigger the menu shortcut.
  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0);
  evt.hardware_keycode = 0x40;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_TRUE(menu_pressed_);
}

}  // namespace views
<commit_msg>Fix build.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gdk/gdkkeysyms.h>

#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/gfx/rect.h"
#include "ui/views/focus/accelerator_handler.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"

namespace views {

class AcceleratorHandlerGtkTest
    : public testing::Test,
      public WidgetDelegate,
      public ui::AcceleratorTarget {
 public:
  AcceleratorHandlerGtkTest()
      : kMenuAccelerator(ui::VKEY_MENU, false, false, false),
        kHomepageAccelerator(ui::VKEY_HOME, false, false, true),
        content_view_(NULL) {
  }

  virtual void SetUp() {
    window_ = Widget::CreateWindowWithBounds(this, gfx::Rect(0, 0, 500, 500));
    window_->Show();
    FocusManager* focus_manager = window_->GetFocusManager();
    focus_manager->RegisterAccelerator(
        kMenuAccelerator, ui::AcceleratorManager::kNormalPriority, this);
    focus_manager->RegisterAccelerator(
        kHomepageAccelerator, ui::AcceleratorManager::kNormalPriority, this);
    menu_pressed_ = false;
    home_pressed_ = false;
  }

  virtual void TearDown() {
    window_->Close();

    // Flush the message loop to make application verifiers happy.
    message_loop_.RunAllPending();
  }

  GdkEventKey CreateKeyEvent(GdkEventType type, guint keyval, guint state) {
    GdkEventKey evt;
    memset(&evt, 0, sizeof(evt));
    evt.type = type;
    evt.keyval = keyval;
    // The keyval won't be a "correct" hardware keycode for any real hardware,
    // but the code should never depend on exact hardware keycodes, just the
    // fact that the code for presses and releases of the same key match.
    evt.hardware_keycode = keyval;
    evt.state = state;
    GtkWidget* widget = GTK_WIDGET(window_->GetNativeWindow());
    evt.window = widget->window;
    return evt;
  }

  // AcceleratorTarget implementation.
  virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) {
    if (accelerator == kMenuAccelerator)
      menu_pressed_ = true;
    else if (accelerator == kHomepageAccelerator)
      home_pressed_ = true;
    return true;
  }
  virtual bool CanHandleAccelerators() const {
    return true;
  }

  // WidgetDelegate Implementation.
  virtual View* GetContentsView() {
    if (!content_view_)
      content_view_ = new View();
    return content_view_;
  }
  virtual const views::Widget* GetWidget() const {
    return content_view_->GetWidget();
  }
  virtual views::Widget* GetWidget() {
    return content_view_->GetWidget();
  }

  virtual void InitContentView() {
  }

 protected:
  bool menu_pressed_;
  bool home_pressed_;

 private:
  ui::Accelerator kMenuAccelerator;
  ui::Accelerator kHomepageAccelerator;
  Widget* window_;
  View* content_view_;
  MessageLoopForUI message_loop_;
  DISALLOW_COPY_AND_ASSIGN(AcceleratorHandlerGtkTest);
};

// Test that the homepage accelerator (Alt+Home) is activated on key down
// and that the menu accelerator (Alt) is never activated.
TEST_F(AcceleratorHandlerGtkTest, TestHomepageAccelerator) {
  AcceleratorHandler handler;
  GdkEventKey evt;

  ASSERT_FALSE(menu_pressed_);
  ASSERT_FALSE(home_pressed_);

  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);
  ASSERT_FALSE(home_pressed_);

  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Home, GDK_MOD1_MASK);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);
  ASSERT_TRUE(home_pressed_);

  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Home, GDK_MOD1_MASK);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));
  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);
  ASSERT_TRUE(home_pressed_);
}

// Test that the menu accelerator is activated on key up and not key down.
TEST_F(AcceleratorHandlerGtkTest, TestMenuAccelerator) {
  AcceleratorHandler handler;
  GdkEventKey evt;

  ASSERT_FALSE(menu_pressed_);

  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);

  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0);
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_TRUE(menu_pressed_);
}

// Test that the menu accelerator isn't confused by the interaction of the
// Alt and Shift keys. Try the following sequence on Linux:
//   Press Alt
//   Press Shift
//   Release Alt
//   Release Shift
// The key codes for pressing Alt and releasing Alt are different! This
// caused a bug in a previous version of the code, which is now fixed by
// keeping track of hardware keycodes, which are consistent.
TEST_F(AcceleratorHandlerGtkTest, TestAltShiftInteraction) {
  AcceleratorHandler handler;
  GdkEventKey evt;

  ASSERT_FALSE(menu_pressed_);

  // Press Shift.
  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Shift_L, 0);
  evt.hardware_keycode = 0x32;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));
  // Press Alt - but GDK calls this Meta when Shift is also down.
  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Meta_L, 0);
  evt.hardware_keycode = 0x40;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  // Release Shift.
  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Shift_L, 0);
  evt.hardware_keycode = 0x32;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));
  // Release Alt - with Shift not down, the keyval is now Alt, but
  // the hardware keycode is unchanged.
  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0);
  evt.hardware_keycode = 0x40;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_FALSE(menu_pressed_);

  // Press Alt by itself.
  evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0);
  evt.hardware_keycode = 0x40;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  // This line fails if we don't keep track of hardware keycodes.
  ASSERT_FALSE(menu_pressed_);

  // Release Alt - now this should trigger the menu shortcut.
  evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0);
  evt.hardware_keycode = 0x40;
  EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt)));

  ASSERT_TRUE(menu_pressed_);
}

}  // namespace views
<|endoftext|>


<commit_before>#include "view.h"
#include "util/tileID.h"
#include "platform.h"
#include "glm/gtx/string_cast.hpp"

const int View::s_maxZoom; // Create a stack reference to the static member variable

View::View(int _width, int _height, ProjectionType _projType) {
    //Set the map projection for the view module to use.
    setMapProjection(_projType);

    // Set up projection matrix based on input width and height with an arbitrary zoom
    setSize(_width, _height);
    setZoom(16); // Arbitrary zoom for testing

    // Set up view matrix
    m_pos = glm::dvec3(0, 0, 1000); // Start at 0 to begin
    glm::dvec3 direction = glm::dvec3(0, 0, -1); // Look straight down
    glm::dvec3 up = glm::dvec3(0, 1, 0); // Y-axis is 'up'
    m_view = glm::lookAt(m_pos, m_pos + direction, up);
}

void View::setMapProjection(ProjectionType _projType) {
    switch(_projType) {
        case ProjectionType::mercator:
            m_projection.reset(new MercatorProjection());
            break;
        default:
            logMsg("Error: not a valid map projection specified.\n Setting map projection to mercator by default");
            m_projection.reset(new MercatorProjection());
            break;
    }
    m_dirty = true;
}

const MapProjection& View::getMapProjection() {
    return *m_projection.get();
}

void View::setSize(int _width, int _height) {

    m_vpWidth = _width;
    m_vpHeight = _height;
    m_aspect = (float)_width / (float)_height;
    setZoom(m_zoom);
    m_dirty = true;

}

void View::setPosition(double _x, double _y) {

    translate(_x - m_pos.x, _y - m_pos.y);
    m_dirty = true;

}

void View::translate(double _dx, double _dy) {

    m_pos.x += _dx;
    m_pos.y += _dy;
    m_view = glm::lookAt(m_pos, m_pos + glm::dvec3(0, 0, -1), glm::dvec3(0, 1, 0));
    m_dirty = true;

}

void View::zoom(int _dz) {
    setZoom(m_zoom + _dz);
}

void View::setZoom(int _z) {

    // ensure zoom value is allowed
    glm::clamp(_z, 0, s_maxZoom);

    m_zoom = _z;

    // find dimensions of tiles in world space at new zoom level
    float tileSize = 2 * MapProjection::HALF_CIRCUMFERENCE * pow(2, -m_zoom);

    // viewport height in world space is such that each tile is 256 px square in screen space
    m_height = (float)m_vpHeight / (float)256.0 * tileSize;
    m_width = m_height * m_aspect;

    // set vertical field-of-view to 90 deg
    double fovy = PI * 0.5;

    // set camera z to produce desired viewable area
    m_pos.z = m_height * 0.5 / tan(fovy * 0.5);

    // set near clipping distance as a function of camera z
    double near = m_pos.z / 50.0;

    // update view and projection matrices
    m_view = glm::lookAt(m_pos, m_pos + glm::dvec3(0, 0, -1), glm::dvec3(0, 1, 0));
    m_proj = glm::perspective(fovy, m_aspect, near, m_pos.z + 1.0);

    m_dirty = true;

}

const glm::dmat4 View::getViewProjectionMatrix() const {
    return m_proj * m_view;
}

glm::dmat2 View::getBoundsRect() const {

    double hw = m_width * 0.5;
    double hh = m_height * 0.5;
    return glm::dmat2(m_pos.x - hw, m_pos.y - hh, m_pos.x + hw, m_pos.y + hh);

}

const std::set<TileID>& View::getVisibleTiles() {

    if (!m_dirty) {
        return m_visibleTiles;
    }

    m_visibleTiles.clear();

    float tileSize = 2 * MapProjection::HALF_CIRCUMFERENCE * pow(2, -m_zoom);
    float invTileSize = 1.0 / tileSize;

    float vpLeftEdge = m_pos.x - m_width * 0.5 + MapProjection::HALF_CIRCUMFERENCE;
    float vpRightEdge = vpLeftEdge + m_width;
    float vpBottomEdge = -m_pos.y - m_height * 0.5 + MapProjection::HALF_CIRCUMFERENCE;
    float vpTopEdge = vpBottomEdge + m_height;

    int tileX = (int) vpLeftEdge * invTileSize;
    int tileY = (int) vpBottomEdge * invTileSize;

    float x = tileX * tileSize;
    float y = tileY * tileSize;

    while (x < vpRightEdge) {

        while (y < vpTopEdge) {

            m_visibleTiles.insert(TileID(tileX, tileY, m_zoom));
            tileY++;
            y += tileSize;

        }

        tileY = (int) vpBottomEdge * invTileSize;
        y = tileY * tileSize;

        tileX++;
        x += tileSize;
    }

    m_dirty = false;

    return m_visibleTiles;

}
<commit_msg>Fix zoom value clamping<commit_after>#include "view.h"
#include "util/tileID.h"
#include "platform.h"
#include "glm/gtx/string_cast.hpp"

const int View::s_maxZoom; // Create a stack reference to the static member variable

View::View(int _width, int _height, ProjectionType _projType) {
    //Set the map projection for the view module to use.
    setMapProjection(_projType);

    // Set up projection matrix based on input width and height with an arbitrary zoom
    setSize(_width, _height);
    setZoom(16); // Arbitrary zoom for testing

    // Set up view matrix
    m_pos = glm::dvec3(0, 0, 1000); // Start at 0 to begin
    glm::dvec3 direction = glm::dvec3(0, 0, -1); // Look straight down
    glm::dvec3 up = glm::dvec3(0, 1, 0); // Y-axis is 'up'
    m_view = glm::lookAt(m_pos, m_pos + direction, up);
}

void View::setMapProjection(ProjectionType _projType) {
    switch(_projType) {
        case ProjectionType::mercator:
            m_projection.reset(new MercatorProjection());
            break;
        default:
            logMsg("Error: not a valid map projection specified.\n Setting map projection to mercator by default");
            m_projection.reset(new MercatorProjection());
            break;
    }
    m_dirty = true;
}

const MapProjection& View::getMapProjection() {
    return *m_projection.get();
}

void View::setSize(int _width, int _height) {

    m_vpWidth = _width;
    m_vpHeight = _height;
    m_aspect = (float)_width / (float)_height;
    setZoom(m_zoom);
    m_dirty = true;

}

void View::setPosition(double _x, double _y) {

    translate(_x - m_pos.x, _y - m_pos.y);
    m_dirty = true;

}

void View::translate(double _dx, double _dy) {

    m_pos.x += _dx;
    m_pos.y += _dy;
    m_view = glm::lookAt(m_pos, m_pos + glm::dvec3(0, 0, -1), glm::dvec3(0, 1, 0));
    m_dirty = true;

}

void View::zoom(int _dz) {
    setZoom(m_zoom + _dz);
}

void View::setZoom(int _z) {

    // ensure zoom value is allowed
    m_zoom = glm::clamp(_z, 0, s_maxZoom);

    // find dimensions of tiles in world space at new zoom level
    float tileSize = 2 * MapProjection::HALF_CIRCUMFERENCE * pow(2, -m_zoom);

    // viewport height in world space is such that each tile is 256 px square in screen space
    m_height = (float)m_vpHeight / (float)256.0 * tileSize;
    m_width = m_height * m_aspect;

    // set vertical field-of-view to 90 deg
    double fovy = PI * 0.5;

    // set camera z to produce desired viewable area
    m_pos.z = m_height * 0.5 / tan(fovy * 0.5);

    // set near clipping distance as a function of camera z
    double near = m_pos.z / 50.0;

    // update view and projection matrices
    m_view = glm::lookAt(m_pos, m_pos + glm::dvec3(0, 0, -1), glm::dvec3(0, 1, 0));
    m_proj = glm::perspective(fovy, m_aspect, near, m_pos.z + 1.0);

    m_dirty = true;

}

const glm::dmat4 View::getViewProjectionMatrix() const {
    return m_proj * m_view;
}

glm::dmat2 View::getBoundsRect() const {

    double hw = m_width * 0.5;
    double hh = m_height * 0.5;
    return glm::dmat2(m_pos.x - hw, m_pos.y - hh, m_pos.x + hw, m_pos.y + hh);

}

const std::set<TileID>& View::getVisibleTiles() {

    if (!m_dirty) {
        return m_visibleTiles;
    }

    m_visibleTiles.clear();

    float tileSize = 2 * MapProjection::HALF_CIRCUMFERENCE * pow(2, -m_zoom);
    float invTileSize = 1.0 / tileSize;

    float vpLeftEdge = m_pos.x - m_width * 0.5 + MapProjection::HALF_CIRCUMFERENCE;
    float vpRightEdge = vpLeftEdge + m_width;
    float vpBottomEdge = -m_pos.y - m_height * 0.5 + MapProjection::HALF_CIRCUMFERENCE;
    float vpTopEdge = vpBottomEdge + m_height;

    int tileX = (int) vpLeftEdge * invTileSize;
    int tileY = (int) vpBottomEdge * invTileSize;

    float x = tileX * tileSize;
    float y = tileY * tileSize;

    while (x < vpRightEdge) {

        while (y < vpTopEdge) {

            m_visibleTiles.insert(TileID(tileX, tileY, m_zoom));
            tileY++;
            y += tileSize;

        }

        tileY = (int) vpBottomEdge * invTileSize;
        y = tileY * tileSize;

        tileX++;
        x += tileSize;
    }

    m_dirty = false;

    return m_visibleTiles;

}
<|endoftext|>