<commit_before>/*
 * arcball.cpp
 *
 * Created on: 10.05.2012
 * @author Ralph Schurade
 */
#include "arcball.h"

#include "../../data/models.h"

#include <QtDebug>

#include <math.h>

ArcBall::ArcBall( int width, int height ) :
    CameraBase( width, height ),
    Epsilon( 0.00001 ),
    m_moveX( 0 ),
    m_moveY( 0 ),
    m_oldMoveX( 0 ),
    m_oldMoveY( 0 ),
    m_midClickX( 0 ),
    m_midClickY( 0 )
{

    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();
}

ArcBall::~ArcBall()
{
}

// maps the specified mouse position to the sphere defined
// with center and radius. the resulting vector lies on the
// surface of the sphere.
QVector3D ArcBall::map_sphere( int x, int y )
{
    float tmpx = ( x * m_adjust_width ) - 1.0;
    float tmpy = 1.0 - ( y * m_adjust_height );

    float length = ( tmpx * tmpx ) + ( tmpy * tmpy );

    QVector3D bm;
    if ( length > 1.0 )
    {
        float norm = 1.0 / sqrt( length );
        bm.setX( tmpx * norm );
        bm.setY( tmpy * norm );
        bm.setZ( 0.0 );
    }
    else
    {
        bm.setX( tmpx );
        bm.setY( tmpy );
        bm.setZ( sqrt( 1.0 - length ) );
    }
    return bm;
}

/// sets the current position and calculates the current
/// rotation matrix.
void ArcBall::drag( int x, int y )
{
    QVector3D v_to = map_sphere( x, y );
    QVector3D perp = QVector3D::crossProduct( v_from, v_to);

    if ( perp.length() > Epsilon )
    {
        q_current_rotation.setX( perp.x() );
        q_current_rotation.setY( perp.y() );
        q_current_rotation.setZ( perp.z() );;
        q_current_rotation.setScalar( ( v_from.x() * v_to.x() ) + ( v_from.y() * v_to.y() ) + ( v_from.z() * v_to.z() ) );
    }
    else
    {
        q_current_rotation.setX( 0.0 );
        q_current_rotation.setY( 0.0 );
        q_current_rotation.setZ( 0.0 );
        q_current_rotation.setScalar( 0.0 );
    }
    m_currentRot.setToIdentity();
    m_currentRot.rotate( q_current_rotation );
    m_currentRot = m_currentRot * m_lastRot ;
}

/// indicates the beginning of the dragging.
void ArcBall::click( int x, int y )
{
    m_lastRot = m_currentRot;
    v_mouse_down.setX( x );
    v_mouse_down.setY( y );
    v_mouse_down.setZ( 0.0 );
    v_from = map_sphere( x, y );
}

void ArcBall::midClick( int x, int y )
{
    m_midClickX = x;
    m_midClickY = y;
    m_oldMoveX = m_moveX;
    m_oldMoveY = m_moveY;
}

void ArcBall::mouseWheel( float step )
{
    if ( m_zoom < 2.0f )
    {
        step /= 2.0;
    }
    m_zoom += step;

    m_zoom = qMax( 1.0f, m_zoom );
}

void ArcBall::midDrag( int x, int y )
{
    m_moveX = ( m_oldMoveX + ( m_midClickX - x ) / 2 );
    m_moveY = ( m_oldMoveY + ( m_midClickY - y ) / 2 );
}

void ArcBall::setRotCenter( float x, float y, float z )
{
    m_rotCenter = QVector3D( -x, -y, -z );
}

void ArcBall::setView( Fn::Orient view )
{
    m_zoom = 1.0;
    m_moveX = 0;
    m_moveY = 0;
    m_oldMoveX = 0;
    m_oldMoveY = 0;
    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();

    QQuaternion rotx( sqrt(0.5), 0, 0, sqrt(0.5) );
    QQuaternion rot_x( -sqrt(0.5), 0, 0, sqrt(0.5) );
    QQuaternion roty( 0, sqrt(0.5), 0, sqrt(0.5) );
    QQuaternion rot_y( 0, -sqrt(0.5), 0, sqrt(0.5) );
    QQuaternion rotz( 0, 0, sqrt(0.5), sqrt(0.5) );
    QQuaternion rot_z( 0, 0, -sqrt(0.5), sqrt(0.5) );

    switch( view )
    {
        case Fn::Orient::NONE:
            break;
        case Fn::Orient::AXIAL:
            break;
        case Fn::Orient::CORONAL:
            m_currentRot.rotate( rotz );
            m_currentRot.rotate( rotx );
            m_currentRot.rotate( rotx );
            break;
        case Fn::Orient::SAGITTAL:
            m_currentRot.rotate( rot_x );
            m_currentRot.rotate( rot_y );
            break;
        case Fn::Orient::AXIAL2:
            m_currentRot.rotate( rot_y );
            m_currentRot.rotate( roty );
            break;
        case Fn::Orient::CORONAL2:
            m_currentRot.rotate( rotz );
            break;
        case Fn::Orient::SAGITTAL2:
            m_currentRot.rotate( rotx );
            m_currentRot.rotate( roty );
            break;
    }
}

/// returns the rotation matrix to be used directly
QMatrix4x4 ArcBall::getMVMat()
{
    QMatrix4x4 mv;
    mv.setToIdentity();

    mv = m_currentRot * mv ;

    float dist = Models::getGlobal( Fn::Property::G_ARCBALL_DISTANCE ).toFloat();

    QVector3D halfMove( -m_moveX, m_moveY, -dist );
    QMatrix4x4 tmp;
    tmp.setToIdentity();
    tmp.translate( halfMove );
    tmp = tmp * m_currentRot;

    mv = mv + tmp;

    mv.translate( m_rotCenter );

    return mv;
}

float ArcBall::getMoveX()
{
    return m_moveX;
}

float ArcBall::getMoveY()
{
    return m_moveY;
}

void ArcBall::setMoveX( float x )
{
    m_moveX = x;
}

void ArcBall::setMoveY( float y )
{
    m_moveY = y;
}

QList<QVariant> ArcBall::getState()
{
    QList<QVariant> state;
    state.push_back( m_currentRot );
    state.push_back( m_lastRot );
    state.push_back( m_moveX );
    state.push_back( m_moveY );
    state.push_back( m_oldMoveX );
    state.push_back( m_oldMoveY );
    state.push_back( m_midClickX );
    state.push_back( m_midClickY );
    state.push_back( m_zoom );
    state.push_back( m_rotCenter );
    state.push_back( q_current_rotation );
    return state;
}

void ArcBall::setState( QList<QVariant> state )
{
    m_currentRot = state[0].value<QMatrix4x4>();
    m_lastRot = state[1].value<QMatrix4x4>();
    m_moveX = state[2].toInt();
    m_moveY = state[3].toInt();
    m_oldMoveX = state[4].toInt();
    m_oldMoveY = state[5].toInt();
    m_midClickX = state[6].toInt();
    m_midClickY = state[7].toInt();
    m_zoom = state[8].toFloat();
    m_rotCenter = state[9].value<QVector3D>();
    q_current_rotation = state[10].value<QQuaternion>();
}

QQuaternion ArcBall::getRotation()
{
    return mat2quat( m_currentRot );
}

void ArcBall::setRotation( QQuaternion quat )
{
    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();
    m_currentRot.rotate( quat );
}

inline float SIGN(float x) {return (x >= 0.0f) ? +1.0f : -1.0f;}
inline float NORM(float a, float b, float c, float d) {return sqrt(a * a + b * b + c * c + d * d);}

QQuaternion ArcBall::mat2quat( QMatrix4x4 &mat )
{
    double r11 = mat( 0, 0 );
    double r12 = mat( 0, 1 );
    double r13 = mat( 0, 2 );
    double r21 = mat( 1, 0 );
    double r22 = mat( 1, 1 );
    double r23 = mat( 1, 2 );
    double r31 = mat( 2, 0 );
    double r32 = mat( 2, 1 );
    double r33 = mat( 2, 2 );

    double q0 = ( r11 + r22 + r33 + 1.0f ) / 4.0f;
    double q1 = ( r11 - r22 - r33 + 1.0f ) / 4.0f;
    double q2 = ( -r11 + r22 - r33 + 1.0f ) / 4.0f;
    double q3 = ( -r11 - r22 + r33 + 1.0f ) / 4.0f;

    if ( q0 < 0.0f )
        q0 = 0.0f;
    if ( q1 < 0.0f )
        q1 = 0.0f;
    if ( q2 < 0.0f )
        q2 = 0.0f;
    if ( q3 < 0.0f )
        q3 = 0.0f;
    q0 = sqrt( q0 );
    q1 = sqrt( q1 );
    q2 = sqrt( q2 );
    q3 = sqrt( q3 );
    if ( q0 >= q1 && q0 >= q2 && q0 >= q3 )
    {
        q0 *= +1.0f;
        q1 *= SIGN( r32 - r23 );
        q2 *= SIGN( r13 - r31 );
        q3 *= SIGN( r21 - r12 );
    }
    else if ( q1 >= q0 && q1 >= q2 && q1 >= q3 )
    {
        q0 *= SIGN( r32 - r23 );
        q1 *= +1.0f;
        q2 *= SIGN( r21 + r12 );
        q3 *= SIGN( r13 + r31 );
    }
    else if ( q2 >= q0 && q2 >= q1 && q2 >= q3 )
    {
        q0 *= SIGN( r13 - r31 );
        q1 *= SIGN( r21 + r12 );
        q2 *= +1.0f;
        q3 *= SIGN( r32 + r23 );
    }
    else if ( q3 >= q0 && q3 >= q1 && q3 >= q2 )
    {
        q0 *= SIGN( r21 - r12 );
        q1 *= SIGN( r31 + r13 );
        q2 *= SIGN( r32 + r23 );
        q3 *= +1.0f;
    }
    else
    {
        printf( "coding error\n" );
    }
    double r = NORM( q0, q1, q2, q3 );
    q0 /= r;
    q1 /= r;
    q2 /= r;
    q3 /= r;

    return QQuaternion( q0, q1, q2, q3 );
}

QVector3D ArcBall::getRotCenter()
{
    return m_rotCenter;
}
<commit_msg>middle mouse dragging now works properly with zoom levels<commit_after>/*
 * arcball.cpp
 *
 * Created on: 10.05.2012
 * @author Ralph Schurade
 */
#include "arcball.h"

#include "../../data/models.h"

#include <QtDebug>

#include <math.h>

ArcBall::ArcBall( int width, int height ) :
    CameraBase( width, height ),
    Epsilon( 0.00001 ),
    m_moveX( 0 ),
    m_moveY( 0 ),
    m_oldMoveX( 0 ),
    m_oldMoveY( 0 ),
    m_midClickX( 0 ),
    m_midClickY( 0 )
{

    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();
}

ArcBall::~ArcBall()
{
}

// maps the specified mouse position to the sphere defined
// with center and radius. the resulting vector lies on the
// surface of the sphere.
QVector3D ArcBall::map_sphere( int x, int y )
{
    float tmpx = ( x * m_adjust_width ) - 1.0;
    float tmpy = 1.0 - ( y * m_adjust_height );

    float length = ( tmpx * tmpx ) + ( tmpy * tmpy );

    QVector3D bm;
    if ( length > 1.0 )
    {
        float norm = 1.0 / sqrt( length );
        bm.setX( tmpx * norm );
        bm.setY( tmpy * norm );
        bm.setZ( 0.0 );
    }
    else
    {
        bm.setX( tmpx );
        bm.setY( tmpy );
        bm.setZ( sqrt( 1.0 - length ) );
    }
    return bm;
}

/// sets the current position and calculates the current
/// rotation matrix.
void ArcBall::drag( int x, int y )
{
    QVector3D v_to = map_sphere( x, y );
    QVector3D perp = QVector3D::crossProduct( v_from, v_to);

    if ( perp.length() > Epsilon )
    {
        q_current_rotation.setX( perp.x() );
        q_current_rotation.setY( perp.y() );
        q_current_rotation.setZ( perp.z() );;
        q_current_rotation.setScalar( ( v_from.x() * v_to.x() ) + ( v_from.y() * v_to.y() ) + ( v_from.z() * v_to.z() ) );
    }
    else
    {
        q_current_rotation.setX( 0.0 );
        q_current_rotation.setY( 0.0 );
        q_current_rotation.setZ( 0.0 );
        q_current_rotation.setScalar( 0.0 );
    }
    m_currentRot.setToIdentity();
    m_currentRot.rotate( q_current_rotation );
    m_currentRot = m_currentRot * m_lastRot ;
}

/// indicates the beginning of the dragging.
void ArcBall::click( int x, int y )
{
    m_lastRot = m_currentRot;
    v_mouse_down.setX( x );
    v_mouse_down.setY( y );
    v_mouse_down.setZ( 0.0 );
    v_from = map_sphere( x, y );
}

void ArcBall::midClick( int x, int y )
{
    m_midClickX = x;
    m_midClickY = y;
    m_oldMoveX = m_moveX;
    m_oldMoveY = m_moveY;
}

void ArcBall::mouseWheel( float step )
{
    if ( m_zoom < 2.0f )
    {
        step /= 2.0;
    }
    m_zoom += step;

    m_zoom = qMax( 1.0f, m_zoom );
}

void ArcBall::midDrag( int x, int y )
{
    m_moveX = m_oldMoveX + ( ( m_midClickX - x ) / 2 ) / m_zoom;
    m_moveY = m_oldMoveY + ( ( m_midClickY - y ) / 2 ) / m_zoom;
}

void ArcBall::setRotCenter( float x, float y, float z )
{
    m_rotCenter = QVector3D( -x, -y, -z );
}

void ArcBall::setView( Fn::Orient view )
{
    m_zoom = 1.0;
    m_moveX = 0;
    m_moveY = 0;
    m_oldMoveX = 0;
    m_oldMoveY = 0;
    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();

    QQuaternion rotx( sqrt(0.5), 0, 0, sqrt(0.5) );
    QQuaternion rot_x( -sqrt(0.5), 0, 0, sqrt(0.5) );
    QQuaternion roty( 0, sqrt(0.5), 0, sqrt(0.5) );
    QQuaternion rot_y( 0, -sqrt(0.5), 0, sqrt(0.5) );
    QQuaternion rotz( 0, 0, sqrt(0.5), sqrt(0.5) );
    QQuaternion rot_z( 0, 0, -sqrt(0.5), sqrt(0.5) );

    switch( view )
    {
        case Fn::Orient::NONE:
            break;
        case Fn::Orient::AXIAL:
            break;
        case Fn::Orient::CORONAL:
            m_currentRot.rotate( rotz );
            m_currentRot.rotate( rotx );
            m_currentRot.rotate( rotx );
            break;
        case Fn::Orient::SAGITTAL:
            m_currentRot.rotate( rot_x );
            m_currentRot.rotate( rot_y );
            break;
        case Fn::Orient::AXIAL2:
            m_currentRot.rotate( rot_y );
            m_currentRot.rotate( roty );
            break;
        case Fn::Orient::CORONAL2:
            m_currentRot.rotate( rotz );
            break;
        case Fn::Orient::SAGITTAL2:
            m_currentRot.rotate( rotx );
            m_currentRot.rotate( roty );
            break;
    }
}

/// returns the rotation matrix to be used directly
QMatrix4x4 ArcBall::getMVMat()
{
    QMatrix4x4 mv;
    mv.setToIdentity();

    mv = m_currentRot * mv ;

    float dist = Models::getGlobal( Fn::Property::G_ARCBALL_DISTANCE ).toFloat();

    QVector3D halfMove( -m_moveX, m_moveY, -dist );
    QMatrix4x4 tmp;
    tmp.setToIdentity();
    tmp.translate( halfMove );
    tmp = tmp * m_currentRot;

    mv = mv + tmp;

    mv.translate( m_rotCenter );

    return mv;
}

float ArcBall::getMoveX()
{
    return m_moveX;
}

float ArcBall::getMoveY()
{
    return m_moveY;
}

void ArcBall::setMoveX( float x )
{
    m_moveX = x;
}

void ArcBall::setMoveY( float y )
{
    m_moveY = y;
}

QList<QVariant> ArcBall::getState()
{
    QList<QVariant> state;
    state.push_back( m_currentRot );
    state.push_back( m_lastRot );
    state.push_back( m_moveX );
    state.push_back( m_moveY );
    state.push_back( m_oldMoveX );
    state.push_back( m_oldMoveY );
    state.push_back( m_midClickX );
    state.push_back( m_midClickY );
    state.push_back( m_zoom );
    state.push_back( m_rotCenter );
    state.push_back( q_current_rotation );
    return state;
}

void ArcBall::setState( QList<QVariant> state )
{
    m_currentRot = state[0].value<QMatrix4x4>();
    m_lastRot = state[1].value<QMatrix4x4>();
    m_moveX = state[2].toInt();
    m_moveY = state[3].toInt();
    m_oldMoveX = state[4].toInt();
    m_oldMoveY = state[5].toInt();
    m_midClickX = state[6].toInt();
    m_midClickY = state[7].toInt();
    m_zoom = state[8].toFloat();
    m_rotCenter = state[9].value<QVector3D>();
    q_current_rotation = state[10].value<QQuaternion>();
}

QQuaternion ArcBall::getRotation()
{
    return mat2quat( m_currentRot );
}

void ArcBall::setRotation( QQuaternion quat )
{
    m_currentRot.setToIdentity();
    m_lastRot.setToIdentity();
    m_currentRot.rotate( quat );
}

inline float SIGN(float x) {return (x >= 0.0f) ? +1.0f : -1.0f;}
inline float NORM(float a, float b, float c, float d) {return sqrt(a * a + b * b + c * c + d * d);}

QQuaternion ArcBall::mat2quat( QMatrix4x4 &mat )
{
    double r11 = mat( 0, 0 );
    double r12 = mat( 0, 1 );
    double r13 = mat( 0, 2 );
    double r21 = mat( 1, 0 );
    double r22 = mat( 1, 1 );
    double r23 = mat( 1, 2 );
    double r31 = mat( 2, 0 );
    double r32 = mat( 2, 1 );
    double r33 = mat( 2, 2 );

    double q0 = ( r11 + r22 + r33 + 1.0f ) / 4.0f;
    double q1 = ( r11 - r22 - r33 + 1.0f ) / 4.0f;
    double q2 = ( -r11 + r22 - r33 + 1.0f ) / 4.0f;
    double q3 = ( -r11 - r22 + r33 + 1.0f ) / 4.0f;

    if ( q0 < 0.0f )
        q0 = 0.0f;
    if ( q1 < 0.0f )
        q1 = 0.0f;
    if ( q2 < 0.0f )
        q2 = 0.0f;
    if ( q3 < 0.0f )
        q3 = 0.0f;
    q0 = sqrt( q0 );
    q1 = sqrt( q1 );
    q2 = sqrt( q2 );
    q3 = sqrt( q3 );
    if ( q0 >= q1 && q0 >= q2 && q0 >= q3 )
    {
        q0 *= +1.0f;
        q1 *= SIGN( r32 - r23 );
        q2 *= SIGN( r13 - r31 );
        q3 *= SIGN( r21 - r12 );
    }
    else if ( q1 >= q0 && q1 >= q2 && q1 >= q3 )
    {
        q0 *= SIGN( r32 - r23 );
        q1 *= +1.0f;
        q2 *= SIGN( r21 + r12 );
        q3 *= SIGN( r13 + r31 );
    }
    else if ( q2 >= q0 && q2 >= q1 && q2 >= q3 )
    {
        q0 *= SIGN( r13 - r31 );
        q1 *= SIGN( r21 + r12 );
        q2 *= +1.0f;
        q3 *= SIGN( r32 + r23 );
    }
    else if ( q3 >= q0 && q3 >= q1 && q3 >= q2 )
    {
        q0 *= SIGN( r21 - r12 );
        q1 *= SIGN( r31 + r13 );
        q2 *= SIGN( r32 + r23 );
        q3 *= +1.0f;
    }
    else
    {
        printf( "coding error\n" );
    }
    double r = NORM( q0, q1, q2, q3 );
    q0 /= r;
    q1 /= r;
    q2 /= r;
    q3 /= r;

    return QQuaternion( q0, q1, q2, q3 );
}

QVector3D ArcBall::getRotCenter()
{
    return m_rotCenter;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: LegendHelper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: bm $ $Date: 2004-01-26 09:13:02 $
 *
 *  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: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "LegendHelper.hxx"
#include "macros.hxx"

#ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart2/XChartDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XLEGEND_HPP_
#include <com/sun/star/chart2/XLegend.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

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

//.............................................................................
namespace chart
{
//.............................................................................

// static
rtl::OUString LegendHelper::getIdentifierForLegend()
{
    static rtl::OUString aIdentifier( C2U( "@legend" ) );
    return aIdentifier;
}

// static
uno::Reference< chart2::XLegend > LegendHelper::getLegend(
    const uno::Reference< frame::XModel >& xModel )
{
    uno::Reference< chart2::XLegend > xResult;

    uno::Reference< chart2::XChartDocument > xChartDoc( xModel, uno::UNO_QUERY );
    if( xChartDoc.is())
    {
        try
        {
            uno::Reference< chart2::XDiagram > xDia( xChartDoc->getDiagram());
            if( xDia.is())
                xResult.set( xDia->getLegend() );
        }
        catch( uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }

    }

    return xResult;
}

// static
void LegendHelper::defaultFillEmptyLegend(
    const uno::Reference< chart2::XLegend > & xLegend,
    const uno::Reference< chart2::XDiagram > & xDiagram )
{
    if( xLegend.is() &&
        xDiagram.is() )
    {
        try
        {
            uno::Reference< chart2::XDataSeriesTreeParent > xRoot( xDiagram->getTree());

            uno::Sequence< uno::Reference< chart2::XDataSeriesTreeNode > > aChildren( xRoot->getChildren());
            for( sal_Int32 i = 0; i < aChildren.getLength(); ++i )
            {
                uno::Reference< lang::XServiceInfo > xInfo( aChildren[ i ], uno::UNO_QUERY );
                if( xInfo.is() &&
                    xInfo->supportsService( C2U( "com.sun.star.chart2.ChartTypeGroup" )))
                {
                    uno::Reference< chart2::XLegendEntry > xEntry( xInfo, uno::UNO_QUERY );
                    if( xEntry.is())
                        xLegend->registerEntry( xEntry );
                }
            }
        }
        catch( uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }
    }
}

// static
void LegendHelper::flushLegend( const uno::Reference< chart2::XLegend > & xLegend )
{
    if( xLegend.is())
    {
        uno::Sequence< uno::Reference< chart2::XLegendEntry > > aEntries( xLegend->getEntries());
        for( sal_Int32 i = 0; i < aEntries.getLength(); ++i )
        {
            xLegend->revokeEntry( aEntries[ i ] );
        }
    }
}

//.............................................................................
} //namespace chart
//.............................................................................

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

#ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart2/XChartDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XLEGEND_HPP_
#include <com/sun/star/chart2/XLegend.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

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

//.............................................................................
namespace chart
{
//.............................................................................

// static
rtl::OUString LegendHelper::getIdentifierForLegend()
{
    static rtl::OUString aIdentifier( C2U( "@legend" ) );
    return aIdentifier;
}

// static
uno::Reference< chart2::XLegend > LegendHelper::getLegend(
    const uno::Reference< frame::XModel >& xModel )
{
    uno::Reference< chart2::XLegend > xResult;

    uno::Reference< chart2::XChartDocument > xChartDoc( xModel, uno::UNO_QUERY );
    if( xChartDoc.is())
    {
        try
        {
            uno::Reference< chart2::XDiagram > xDia( xChartDoc->getDiagram());
            if( xDia.is())
                xResult.set( xDia->getLegend() );
        }
        catch( uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }

    }

    return xResult;
}

// static
void LegendHelper::defaultFillEmptyLegend(
    const uno::Reference< chart2::XLegend > & xLegend,
    const uno::Reference< chart2::XDiagram > & xDiagram )
{
    if( xLegend.is() &&
        xDiagram.is() )
    {
        try
        {
            uno::Reference< chart2::XDataSeriesTreeParent > xRoot( xDiagram->getTree());

            uno::Sequence< uno::Reference< chart2::XDataSeriesTreeNode > > aChildren( xRoot->getChildren());
            for( sal_Int32 i = 0; i < aChildren.getLength(); ++i )
            {
                uno::Reference< lang::XServiceInfo > xInfo( aChildren[ i ], uno::UNO_QUERY );
                if( xInfo.is() &&
                    xInfo->supportsService( C2U( "com.sun.star.chart2.ChartTypeGroup" )))
                {
                    uno::Reference< chart2::XLegendEntry > xEntry( xInfo, uno::UNO_QUERY );
                    if( xEntry.is())
                        xLegend->registerEntry( xEntry );
                }
            }
        }
        catch( uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }
    }
}

// static
void LegendHelper::flushLegend( const uno::Reference< chart2::XLegend > & xLegend )
{
    if( xLegend.is())
    {
        uno::Sequence< uno::Reference< chart2::XLegendEntry > > aEntries( xLegend->getEntries());
        for( sal_Int32 i = 0; i < aEntries.getLength(); ++i )
        {
            xLegend->revokeEntry( aEntries[ i ] );
        }
    }
}

//.............................................................................
} //namespace chart
//.............................................................................

<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

#include "cinder/Capture.h"
#include "cinder/gl/Texture.h"
#include "cinder/gl/GlslProg.h"
#include "cinder/Log.h"
#include "cinder/gl/Fbo.h"
#include "cinder/gl/Shader.h"

#include "GridTexture.h"
#include "Landscape.h"
#include "IntroSequence.h"

#include "cinder/MotionManager.h"
#include "cinder/Timeline.h"

using namespace ci;
using namespace ci::app;
using namespace std;

using namespace soso;

struct TouchInfo {
	TouchInfo() = default;
	TouchInfo( uint32_t iId, const vec2 &iStart, const vec2 &iPosition )
	: id( iId ),
		previous( iStart ),
		position( iPosition )
	{}

  uint32_t		id = 0;
  vec2				previous;
  vec2				position;
};

class SelfieSelfieApp : public App {
public:
	void setup() override;
	void update() override;
	void draw() override;

  void touchesBegan( TouchEvent event ) override;
  void touchesMoved( TouchEvent event ) override;
  void touchesEnded( TouchEvent event ) override;

	void updateCamera();
	void showLandscape();

private:
	CameraPersp				camera;
  CaptureRef				capture;

  GridTextureRef		gridTexture;
  Landscape					landscape;
	gl::BatchRef			cameraImage;
	IntroSequence			introduction;

  vector<TouchInfo> touches;
  ci::vec3					cameraOffset;
	float							cameraVelocity = 0.0f;

  bool							drawDebug = false;

	ci::Anim<float>		cameraWeight = 0.0f;
	quat							startOrientation;
};

void SelfieSelfieApp::setup()
{
  CI_LOG_I("Setting up selfie_x_selfie");

  MotionManager::enable();

  GLint size;
  glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
  CI_LOG_I( "Max texture size: " << size );

  auto target = vec3( 5, 0, 0 );
  camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
  camera.setPerspective( 80, getWindowAspectRatio(), 0.1f, 50.0f );
	startOrientation = camera.getOrientation();

  try {
    CI_LOG_I( "Initializing hardware camera." );
    auto front_facing_camera = ([] {
      auto &devices = Capture::getDevices();
      auto first_device = devices.front();
      for( auto device : devices ) {
        if( device->isFrontFacing() ) {
          return device;
        }
      }
      return first_device;
    }());

		#if defined(CINDER_ANDROID)
			capture = Capture::create( 640, 480, front_facing_camera );
		#else
    	capture = Capture::create( 480, 360, front_facing_camera );
    #endif
    capture->start();

    CI_LOG_I( "Creating Grid Texture" );
    gridTexture = make_shared<GridTexture>( ivec2( 320, 240 ), 12 );

    CI_LOG_I( "Setting up landscape geometry." );
    landscape.setup();
    landscape.setTextureUnits( 0, 1 );
    landscape.setGridSize( gridTexture->getGridDimensions() );
  }
  catch( ci::Exception &exc ) {
    CI_LOG_E( "Error using device camera: " << exc.what() );
  }

  auto err = gl::getError();
  if( err ) {
    CI_LOG_E( "Post-Setup gl error: " << gl::getErrorString(err) );
  }

	introduction.setup( getAssetPath( "intro/5" ) );
	introduction.setFinishFn( [this] { showLandscape(); } );
}

void SelfieSelfieApp::touchesBegan( TouchEvent event )
{
  for( auto &t : event.getTouches() ) {
    touches.emplace_back( t.getId(), t.getPos(), t.getPos() );
  }

  if( touches.size() == 4 ) {
    drawDebug = ! drawDebug;
  }
}

void SelfieSelfieApp::touchesMoved( TouchEvent event )
{
  for( auto &t : event.getTouches() ) {
    for( auto &s : touches ) {
      if( s.id == t.getId() ) {
				s.previous = s.position;
        s.position = t.getPos();
      }
    }
  }
}

void SelfieSelfieApp::touchesEnded( TouchEvent event )
{
  touches.erase( std::remove_if( touches.begin(), touches.end(), [&event] (const TouchInfo &s) {
    for( auto &t : event.getTouches() ) {
      if (t.getId() == s.id) {
        return true;
      }
    }
    return false;
  }), touches.end() );
}

void SelfieSelfieApp::showLandscape()
{
	// Enable looking around with the gyro
	timeline().apply( &cameraWeight, 1.0f, 1.33f ).easeFn( EaseInOutCubic() );
}

void SelfieSelfieApp::update()
{
	introduction.update();
	updateCamera();

  if( capture && capture->checkNewFrame() ) {
    gridTexture->update( *capture->getSurface() );

    auto err = gl::getError();
    if( err ) {
      CI_LOG_E( "Texture copy gl error: " << gl::getErrorString(err) );
    }
  }
}

void SelfieSelfieApp::updateCamera()
{
	if( touches.size() == 1 )
	{
		const auto forward = ([] {
			auto gravity = MotionManager::getGravityDirection();
			if( abs( gravity.x ) > abs( gravity.y ) ) {
				auto x = copysign( 1.0f, gravity.x );
				return vec3( x, 0, 0 );
			}
			else {
				auto y = copysign( 1.0f, gravity.y );
				return vec3( 0, - y, 0 );
			}
		}());

		auto &touch = touches.front();
		auto delta = vec3( touch.position - touch.previous, 0 );
		touch.previous = touch.position;

		auto amount = length( delta );
		auto dir = dot( normalize(delta), forward );

		if( isfinite( amount ) && isfinite( dir ) ) {
			cameraVelocity += amount * dir;
		}
	}

	auto ray = camera.getViewDirection();
	cameraOffset += ray * cameraVelocity * 0.0025f;
	cameraVelocity *= 0.86f;

	auto l = length(cameraOffset);
	auto maximum = 2.7f;
	if( l > maximum ) {
		cameraOffset *= (maximum / l);
	}
	camera.setEyePoint( cameraOffset );

	auto r = glm::slerp( startOrientation, MotionManager::getRotation(), cameraWeight.value() );
	camera.setOrientation( r );
}

void SelfieSelfieApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );

  {
    gl::enableDepthRead();
    gl::enableDepthWrite();
		gl::ScopedGlslProg prog( gl::getStockShader( gl::ShaderDef().texture(gridTexture->getTexture()->getTarget()) ) );

    gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
    gl::ScopedTextureBind tex1( gridTexture->getBlurredTexture(), 1 );
    gl::ScopedMatrices matrices;
    gl::setMatrices( camera );

		landscape.draw( gridTexture->getCurrentIndex() );

		auto mat = translate( vec3( 0, -4.0f, 0 ) );
		auto dims = vec2(gridTexture->getCellDimensions()) / gridTexture->getGridSize();
		auto offset = vec2(gridTexture->getIndexOffset( gridTexture->getCellDimensions(), gridTexture->getCurrentIndex() )) / gridTexture->getGridSize();
		auto rect = Rectf( -1.0f, -1.0f, 1.0f, 1.0f ).scaled( vec2( 1.333f, 1.0f ) ).scaled( 0.2f );
		auto half_pi = (float) M_PI / 2.0f;
		auto xf1 = translate( vec3( - 12.0f, 0.0f, 0.0f ) ) * rotate( - half_pi, vec3( 1, 0, 0 ) ) * rotate( half_pi, vec3( 0, 1, 0 ) );
		auto xf2 = translate( vec3( 4.0f, 0.0f, 0.0f ) ) * rotate( half_pi, vec3( 1, 0, 0 ) ) * rotate( - half_pi, vec3( 0, 1, 0 ) );

		{
			gl::ScopedModelMatrix m;
			gl::multModelMatrix( xf1 );
			gl::drawSolidRect( rect, offset, offset + dims );
		}

		{
			gl::ScopedModelMatrix m;
			gl::multModelMatrix( xf2 );
			gl::drawSolidRect( rect, offset, offset + dims );
		}

  }

  gl::disableDepthRead();

	gl::ScopedMatrices matrices;
	gl::setMatricesWindow( getWindowSize() );
	introduction.draw();

  if( drawDebug && gridTexture )
  {
    auto rect = Rectf(gridTexture->getTexture()->getBounds());
    auto window_rect = Rectf(getWindowBounds());
    auto window_rect_a = window_rect.scaled( vec2( 0.5f ) );
    auto window_rect_b = window_rect_a + vec2( window_rect_a.getWidth(), 0 );
    gl::draw( gridTexture->getTexture(), rect.getCenteredFit( window_rect_a, false ) );
    gl::draw( gridTexture->getBlurredTexture(), rect.getCenteredFit( window_rect_b, false ) );
  }

  /*
  // For confirming version changes, draw a different colored dot.
  gl::ScopedColor color( Color( 0.0f, 0.0f, 1.0f ) );
  gl::drawSolidCircle( vec2( 20.0f ), 10.0f );
  //*/

  auto err = gl::getError();
  if( err ) {
    CI_LOG_E( "Draw gl error: " << gl::getErrorString(err) );
  }
}

inline void prepareSettings( app::App::Settings *iSettings )
{
  iSettings->setMultiTouchEnabled();
	iSettings->setHighDensityDisplayEnabled();
}

CINDER_APP( SelfieSelfieApp, RendererGl, &prepareSettings )
<commit_msg>Remove some gl error checks.<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

#include "cinder/Capture.h"
#include "cinder/gl/Texture.h"
#include "cinder/gl/GlslProg.h"
#include "cinder/Log.h"
#include "cinder/gl/Fbo.h"
#include "cinder/gl/Shader.h"

#include "GridTexture.h"
#include "Landscape.h"
#include "IntroSequence.h"

#include "cinder/MotionManager.h"
#include "cinder/Timeline.h"

using namespace ci;
using namespace ci::app;
using namespace std;

using namespace soso;

struct TouchInfo {
	TouchInfo() = default;
	TouchInfo( uint32_t iId, const vec2 &iStart, const vec2 &iPosition )
	: id( iId ),
		previous( iStart ),
		position( iPosition )
	{}

  uint32_t		id = 0;
  vec2				previous;
  vec2				position;
};

class SelfieSelfieApp : public App {
public:
	void setup() override;
	void update() override;
	void draw() override;

  void touchesBegan( TouchEvent event ) override;
  void touchesMoved( TouchEvent event ) override;
  void touchesEnded( TouchEvent event ) override;

	void updateCamera();
	void showLandscape();

private:
	CameraPersp				camera;
  CaptureRef				capture;

  GridTextureRef		gridTexture;
  Landscape					landscape;
	gl::BatchRef			cameraImage;
	IntroSequence			introduction;

  vector<TouchInfo> touches;
  ci::vec3					cameraOffset;
	float							cameraVelocity = 0.0f;

  bool							drawDebug = false;

	ci::Anim<float>		cameraWeight = 0.0f;
	quat							startOrientation;
};

void SelfieSelfieApp::setup()
{
  CI_LOG_I("Setting up selfie_x_selfie");

  MotionManager::enable();

  GLint size;
  glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
  CI_LOG_I( "Max texture size: " << size );

  auto target = vec3( 5, 0, 0 );
  camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
  camera.setPerspective( 80, getWindowAspectRatio(), 0.1f, 50.0f );
	startOrientation = camera.getOrientation();

  try {
    CI_LOG_I( "Initializing hardware camera." );
    auto front_facing_camera = ([] {
      auto &devices = Capture::getDevices();
      auto first_device = devices.front();
      for( auto device : devices ) {
        if( device->isFrontFacing() ) {
          return device;
        }
      }
      return first_device;
    }());

		#if defined(CINDER_ANDROID)
			capture = Capture::create( 640, 480, front_facing_camera );
		#else
    	capture = Capture::create( 480, 360, front_facing_camera );
    #endif
    capture->start();

    CI_LOG_I( "Creating Grid Texture" );
    gridTexture = make_shared<GridTexture>( ivec2( 320, 240 ), 12 );

    CI_LOG_I( "Setting up landscape geometry." );
    landscape.setup();
    landscape.setTextureUnits( 0, 1 );
    landscape.setGridSize( gridTexture->getGridDimensions() );
  }
  catch( ci::Exception &exc ) {
    CI_LOG_E( "Error using device camera: " << exc.what() );
  }

	introduction.setup( getAssetPath( "intro/5" ) );
	introduction.setFinishFn( [this] { showLandscape(); } );
}

void SelfieSelfieApp::touchesBegan( TouchEvent event )
{
  for( auto &t : event.getTouches() ) {
    touches.emplace_back( t.getId(), t.getPos(), t.getPos() );
  }

  if( touches.size() == 4 ) {
    drawDebug = ! drawDebug;
  }
}

void SelfieSelfieApp::touchesMoved( TouchEvent event )
{
  for( auto &t : event.getTouches() ) {
    for( auto &s : touches ) {
      if( s.id == t.getId() ) {
				s.previous = s.position;
        s.position = t.getPos();
      }
    }
  }
}

void SelfieSelfieApp::touchesEnded( TouchEvent event )
{
  touches.erase( std::remove_if( touches.begin(), touches.end(), [&event] (const TouchInfo &s) {
    for( auto &t : event.getTouches() ) {
      if (t.getId() == s.id) {
        return true;
      }
    }
    return false;
  }), touches.end() );
}

void SelfieSelfieApp::showLandscape()
{
	// Enable looking around with the gyro
	timeline().apply( &cameraWeight, 1.0f, 1.33f ).easeFn( EaseInOutCubic() );
}

void SelfieSelfieApp::update()
{
	introduction.update();
	updateCamera();

  if( capture && capture->checkNewFrame() ) {
    gridTexture->update( *capture->getSurface() );
  }
}

void SelfieSelfieApp::updateCamera()
{
	if( touches.size() == 1 )
	{
		const auto forward = ([] {
			auto gravity = MotionManager::getGravityDirection();
			if( abs( gravity.x ) > abs( gravity.y ) ) {
				auto x = copysign( 1.0f, gravity.x );
				return vec3( x, 0, 0 );
			}
			else {
				auto y = copysign( 1.0f, gravity.y );
				return vec3( 0, - y, 0 );
			}
		}());

		auto &touch = touches.front();
		auto delta = vec3( touch.position - touch.previous, 0 );
		touch.previous = touch.position;

		auto amount = length( delta );
		auto dir = dot( normalize(delta), forward );

		if( isfinite( amount ) && isfinite( dir ) ) {
			cameraVelocity += amount * dir;
		}
	}

	auto ray = camera.getViewDirection();
	cameraOffset += ray * cameraVelocity * 0.0025f;
	cameraVelocity *= 0.86f;

	auto l = length(cameraOffset);
	auto maximum = 2.7f;
	if( l > maximum ) {
		cameraOffset *= (maximum / l);
	}
	camera.setEyePoint( cameraOffset );

	auto r = glm::slerp( startOrientation, MotionManager::getRotation(), cameraWeight.value() );
	camera.setOrientation( r );
}

void SelfieSelfieApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );

  {
    gl::enableDepthRead();
    gl::enableDepthWrite();
		gl::ScopedGlslProg prog( gl::getStockShader( gl::ShaderDef().texture(gridTexture->getTexture()->getTarget()) ) );

    gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
    gl::ScopedTextureBind tex1( gridTexture->getBlurredTexture(), 1 );
    gl::ScopedMatrices matrices;
    gl::setMatrices( camera );

		landscape.draw( gridTexture->getCurrentIndex() );

		auto mat = translate( vec3( 0, -4.0f, 0 ) );
		auto dims = vec2(gridTexture->getCellDimensions()) / gridTexture->getGridSize();
		auto offset = vec2(gridTexture->getIndexOffset( gridTexture->getCellDimensions(), gridTexture->getCurrentIndex() )) / gridTexture->getGridSize();
		auto rect = Rectf( -1.0f, -1.0f, 1.0f, 1.0f ).scaled( vec2( 1.333f, 1.0f ) ).scaled( 0.2f );
		auto half_pi = (float) M_PI / 2.0f;
		auto xf1 = translate( vec3( - 12.0f, 0.0f, 0.0f ) ) * rotate( - half_pi, vec3( 1, 0, 0 ) ) * rotate( half_pi, vec3( 0, 1, 0 ) );
		auto xf2 = translate( vec3( 4.0f, 0.0f, 0.0f ) ) * rotate( half_pi, vec3( 1, 0, 0 ) ) * rotate( - half_pi, vec3( 0, 1, 0 ) );

		{
			gl::ScopedModelMatrix m;
			gl::multModelMatrix( xf1 );
			gl::drawSolidRect( rect, offset, offset + dims );
		}

		{
			gl::ScopedModelMatrix m;
			gl::multModelMatrix( xf2 );
			gl::drawSolidRect( rect, offset, offset + dims );
		}

  }

  gl::disableDepthRead();

	gl::ScopedMatrices matrices;
	gl::setMatricesWindow( getWindowSize() );
	introduction.draw();

  if( drawDebug && gridTexture )
  {
    auto rect = Rectf(gridTexture->getTexture()->getBounds());
    auto window_rect = Rectf(getWindowBounds());
    auto window_rect_a = window_rect.scaled( vec2( 0.5f ) );
    auto window_rect_b = window_rect_a + vec2( window_rect_a.getWidth(), 0 );
    gl::draw( gridTexture->getTexture(), rect.getCenteredFit( window_rect_a, false ) );
    gl::draw( gridTexture->getBlurredTexture(), rect.getCenteredFit( window_rect_b, false ) );
  }

  /*
  // For confirming version changes, draw a different colored dot.
  gl::ScopedColor color( Color( 0.0f, 0.0f, 1.0f ) );
  gl::drawSolidCircle( vec2( 20.0f ), 10.0f );
  //*/

  auto err = gl::getError();
  if( err ) {
    CI_LOG_E( "Draw gl error: " << gl::getErrorString(err) );
  }
}

inline void prepareSettings( app::App::Settings *iSettings )
{
  iSettings->setMultiTouchEnabled();
	iSettings->setHighDensityDisplayEnabled();
}

CINDER_APP( SelfieSelfieApp, RendererGl, &prepareSettings )
<|endoftext|>


<commit_before>#include "mainwindow.h"

#include <QCloseEvent>

namespace NeovimQt {

MainWindow::MainWindow(NeovimConnector *c, QWidget *parent)
:QMainWindow(parent), m_nvim(0), m_errorWidget(0), m_shell(0),
	m_delayedShow(false)
{
	m_errorWidget = new ErrorWidget();
	newDockWidgetFor(m_errorWidget);
	m_errorWidget->setVisible(false);

	init(c);
}

void MainWindow::init(NeovimConnector *c)
{
	if (m_shell) {
		m_shell->deleteLater();
	}
	if (m_nvim) {
		m_nvim->deleteLater();
	}

	m_nvim = c;
	m_shell = new Shell(c);
	setCentralWidget(m_shell);
	connect(m_shell, SIGNAL(neovimTitleChanged(const QString &)),
			this, SLOT(neovimSetTitle(const QString &)));
	connect(m_shell, &Shell::neovimResized,
			this, &MainWindow::neovimWidgetResized);
	connect(m_nvim, &NeovimConnector::processExited,
			this, &MainWindow::neovimExited);
	connect(m_nvim, &NeovimConnector::error,
			this, &MainWindow::neovimError);
	connect(m_errorWidget, &ErrorWidget::reconnectNeovim,
			this, &MainWindow::reconnectNeovim);
	m_shell->setFocus(Qt::OtherFocusReason);

	if (m_nvim->errorCause()) {
		neovimError(m_nvim->errorCause());
	}
}

QDockWidget* MainWindow::newDockWidgetFor(QWidget *w)
{
	QDockWidget *dock = new QDockWidget(this);
	dock->setAllowedAreas(Qt::TopDockWidgetArea);
	dock->setWidget(w);
	dock->setFeatures(QDockWidget::NoDockWidgetFeatures);
	dock->setTitleBarWidget(new QWidget(this));
	addDockWidget(Qt::TopDockWidgetArea, dock);
	return dock;
}

/** The Neovim process has exited */
void MainWindow::neovimExited(int status)
{
	showIfDelayed();

	if (m_nvim->errorCause() != NeovimConnector::NoError) {
		m_errorWidget->setText(m_nvim->errorString());
		m_errorWidget->showReconnect(m_nvim->canReconnect());
		m_errorWidget->setVisible(true);
	} else if (status != 0) {
		m_errorWidget->setText(QString("Neovim exited with status code (%1)").arg(status));
		m_errorWidget->showReconnect(m_nvim->canReconnect());
		m_errorWidget->setVisible(true);
	} else {
		close();
	}
}
void MainWindow::neovimError(NeovimConnector::NeovimError err)
{
	showIfDelayed();

	switch(err) {
	case NeovimConnector::FailedToStart:
		m_errorWidget->setText("Unable to start nvim: " + m_nvim->errorString());
		break;
	default:
		m_errorWidget->setText(m_nvim->errorString());
	}
	m_errorWidget->showReconnect(m_nvim->canReconnect());
	m_errorWidget->setVisible(true);
}

void MainWindow::neovimSetTitle(const QString &title)
{
	this->setWindowTitle(title);
}

void MainWindow::neovimWidgetResized()
{
	if (isMaximized() || isFullScreen()) {
		// FIXME: for now do nothing, we may have to trigger
		// a shell resize here
	} else {
		resize(sizeHint());
	}
}

void MainWindow::reconnectNeovim()
{
	if (m_nvim->canReconnect()) {
		init(m_nvim->reconnect());
	}
	m_errorWidget->setVisible(false);
}

void MainWindow::closeEvent(QCloseEvent *ev)
{
	// Never unless the Neovim shell closes too
	if (m_shell->close()) {
		QWidget::closeEvent(ev);
	} else {
		ev->ignore();
	}
}

/**
 * Call show() after a 1s delay or when Neovim connects,
 * whichever comes first
 */
void MainWindow::delayedShow(bool enable)
{
	if (m_nvim->errorCause() != NeovimConnector::NoError) {
		show();
		return;
	}

	m_delayedShow = enable;
	if (enable) {
		QTimer *t = new QTimer(this);
		t->setSingleShot(true);
		t->setInterval(1000);
		connect(t, &QTimer::timeout, this, &QMainWindow::show);
		t->start();
	}
}

void MainWindow::showIfDelayed()
{
	if (m_delayedShow && !isVisible()) {
		this->show();
	}
	m_delayedShow = false;
}

} // Namespace

<commit_msg>GUI: Fix delayedShow regression<commit_after>#include "mainwindow.h"

#include <QCloseEvent>

namespace NeovimQt {

MainWindow::MainWindow(NeovimConnector *c, QWidget *parent)
:QMainWindow(parent), m_nvim(0), m_errorWidget(0), m_shell(0),
	m_delayedShow(false)
{
	m_errorWidget = new ErrorWidget();
	newDockWidgetFor(m_errorWidget);
	m_errorWidget->setVisible(false);

	init(c);
}

void MainWindow::init(NeovimConnector *c)
{
	if (m_shell) {
		m_shell->deleteLater();
	}
	if (m_nvim) {
		m_nvim->deleteLater();
	}

	m_nvim = c;
	m_shell = new Shell(c);
	setCentralWidget(m_shell);
	connect(m_shell, SIGNAL(neovimTitleChanged(const QString &)),
			this, SLOT(neovimSetTitle(const QString &)));
	connect(m_shell, &Shell::neovimResized,
			this, &MainWindow::neovimWidgetResized);
	connect(m_nvim, &NeovimConnector::processExited,
			this, &MainWindow::neovimExited);
	connect(m_nvim, &NeovimConnector::error,
			this, &MainWindow::neovimError);
	connect(m_errorWidget, &ErrorWidget::reconnectNeovim,
			this, &MainWindow::reconnectNeovim);
	m_shell->setFocus(Qt::OtherFocusReason);

	if (m_nvim->errorCause()) {
		neovimError(m_nvim->errorCause());
	}
}

QDockWidget* MainWindow::newDockWidgetFor(QWidget *w)
{
	QDockWidget *dock = new QDockWidget(this);
	dock->setAllowedAreas(Qt::TopDockWidgetArea);
	dock->setWidget(w);
	dock->setFeatures(QDockWidget::NoDockWidgetFeatures);
	dock->setTitleBarWidget(new QWidget(this));
	addDockWidget(Qt::TopDockWidgetArea, dock);
	return dock;
}

/** The Neovim process has exited */
void MainWindow::neovimExited(int status)
{
	showIfDelayed();

	if (m_nvim->errorCause() != NeovimConnector::NoError) {
		m_errorWidget->setText(m_nvim->errorString());
		m_errorWidget->showReconnect(m_nvim->canReconnect());
		m_errorWidget->setVisible(true);
	} else if (status != 0) {
		m_errorWidget->setText(QString("Neovim exited with status code (%1)").arg(status));
		m_errorWidget->showReconnect(m_nvim->canReconnect());
		m_errorWidget->setVisible(true);
	} else {
		close();
	}
}
void MainWindow::neovimError(NeovimConnector::NeovimError err)
{
	showIfDelayed();

	switch(err) {
	case NeovimConnector::FailedToStart:
		m_errorWidget->setText("Unable to start nvim: " + m_nvim->errorString());
		break;
	default:
		m_errorWidget->setText(m_nvim->errorString());
	}
	m_errorWidget->showReconnect(m_nvim->canReconnect());
	m_errorWidget->setVisible(true);
}

void MainWindow::neovimSetTitle(const QString &title)
{
	this->setWindowTitle(title);
}

void MainWindow::neovimWidgetResized()
{
	if (isMaximized() || isFullScreen()) {
		// FIXME: for now do nothing, we may have to trigger
		// a shell resize here
	} else {
		resize(sizeHint());
	}
}

void MainWindow::reconnectNeovim()
{
	if (m_nvim->canReconnect()) {
		init(m_nvim->reconnect());
	}
	m_errorWidget->setVisible(false);
}

void MainWindow::closeEvent(QCloseEvent *ev)
{
	// Never unless the Neovim shell closes too
	if (m_shell->close()) {
		QWidget::closeEvent(ev);
	} else {
		ev->ignore();
	}
}

/// Call show() after a 1s delay or when Neovim attachment
/// is complete, whichever comes first
void MainWindow::delayedShow(bool enable)
{
	if (m_nvim->errorCause() != NeovimConnector::NoError) {
		show();
		return;
	}

	m_delayedShow = enable;
	if (enable) {
		QTimer *t = new QTimer(this);
		t->setSingleShot(true);
		t->setInterval(1000);
		connect(m_shell, &Shell::neovimResized, this, &QMainWindow::show);
		connect(t, &QTimer::timeout, this, &QMainWindow::show);
		t->start();
	}
}

void MainWindow::showIfDelayed()
{
	if (m_delayedShow && !isVisible()) {
		this->show();
	}
	m_delayedShow = false;
}

} // Namespace

<|endoftext|>


<commit_before>/* mbino - basic mbed APIs for the Arduino platform
 * Copyright (c) 2017 Thomas Kemmer
 *
 * mbed Microcontroller Library
 * Copyright (c) 2006-2013 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You
 * may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.  See the License for the specific language governing
 * permissions and limitations under the License.
 */
#include "serial_api.h"

#include <Arduino.h>
#include <SoftwareSerial.h>

namespace mbino {

    template<class T>
    void serial_stream_begin(serial_stream_t* obj, long baud, uint8_t config)
    {
        T* stream = static_cast<T*>(obj);
        stream->begin(baud, config);
        // wait for serial port to become ready
        while (!*stream)
            ;
    }

    template<class T>
    void serial_stream_end(serial_stream_t* obj)
    {
        static_cast<T*>(obj)->end();
    }

    template<>
    void serial_stream_begin<SoftwareSerial>(serial_stream_t* obj, long baud, uint8_t)
    {
        // config not supported
        static_cast<SoftwareSerial*>(obj)->begin(baud);
    }

    template<>
    void serial_stream_end<SoftwareSerial>(serial_stream_t* obj)
    {
        // no virtual destructor!!!
        SoftwareSerial* serial = static_cast<SoftwareSerial*>(obj);
        delete serial;
    }

    template<class T>
    static void serial_init(serial_t* obj, T* stream)
    {
        static const serial_stream_interface_t interface = {
            &serial_stream_begin<T>,
            &serial_stream_end<T>
        };
        obj->interface = &interface;
        obj->stream = stream;
        obj->baudrate = 9600;
        obj->config = SERIAL_8N1;
        obj->initialized = false;
    }

    static void serial_begin(serial_t* obj)
    {
        // serial API is not synchronized
        if (!obj->initialized) {
            obj->interface->begin(obj->stream, obj->baudrate, obj->config);
            obj->initialized = true;
        }
    }

    static void serial_restart(serial_t* obj)
    {
        // serial API is not synchronized
        if (obj->initialized) {
            obj->stream->flush();
            obj->interface->begin(obj->stream, obj->baudrate, obj->config);
        }
    }

    void serial_init(serial_t* obj, PinName tx, PinName rx)
    {
        serial_init(obj, new SoftwareSerial(rx, tx));
    }

    int serial_usb_init(serial_t* obj)
    {
#ifdef SERIAL_PORT_MONITOR
        serial_init(obj, &SERIAL_PORT_MONITOR);
        return 0;
#else
        return -1;
#endif
    }

    int serial_uart_init(serial_t* obj, uint8_t uart)
    {
        switch (uart) {
#ifdef SERIAL_PORT_HARDWARE
        case 0:
            serial_init(obj, &SERIAL_PORT_HARDWARE);
            return 0;
#endif
#ifdef SERIAL_PORT_HARDWARE1
        case 1:
            serial_init(obj, &SERIAL_PORT_HARDWARE1);
            return 0;
#endif
#ifdef SERIAL_PORT_HARDWARE2
        case 2:
            serial_init(obj, &SERIAL_PORT_HARDWARE2);
            return 0;
#endif
#ifdef SERIAL_PORT_HARDWARE3
        case 3:
            serial_init(obj, &SERIAL_PORT_HARDWARE3);
            return 0;
#endif
        default:
            return -1;
        }
    }

    void serial_free(serial_t* obj)
    {
        obj->interface->end(obj->stream);
    }

    void serial_baud(serial_t* obj, long baudrate)
    {
        obj->baudrate = baudrate;
        serial_restart(obj);
    }

    void serial_format(serial_t* obj, uint8_t data_bits, SerialParity parity, uint8_t stop_bits)
    {
        uint8_t config = (((data_bits - 5) & 0x3) << 1) | (((stop_bits - 1) & 0x1) << 3);
        switch (parity) {
        case ParityNone:
            config |= SERIAL_8N1 & 0xF0;
            break;
        case ParityOdd:
            config |= SERIAL_8O1 & 0xF0;
            break;
        case ParityEven:
            config |= SERIAL_8E1 & 0xF0;
            break;
        }
        obj->config = config;
        serial_restart(obj);
    }

    int serial_getc(serial_t* obj)
    {
        serial_begin(obj);
        // mbed getc() is blocking, while Arduino Stream::read() is not
        int c;
        do {
            c = obj->stream->read();
        } while (c < 0);
        return c;
    }

    void serial_putc(serial_t* obj, int c)
    {
        serial_begin(obj);
        obj->stream->write(c);
    }

    void serial_puts(serial_t* obj, const char* s)
    {
        serial_begin(obj);
        obj->stream->write(s);
    }

    bool serial_readable(serial_t* obj)
    {
        return obj->stream->available() != 0;
    }

    bool serial_writable(serial_t* obj)
    {
        return obj->stream->availableForWrite() != 0;
    }

}
<commit_msg>Fix #4: Check for known hardware pin names in serial_init().<commit_after>/* mbino - basic mbed APIs for the Arduino platform
 * Copyright (c) 2017 Thomas Kemmer
 *
 * mbed Microcontroller Library
 * Copyright (c) 2006-2013 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You
 * may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.  See the License for the specific language governing
 * permissions and limitations under the License.
 */
#include "serial_api.h"

#include <Arduino.h>
#include <SoftwareSerial.h>

namespace mbino {

    template<class T>
    void serial_stream_begin(serial_stream_t* obj, long baud, uint8_t config)
    {
        T* stream = static_cast<T*>(obj);
        stream->begin(baud, config);
        // wait for serial port to become ready
        while (!*stream)
            ;
    }

    template<class T>
    void serial_stream_end(serial_stream_t* obj)
    {
        static_cast<T*>(obj)->end();
    }

    template<>
    void serial_stream_begin<SoftwareSerial>(serial_stream_t* obj, long baud, uint8_t)
    {
        // config not supported
        static_cast<SoftwareSerial*>(obj)->begin(baud);
    }

    template<>
    void serial_stream_end<SoftwareSerial>(serial_stream_t* obj)
    {
        // no virtual destructor!!!
        SoftwareSerial* serial = static_cast<SoftwareSerial*>(obj);
        delete serial;
    }

    template<class T>
    static void serial_init(serial_t* obj, T* stream)
    {
        static const serial_stream_interface_t interface = {
            &serial_stream_begin<T>,
            &serial_stream_end<T>
        };
        obj->interface = &interface;
        obj->stream = stream;
        obj->baudrate = 9600;
        obj->config = SERIAL_8N1;
        obj->initialized = false;
    }

    static void serial_begin(serial_t* obj)
    {
        // serial API is not synchronized
        if (!obj->initialized) {
            obj->interface->begin(obj->stream, obj->baudrate, obj->config);
            obj->initialized = true;
        }
    }

    static void serial_restart(serial_t* obj)
    {
        // serial API is not synchronized
        if (obj->initialized) {
            obj->stream->flush();
            obj->interface->begin(obj->stream, obj->baudrate, obj->config);
        }
    }

    void serial_init(serial_t* obj, PinName tx, PinName rx)
    {
        if (false) {
            // make the compiler happy
        }
#ifdef SERIAL_PORT_HARDWARE
        else if (tx == 1 && rx == 0) {
            serial_init(obj, &SERIAL_PORT_HARDWARE);
        }
#endif
#ifdef SERIAL_PORT_HARDWARE1
        else if (tx == 18 && rx == 19) {
            serial_init(obj, &SERIAL_PORT_HARDWARE1);
        }
#endif
#ifdef SERIAL_PORT_HARDWARE2
        else if (tx == 16 && rx == 17) {
            serial_init(obj, &SERIAL_PORT_HARDWARE2);
        }
#endif
#ifdef SERIAL_PORT_HARDWARE3
        else if (tx == 14 && rx == 15) {
            serial_init(obj, &SERIAL_PORT_HARDWARE3);
        }
#endif
        else {
            serial_init(obj, new SoftwareSerial(rx, tx));
        }
    }

    int serial_usb_init(serial_t* obj)
    {
#ifdef SERIAL_PORT_MONITOR
        serial_init(obj, &SERIAL_PORT_MONITOR);
        return 0;
#else
        return -1;
#endif
    }

    int serial_uart_init(serial_t* obj, uint8_t uart)
    {
        switch (uart) {
#ifdef SERIAL_PORT_HARDWARE
        case 0:
            serial_init(obj, &SERIAL_PORT_HARDWARE);
            return 0;
#endif
#ifdef SERIAL_PORT_HARDWARE1
        case 1:
            serial_init(obj, &SERIAL_PORT_HARDWARE1);
            return 0;
#endif
#ifdef SERIAL_PORT_HARDWARE2
        case 2:
            serial_init(obj, &SERIAL_PORT_HARDWARE2);
            return 0;
#endif
#ifdef SERIAL_PORT_HARDWARE3
        case 3:
            serial_init(obj, &SERIAL_PORT_HARDWARE3);
            return 0;
#endif
        default:
            return -1;
        }
    }

    void serial_free(serial_t* obj)
    {
        obj->interface->end(obj->stream);
    }

    void serial_baud(serial_t* obj, long baudrate)
    {
        obj->baudrate = baudrate;
        serial_restart(obj);
    }

    void serial_format(serial_t* obj, uint8_t data_bits, SerialParity parity, uint8_t stop_bits)
    {
        uint8_t config = (((data_bits - 5) & 0x3) << 1) | (((stop_bits - 1) & 0x1) << 3);
        switch (parity) {
        case ParityNone:
            config |= SERIAL_8N1 & 0xF0;
            break;
        case ParityOdd:
            config |= SERIAL_8O1 & 0xF0;
            break;
        case ParityEven:
            config |= SERIAL_8E1 & 0xF0;
            break;
        }
        obj->config = config;
        serial_restart(obj);
    }

    int serial_getc(serial_t* obj)
    {
        serial_begin(obj);
        // mbed getc() is blocking, while Arduino Stream::read() is not
        int c;
        do {
            c = obj->stream->read();
        } while (c < 0);
        return c;
    }

    void serial_putc(serial_t* obj, int c)
    {
        serial_begin(obj);
        obj->stream->write(c);
    }

    void serial_puts(serial_t* obj, const char* s)
    {
        serial_begin(obj);
        obj->stream->write(s);
    }

    bool serial_readable(serial_t* obj)
    {
        return obj->stream->available() != 0;
    }

    bool serial_writable(serial_t* obj)
    {
        return obj->stream->availableForWrite() != 0;
    }

}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2022.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include "../../Foundation/Characters/ToString.h"
#include "../../Foundation/DataExchange/InternetMediaType.h"
#include "../../Foundation/DataExchange/InternetMediaTypeRegistry.h"
#include "../../Foundation/Debug/TimingTrace.h"
#include "../../Foundation/IO/FileSystem/Common.h"
#include "../../Foundation/IO/FileSystem/FileInputStream.h"
#include "../../Foundation/IO/FileSystem/PathName.h"
#include "../../Foundation/IO/Network/HTTP/ClientErrorException.h"
#include "../../Foundation/Streams/InputStream.h"

#include "FileSystemRequestHandler.h"

using std::byte;

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO::FileSystem;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Streams;

using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::WebServer;

using IO::Network::HTTP::ClientErrorException;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1

namespace {
    struct FSRouterRep_ {
        filesystem::path                              fFSRoot_;
        optional<String>                              fURLPrefix2Strip;
        Sequence<String>                              fDefaultIndexFileNames;
        vector<pair<RegularExpression, CacheControl>> fCacheControlSettings;

        FSRouterRep_ (
            const filesystem::path&                                          filesystemRoot,
            const optional<String>&                                          urlPrefix2Strip,
            const Sequence<String>&                                          defaultIndexFileNames,
            const optional<Sequence<pair<RegularExpression, CacheControl>>>& cacheControlSettings)
            : fFSRoot_{filesystem::canonical (filesystemRoot)}
            , fURLPrefix2Strip{urlPrefix2Strip}
            , fDefaultIndexFileNames{defaultIndexFileNames}
        {
            if (cacheControlSettings) {
                for (const auto& i : *cacheControlSettings) {
                    fCacheControlSettings.push_back (i);
                }
            }
        }
        void HandleMessage (Message* m)
        {
#if qDefaultTracingOn
            Debug::TimingTrace ttrc{L"FSRouterRep_::HandleMessage", .001}; // prelim - gather info on whether worht supporting ETAGs etc - why is this sometimes somewhat slow
#endif
            /*
             * @todo rewrite to incrementally copy file from stream, not read all into RAM
             */
            using DataExchange::InternetMediaTypeRegistry;
            // super primitive draft
            RequireNotNull (m);
            String           urlHostRelPath{ExtractURLHostRelPath_ (m)};
            filesystem::path fn{fFSRoot_ / filesystem::path{urlHostRelPath.As<wstring> ()}};
#if USE_NOISY_TRACE_IN_THIS_MODULE_
            Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"{}...FileSystemRequestHandler...HandleMessage", L"relURL=%s, serving fn=%s", Characters::ToString (m->request ()->url ().GetAuthorityRelativeResource ()).c_str (), Characters::ToString (fn).c_str ())};
#endif
            try {
                Response&              response = m->rwResponse ();
                InputStream<byte>::Ptr in{FileInputStream::New (fn)};
                if (optional<InternetMediaType> oMediaType = InternetMediaTypeRegistry::Get ().GetAssociatedContentType (fn.extension ())) {
                    response.contentType = *oMediaType;
#if USE_NOISY_TRACE_IN_THIS_MODULE_
                    DbgTrace (L"content-type: %s", oMediaType->ToString ().c_str ());
#endif
                }
                ApplyCacheControl_ (response, urlHostRelPath);
                response.write (in.ReadAll ());
            }
            catch (const system_error& e) {
#if qCompilerAndStdLib_error_code_compare_condition_Buggy
                // not sure how to workaround this, but fixed in the latest gcc (GLIBCXX 9)
#endif
                if (e.code () == errc::no_such_file_or_directory) {
                    Execution::Throw (ClientErrorException{HTTP::StatusCodes::kNotFound});
                }
                else {
                    Execution::ReThrow ();
                }
            }
        }
        void ApplyCacheControl_ (Response& r, const String& urlRelPath) const
        {
            for (const auto& i : fCacheControlSettings) {
                if (urlRelPath.Match (i.first)) {
                    r.rwHeaders ().cacheControl = i.second;
                    break; // just apply first
                }
            }
        }
        String ExtractURLHostRelPath_ (const Message* m) const
        {
            const Request& request        = m->request ();
            String         urlHostRelPath = request.url ().GetAbsPath<String> ().SubString (1);
            if (fURLPrefix2Strip) {
                if (urlHostRelPath.StartsWith (*fURLPrefix2Strip)) {
                    urlHostRelPath = urlHostRelPath.SubString (fURLPrefix2Strip->length ());
                    if (urlHostRelPath.StartsWith (L"/"sv)) {
                        urlHostRelPath = urlHostRelPath.SubString (1);
                    }
                }
                else {
                    Execution::Throw (ClientErrorException{HTTP::StatusCodes::kNotFound});
                }
            }
            if ((urlHostRelPath.empty () or urlHostRelPath.EndsWith ('/')) and not fDefaultIndexFileNames.empty ()) {
                //@todo tmphack - need to try a bunch and look for 'access'
                urlHostRelPath += fDefaultIndexFileNames[0];
            }
            return urlHostRelPath;
        }
    };
}

/*
 ********************************************************************************
 ************************* WebServer::FileSystemRequestHandler ******************
 ********************************************************************************
 */
FileSystemRequestHandler::FileSystemRequestHandler (const filesystem::path& filesystemRoot, const Options& options)
    : RequestHandler{[rep = make_shared<FSRouterRep_> (filesystemRoot, options.fURLPrefix2Strip, Memory::NullCoalesce (options.fDefaultIndexFileNames), options.fCacheControlSettings)] (Message* m) -> void { rep->HandleMessage (m); }}
{
}
<commit_msg>fixed typo<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2022.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include "../../Foundation/Characters/ToString.h"
#include "../../Foundation/DataExchange/InternetMediaType.h"
#include "../../Foundation/DataExchange/InternetMediaTypeRegistry.h"
#include "../../Foundation/Debug/TimingTrace.h"
#include "../../Foundation/IO/FileSystem/Common.h"
#include "../../Foundation/IO/FileSystem/FileInputStream.h"
#include "../../Foundation/IO/FileSystem/PathName.h"
#include "../../Foundation/IO/Network/HTTP/ClientErrorException.h"
#include "../../Foundation/Streams/InputStream.h"

#include "FileSystemRequestHandler.h"

using std::byte;

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO::FileSystem;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Streams;

using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::WebServer;

using IO::Network::HTTP::ClientErrorException;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1

namespace {
    struct FSRouterRep_ {
        filesystem::path                              fFSRoot_;
        optional<String>                              fURLPrefix2Strip;
        Sequence<String>                              fDefaultIndexFileNames;
        vector<pair<RegularExpression, CacheControl>> fCacheControlSettings;

        FSRouterRep_ (
            const filesystem::path&                                          filesystemRoot,
            const optional<String>&                                          urlPrefix2Strip,
            const Sequence<String>&                                          defaultIndexFileNames,
            const optional<Sequence<pair<RegularExpression, CacheControl>>>& cacheControlSettings)
            : fFSRoot_{filesystem::canonical (filesystemRoot)}
            , fURLPrefix2Strip{urlPrefix2Strip}
            , fDefaultIndexFileNames{defaultIndexFileNames}
        {
            if (cacheControlSettings) {
                for (const auto& i : *cacheControlSettings) {
                    fCacheControlSettings.push_back (i);
                }
            }
        }
        void HandleMessage (Message* m)
        {
#if qDefaultTracingOn
            Debug::TimingTrace ttrc{L"FSRouterRep_::HandleMessage", .001}; // prelim - gather info on whether worht supporting ETAGs etc - why is this sometimes somewhat slow
#endif
            /*
             * @todo rewrite to incrementally copy file from stream, not read all into RAM
             */
            using DataExchange::InternetMediaTypeRegistry;
            // super primitive draft
            RequireNotNull (m);
            String           urlHostRelPath{ExtractURLHostRelPath_ (m)};
            filesystem::path fn{fFSRoot_ / filesystem::path{urlHostRelPath.As<wstring> ()}};
#if USE_NOISY_TRACE_IN_THIS_MODULE_
            Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"{}...FileSystemRequestHandler...HandleMessage", L"relURL=%s, serving fn=%s", Characters::ToString (m->request ().url ().GetAuthorityRelativeResource ()).c_str (), Characters::ToString (fn).c_str ())};
#endif
            try {
                Response&              response = m->rwResponse ();
                InputStream<byte>::Ptr in{FileInputStream::New (fn)};
                if (optional<InternetMediaType> oMediaType = InternetMediaTypeRegistry::Get ().GetAssociatedContentType (fn.extension ())) {
                    response.contentType = *oMediaType;
#if USE_NOISY_TRACE_IN_THIS_MODULE_
                    DbgTrace (L"content-type: %s", oMediaType->ToString ().c_str ());
#endif
                }
                ApplyCacheControl_ (response, urlHostRelPath);
                response.write (in.ReadAll ());
            }
            catch (const system_error& e) {
#if qCompilerAndStdLib_error_code_compare_condition_Buggy
                // not sure how to workaround this, but fixed in the latest gcc (GLIBCXX 9)
#endif
                if (e.code () == errc::no_such_file_or_directory) {
                    Execution::Throw (ClientErrorException{HTTP::StatusCodes::kNotFound});
                }
                else {
                    Execution::ReThrow ();
                }
            }
        }
        void ApplyCacheControl_ (Response& r, const String& urlRelPath) const
        {
            for (const auto& i : fCacheControlSettings) {
                if (urlRelPath.Match (i.first)) {
                    r.rwHeaders ().cacheControl = i.second;
                    break; // just apply first
                }
            }
        }
        String ExtractURLHostRelPath_ (const Message* m) const
        {
            const Request& request        = m->request ();
            String         urlHostRelPath = request.url ().GetAbsPath<String> ().SubString (1);
            if (fURLPrefix2Strip) {
                if (urlHostRelPath.StartsWith (*fURLPrefix2Strip)) {
                    urlHostRelPath = urlHostRelPath.SubString (fURLPrefix2Strip->length ());
                    if (urlHostRelPath.StartsWith (L"/"sv)) {
                        urlHostRelPath = urlHostRelPath.SubString (1);
                    }
                }
                else {
                    Execution::Throw (ClientErrorException{HTTP::StatusCodes::kNotFound});
                }
            }
            if ((urlHostRelPath.empty () or urlHostRelPath.EndsWith ('/')) and not fDefaultIndexFileNames.empty ()) {
                //@todo tmphack - need to try a bunch and look for 'access'
                urlHostRelPath += fDefaultIndexFileNames[0];
            }
            return urlHostRelPath;
        }
    };
}

/*
 ********************************************************************************
 ************************* WebServer::FileSystemRequestHandler ******************
 ********************************************************************************
 */
FileSystemRequestHandler::FileSystemRequestHandler (const filesystem::path& filesystemRoot, const Options& options)
    : RequestHandler{[rep = make_shared<FSRouterRep_> (filesystemRoot, options.fURLPrefix2Strip, Memory::NullCoalesce (options.fDefaultIndexFileNames), options.fCacheControlSettings)] (Message* m) -> void { rep->HandleMessage (m); }}
{
}
<|endoftext|>


<commit_before>#include <TTree.h>
#include <TLorentzVector.h>

#include <AliLog.h>
#include <AliEmcalJet.h>
#include "AliJetContainer.h"
#include "AliAnalysisTaskPrepareInputForEmbedding.h"

ClassImp(AliAnalysisTaskPrepareInputForEmbedding)

//________________________________________________________________________________________________
AliAnalysisTaskPrepareInputForEmbedding::AliAnalysisTaskPrepareInputForEmbedding() : AliAnalysisTaskEmcalJet("AliAnalysisTaskPrepareInputForEmbedding", kTRUE),
fContainer(0),
fMinFractionShared(-1),
fLeadingJetOnly(0),
fTreeJets(0),
fJetDet(0),
fJetPart(0),
fJetDetL(0),
fJetPartL(0),
fNumberOfJets(0),
fhFractionSharedpT(0),
fNAccJets(0)
{
   /// default constructor

   SetMakeGeneralHistograms(kTRUE);

   DefineOutput(2, TTree::Class());
}

//________________________________________________________________________________________________
AliAnalysisTaskPrepareInputForEmbedding::AliAnalysisTaskPrepareInputForEmbedding(const char *name) : AliAnalysisTaskEmcalJet(name, kTRUE),
fContainer(0),
fMinFractionShared(-1),
fLeadingJetOnly(0),
fTreeJets(0),
fJetDet(0),
fJetPart(0),
fJetDetL(0),
fJetPartL(0),
fNumberOfJets(0),
fhFractionSharedpT(0),
fNAccJets(0)

{
   /// standard constructor

   SetMakeGeneralHistograms(kTRUE);
   AliInfo("standard constructor");
   DefineOutput(2, TTree::Class());
}
//________________________________________________________________________________________________

void AliAnalysisTaskPrepareInputForEmbedding::UserCreateOutputObjects(){
   /// Create output
   AliAnalysisTaskEmcal::UserCreateOutputObjects();

   fJetDet   = new TLorentzVector();
   fJetPart  = new TLorentzVector();
   fJetDetL  = new TLorentzVector();
   fJetPartL = new TLorentzVector();

   fTreeJets = new TTree("fTreeJet", "fTreeJet");
   //Important! 'dot' after the name needed -- see TTree doc! otherwise the objects in the branches have all the same name and the output cannot be properly retrieved (only with the TBrowser)
   if(fLeadingJetOnly){
      fTreeJets->Branch("fJetDetL.", fJetDetL);
      fTreeJets->Branch("fJetPartL.",fJetPartL);
   } else {
      fTreeJets->Branch("fJetDet.", fJetDet);
      fTreeJets->Branch("fJetPart.",fJetPart);
   }
   //fOutput->Add(fTreeJets);
   PostData(2, fTreeJets);

   //check
   const Int_t nBinsPt          = 40;
   const Int_t nBinsFraction    = 101;

   const Double_t minPt       = -50.;
   const Double_t maxPt       = 150.;
   const Double_t minFraction =  -0.005;
   const Double_t maxFraction =  1.005;

   fNumberOfJets = new TH1F("fNumberOfJets", "Number of Jets", 6, -0.5, 5.5);
   fOutput->Add(fNumberOfJets);

   fhFractionSharedpT = new TH2F("fhFractionSharedpT", "Reco/particle shared #it{p}_{T} fraction;#it{p}_{T} (GeV/c); Fraction shared #it{p}_{T}", nBinsPt, minPt, maxPt, nBinsFraction, minFraction, maxFraction);
   fOutput->Add(fhFractionSharedpT);

   fNAccJets = new TH1F("fNAccJets","fNAccJets;N/ev",11,-0.5, 9.5);
   fOutput->Add(fNAccJets);

}

//________________________________________________________________________________________________
Bool_t AliAnalysisTaskPrepareInputForEmbedding::Run(){
   /// Run code before FillHistograms()

   return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliAnalysisTaskPrepareInputForEmbedding::FillHistograms(){
   /// Fill histograms defined
   /// In this case it's a TTree

   // Get container with area-based subtraction
   AliEmcalJet* jet = NULL;
   AliJetContainer *jetCont = GetJetContainer(fContainer);
   if(!jetCont) {
      AliError(Form("Container position %d (area based) not found", fContainer));
      return kFALSE;
   }

   //TVector for leading jet
   fJetDetL ->SetPtEtaPhiM(0,0,0,0);
   fJetPartL->SetPtEtaPhiM(0,0,0,0);

   Int_t count = 0;
   jetCont->ResetCurrentID();

   while((jet = jetCont->GetNextJet())) {
      Bool_t acc = jetCont->AcceptJet(jet);
      if(!acc) {
      	 continue;
      }
      fJetDet  ->SetPtEtaPhiM(0,0,0,0);
      fJetPart ->SetPtEtaPhiM(0,0,0,0);

      count++;
      fNumberOfJets->Fill(0);

      AliEmcalJet *jetP = jet->ClosestJet();
      if(!jetP) continue;
      fNumberOfJets->Fill(1);
      Double_t fraction = jetCont->GetFractionSharedPt(jet);
      //fill the TLorentsVectors with the jet 4-vectors
      //Printf("MC jet %p, Fraction %.4f, pT %f, eta %f, phi %f, m  %f",jetP, fraction, jet->Pt(), jet->Eta(), jet->Phi(), jet->M());
      fhFractionSharedpT->Fill(jet->Pt(), fraction);
      if(fMinFractionShared<0. || fraction>fMinFractionShared) {
      	 fNumberOfJets->Fill(2);
      	 fJetDet ->SetPtEtaPhiM(jet->Pt(), jet->Eta(), jet->Phi(), jet->M());
      	 fJetPart->SetPtEtaPhiM(jetP->Pt(), jetP->Eta(), jetP->Phi(), jetP->M());

      	 if(fJetDet->Pt() > fJetDetL->Pt()){
      	    fJetDetL->SetPtEtaPhiM(fJetDet->Pt(), fJetDet->Eta(), fJetDet->Phi(), fJetDet->M());
      	    fJetPartL->SetPtEtaPhiM(fJetPart->Pt(), fJetPart->Eta(), fJetPart->Phi(), fJetPart->M());

      	 }
      	 if(!fLeadingJetOnly) fTreeJets->Fill();

      }

   }
   fNAccJets->Fill(count);

   if(fLeadingJetOnly) {
      if(fJetPartL->Pt() > 0){ // fill only when there is a leading jet
      	 fTreeJets->Fill();
      }
   }

   return kTRUE;
}

//________________________________________________________________________________________________

AliAnalysisTaskPrepareInputForEmbedding::~AliAnalysisTaskPrepareInputForEmbedding() {
   /// Destructor.

 }

//________________________________________________________________________________________________

void AliAnalysisTaskPrepareInputForEmbedding::Terminate(Option_t *)
{
   /// Called once at the end of the analysis.

}
<commit_msg>Add branches for cross section and Ntrials<commit_after>#include <TTree.h>
#include <TLorentzVector.h>

#include <AliLog.h>
#include <AliEmcalJet.h>
#include "AliJetContainer.h"
#include "AliAnalysisTaskPrepareInputForEmbedding.h"

ClassImp(AliAnalysisTaskPrepareInputForEmbedding)

//________________________________________________________________________________________________
AliAnalysisTaskPrepareInputForEmbedding::AliAnalysisTaskPrepareInputForEmbedding() : AliAnalysisTaskEmcalJet("AliAnalysisTaskPrepareInputForEmbedding", kTRUE),
fContainer(0),
fMinFractionShared(-1),
fLeadingJetOnly(0),
fTreeJets(0),
fJetDet(0),
fJetPart(0),
fJetDetL(0),
fJetPartL(0),
fNumberOfJets(0),
fhFractionSharedpT(0),
fNAccJets(0)
{
   /// default constructor

   SetMakeGeneralHistograms(kTRUE);

   DefineOutput(2, TTree::Class());
}

//________________________________________________________________________________________________
AliAnalysisTaskPrepareInputForEmbedding::AliAnalysisTaskPrepareInputForEmbedding(const char *name) : AliAnalysisTaskEmcalJet(name, kTRUE),
fContainer(0),
fMinFractionShared(-1),
fLeadingJetOnly(0),
fTreeJets(0),
fJetDet(0),
fJetPart(0),
fJetDetL(0),
fJetPartL(0),
fNumberOfJets(0),
fhFractionSharedpT(0),
fNAccJets(0)

{
   /// standard constructor

   SetMakeGeneralHistograms(kTRUE);
   AliInfo("standard constructor");
   DefineOutput(2, TTree::Class());
}
//________________________________________________________________________________________________

void AliAnalysisTaskPrepareInputForEmbedding::UserCreateOutputObjects(){
   /// Create output
   AliAnalysisTaskEmcal::UserCreateOutputObjects();

   fJetDet   = new TLorentzVector();
   fJetPart  = new TLorentzVector();
   fJetDetL  = new TLorentzVector();
   fJetPartL = new TLorentzVector();

   fTreeJets = new TTree("fTreeJet", "fTreeJet");
   //Important! 'dot' after the name needed -- see TTree doc! otherwise the objects in the branches have all the same name and the output cannot be properly retrieved (only with the TBrowser)
   if(fLeadingJetOnly){
      fTreeJets->Branch("fJetDetL.", fJetDetL);
      fTreeJets->Branch("fJetPartL.",fJetPartL);
      fTreeJets->Branch("fXsection", &fXsection, "fXsection/F");
      fTreeJets->Branch("fNTrials",  &fNTrials, "fNTrials/I");
   } else {
      fTreeJets->Branch("fJetDet.", fJetDet);
      fTreeJets->Branch("fJetPart.",fJetPart);
      fTreeJets->Branch("fXsection", &fXsection, "fXsection/F");
      fTreeJets->Branch("fNTrials",  &fNTrials, "fNTrials/I");
   }
   //fOutput->Add(fTreeJets);
   PostData(2, fTreeJets);

   //check
   const Int_t nBinsPt          = 40;
   const Int_t nBinsFraction    = 101;

   const Double_t minPt       = -50.;
   const Double_t maxPt       = 150.;
   const Double_t minFraction =  -0.005;
   const Double_t maxFraction =  1.005;

   fNumberOfJets = new TH1F("fNumberOfJets", "Number of Jets", 6, -0.5, 5.5);
   fOutput->Add(fNumberOfJets);

   fhFractionSharedpT = new TH2F("fhFractionSharedpT", "Reco/particle shared #it{p}_{T} fraction;#it{p}_{T} (GeV/c); Fraction shared #it{p}_{T}", nBinsPt, minPt, maxPt, nBinsFraction, minFraction, maxFraction);
   fOutput->Add(fhFractionSharedpT);

   fNAccJets = new TH1F("fNAccJets","fNAccJets;N/ev",11,-0.5, 9.5);
   fOutput->Add(fNAccJets);

}

//________________________________________________________________________________________________
Bool_t AliAnalysisTaskPrepareInputForEmbedding::Run(){
   /// Run code before FillHistograms()

   return kTRUE;
}
//________________________________________________________________________________________________
Bool_t AliAnalysisTaskPrepareInputForEmbedding::FillHistograms(){
   /// Fill histograms defined
   /// In this case it's a TTree

   // Get container with area-based subtraction
   AliEmcalJet* jet = NULL;
   AliJetContainer *jetCont = GetJetContainer(fContainer);
   if(!jetCont) {
      AliError(Form("Container position %d (area based) not found", fContainer));
      return kFALSE;
   }

   //TVector for leading jet
   fJetDetL ->SetPtEtaPhiM(0,0,0,0);
   fJetPartL->SetPtEtaPhiM(0,0,0,0);

   Int_t count = 0;
   jetCont->ResetCurrentID();

   while((jet = jetCont->GetNextJet())) {
      Bool_t acc = jetCont->AcceptJet(jet);
      if(!acc) {
      	 continue;
      }
      fJetDet  ->SetPtEtaPhiM(0,0,0,0);
      fJetPart ->SetPtEtaPhiM(0,0,0,0);

      count++;
      fNumberOfJets->Fill(0);

      AliEmcalJet *jetP = jet->ClosestJet();
      if(!jetP) continue;
      fNumberOfJets->Fill(1);
      Double_t fraction = jetCont->GetFractionSharedPt(jet);
      //fill the TLorentsVectors with the jet 4-vectors
      //Printf("MC jet %p, Fraction %.4f, pT %f, eta %f, phi %f, m  %f",jetP, fraction, jet->Pt(), jet->Eta(), jet->Phi(), jet->M());
      fhFractionSharedpT->Fill(jet->Pt(), fraction);
      if(fMinFractionShared<0. || fraction>fMinFractionShared) {
      	 fNumberOfJets->Fill(2);
      	 fJetDet ->SetPtEtaPhiM(jet->Pt(), jet->Eta(), jet->Phi(), jet->M());
      	 fJetPart->SetPtEtaPhiM(jetP->Pt(), jetP->Eta(), jetP->Phi(), jetP->M());

      	 if(fJetDet->Pt() > fJetDetL->Pt()){
      	    fJetDetL->SetPtEtaPhiM(fJetDet->Pt(), fJetDet->Eta(), fJetDet->Phi(), fJetDet->M());
      	    fJetPartL->SetPtEtaPhiM(fJetPart->Pt(), fJetPart->Eta(), fJetPart->Phi(), fJetPart->M());

      	 }
      	 if(!fLeadingJetOnly) fTreeJets->Fill();

      }

   }
   fNAccJets->Fill(count);

   if(fLeadingJetOnly) {
      if(fJetPartL->Pt() > 0){ // fill only when there is a leading jet
      	 fTreeJets->Fill();
      }
   }

   return kTRUE;
}

//________________________________________________________________________________________________

AliAnalysisTaskPrepareInputForEmbedding::~AliAnalysisTaskPrepareInputForEmbedding() {
   /// Destructor.

 }

//________________________________________________________________________________________________

void AliAnalysisTaskPrepareInputForEmbedding::Terminate(Option_t *)
{
   /// Called once at the end of the analysis.

}
<|endoftext|>