<commit_before>//////////////////////////////////////////////////////////////////////////////
// oxygentransitionwidget.cpp
// stores event filters and maps widgets to transitions for transitions
// -------------------
//
// Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////////

#include "oxygentransitionwidget.h"

#include <cassert>
#include <QtGui/QPainter>
#include <QtGui/QPaintEvent>
#include <QStyleOption>
#include <QtCore/QCoreApplication>
#include <QtCore/QTextStream>

namespace Oxygen
{

    //________________________________________________
    bool TransitionWidget::_paintEnabled = true;
    bool TransitionWidget::paintEnabled( void )
    { return _paintEnabled; }

    int TransitionWidget::_steps = 0;

    //________________________________________________
    TransitionWidget::TransitionWidget( QWidget* parent, int duration ):
        QWidget( parent ),
        _flags( None ),
        _animation( new Animation( duration, this ) ),
        _opacity( 0 )
    {

        // background flags
        setAttribute(Qt::WA_NoSystemBackground );
        setAutoFillBackground( false );

        // setup animation
        _animation.data()->setStartValue( 0 );
        _animation.data()->setEndValue( 1.0 );
        _animation.data()->setTargetObject( this );
        _animation.data()->setPropertyName( "opacity" );

        // setup connections
        connect( _animation.data(), SIGNAL(finished()), SIGNAL(finished()) );

    }

    //________________________________________________
    QPixmap TransitionWidget::grab( QWidget* widget, QRect rect )
    {

        // change rect
        if( !rect.isValid() ) rect = widget->rect();
        if( !rect.isValid() ) return QPixmap();

        // initialize pixmap
        QPixmap out( rect.size() );
        out.fill( Qt::transparent );
        _paintEnabled = false;

        if( testFlag( GrabFromWindow ) )
        {

            rect = rect.translated( widget->mapTo( widget->window(), widget->rect().topLeft() ) );
            widget = widget->window();
            out = QPixmap::grabWidget( widget, rect );

        } else {

            if( !testFlag( Transparent ) ) { grabBackground( out, widget, rect ); }
            grabWidget( out, widget, rect );

        }

        _paintEnabled = true;

        return out;

    }

    //________________________________________________
    void TransitionWidget::paintEvent( QPaintEvent* event )
    {

        // fully transparent case
        if( opacity() >= 1.0 && endPixmap().isNull() ) return;
        if( !_paintEnabled ) return;

        // get rect
        QRect rect = event->rect();
        if( !rect.isValid() ) rect = this->rect();

        // local pixmap
        const bool paintOnWidget( testFlag( PaintOnWidget ) && !testFlag( Transparent ) );
        if( !paintOnWidget )
        {

            if( _currentPixmap.isNull() || _currentPixmap.size() != size() )
            { _currentPixmap = QPixmap( size() ); }

        }

        // fill
        _currentPixmap.fill( Qt::transparent );

        // copy local pixmap to current
        {

            QPainter p;

            // draw end pixmap first, provided that opacity is small enough
            if( opacity() >= 0.004 && !_endPixmap.isNull() )
            {

                // faded endPixmap if parent target is transparent and opacity is
                if( opacity() <= 0.996 && testFlag( Transparent ) )
                {

                    fade( _endPixmap, _currentPixmap, opacity(), rect );
                    p.begin( &_currentPixmap );
                    p.setClipRect( event->rect() );

                } else {

                    if( paintOnWidget ) p.begin( this );
                    else p.begin( &_currentPixmap );
                    p.setClipRect( event->rect() );
                    p.drawPixmap( QPoint(), _endPixmap );

                }

            } else {

                if( paintOnWidget ) p.begin( this );
                else p.begin( &_currentPixmap );
                p.setClipRect( event->rect() );

            }

            // draw fading start pixmap
            if( opacity() <= 0.996 && !_startPixmap.isNull() )
            {
                if( opacity() >= 0.004 )
                {

                    fade( _startPixmap, _localStartPixmap, 1.0-opacity(), rect );
                    p.drawPixmap( QPoint(), _localStartPixmap );

                } else p.drawPixmap( QPoint(), _startPixmap );

            }

            p.end();
        }

        // copy current pixmap on widget
        if( !paintOnWidget )
        {
            QPainter p( this );
            p.setClipRect( event->rect() );
            p.drawPixmap( QPoint(0,0), _currentPixmap );
            p.end();
        }
    }

    //________________________________________________
    void TransitionWidget::grabBackground( QPixmap& pixmap, QWidget* widget, QRect& rect ) const
    {
        if( !widget ) return;

        QWidgetList widgets;
        if( widget->autoFillBackground() )
        { widgets.push_back( widget ); }

        QWidget *parent(0);

        // get highest level parent
        for( parent = widget->parentWidget(); parent; parent = parent->parentWidget() )
        {

            if( !( parent->isVisible() && parent->rect().isValid() ) ) continue;

            // store in list
            widgets.push_back( parent );

            // stop at topLevel
            if( parent->isTopLevel() || parent->autoFillBackground() ) break;

        }

        if( !parent ) parent = widget;

        // painting
        QPainter p(&pixmap);
        p.setClipRect( rect );
        const QBrush backgroundBrush = parent->palette().brush( parent->backgroundRole());
        if( backgroundBrush.style() == Qt::TexturePattern)
        {

            p.drawTiledPixmap( rect, backgroundBrush.texture(), widget->mapTo( parent, rect.topLeft() ) );

        } else {

            p.fillRect( pixmap.rect(), backgroundBrush );

        }

        if( parent->isTopLevel() && parent->testAttribute(Qt::WA_StyledBackground))
        {
            QStyleOption option;
            option.initFrom(parent);
            option.rect = rect;
            option.rect.translate( widget->mapTo( parent, rect.topLeft() ) );
            p.translate(-option.rect.topLeft());
            parent->style()->drawPrimitive ( QStyle::PE_Widget, &option, &p, parent );
        }

        p.end();

        // draw all widgets in parent list
        // backward
        QPaintEvent event(rect);
        for( int i = widgets.size() - 1; i>=0; i-- )
        {
            QWidget* w = widgets.at(i);
            QPainter::setRedirected( w, &pixmap, widget->mapTo(w, rect.topLeft() ) );
            event = QPaintEvent(QRect( QPoint(), rect.size()));
            QCoreApplication::sendEvent(w, &event);
            QPainter::restoreRedirected(w);
        }

    }

    //________________________________________________
    void TransitionWidget::grabWidget( QPixmap& pixmap, QWidget* widget, QRect& rect ) const
    { widget->render( &pixmap, pixmap.rect().topLeft(), rect, QWidget::DrawChildren ); }

    //________________________________________________
    void TransitionWidget::fade( const QPixmap& source, QPixmap& target, qreal opacity, const QRect& rect ) const
    {

        if( target.isNull() || target.size() != size() )
        { target = QPixmap( size() ); }

        // erase target
        target.fill( Qt::transparent );

        // check opacity
        if( opacity*255 < 1 ) return;

        QPainter p( &target );
        p.setClipRect( rect );

        // draw pixmap
        p.drawPixmap( QPoint(0,0), source );

        // opacity mask (0.996 corresponds to 254/255)
        if( opacity <= 0.996 )
        {
            p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
            QColor color( Qt::black );
            color.setAlphaF( opacity );
            p.fillRect(rect, color );
        }

        p.end();
        return;
    }

}
<commit_msg>Replace deprecated in Qt4 and ignored in Qt5 setRedirected() call with render()<commit_after>//////////////////////////////////////////////////////////////////////////////
// oxygentransitionwidget.cpp
// stores event filters and maps widgets to transitions for transitions
// -------------------
//
// Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////////

#include "oxygentransitionwidget.h"

#include <cassert>
#include <QtGui/QPainter>
#include <QtGui/QPaintEvent>
#include <QStyleOption>
#include <QtCore/QCoreApplication>
#include <QtCore/QTextStream>

namespace Oxygen
{

    //________________________________________________
    bool TransitionWidget::_paintEnabled = true;
    bool TransitionWidget::paintEnabled( void )
    { return _paintEnabled; }

    int TransitionWidget::_steps = 0;

    //________________________________________________
    TransitionWidget::TransitionWidget( QWidget* parent, int duration ):
        QWidget( parent ),
        _flags( None ),
        _animation( new Animation( duration, this ) ),
        _opacity( 0 )
    {

        // background flags
        setAttribute(Qt::WA_NoSystemBackground );
        setAutoFillBackground( false );

        // setup animation
        _animation.data()->setStartValue( 0 );
        _animation.data()->setEndValue( 1.0 );
        _animation.data()->setTargetObject( this );
        _animation.data()->setPropertyName( "opacity" );

        // setup connections
        connect( _animation.data(), SIGNAL(finished()), SIGNAL(finished()) );

    }

    //________________________________________________
    QPixmap TransitionWidget::grab( QWidget* widget, QRect rect )
    {

        // change rect
        if( !rect.isValid() ) rect = widget->rect();
        if( !rect.isValid() ) return QPixmap();

        // initialize pixmap
        QPixmap out( rect.size() );
        out.fill( Qt::transparent );
        _paintEnabled = false;

        if( testFlag( GrabFromWindow ) )
        {

            rect = rect.translated( widget->mapTo( widget->window(), widget->rect().topLeft() ) );
            widget = widget->window();
            out = QPixmap::grabWidget( widget, rect );

        } else {

            if( !testFlag( Transparent ) ) { grabBackground( out, widget, rect ); }
            grabWidget( out, widget, rect );

        }

        _paintEnabled = true;

        return out;

    }

    //________________________________________________
    void TransitionWidget::paintEvent( QPaintEvent* event )
    {

        // fully transparent case
        if( opacity() >= 1.0 && endPixmap().isNull() ) return;
        if( !_paintEnabled ) return;

        // get rect
        QRect rect = event->rect();
        if( !rect.isValid() ) rect = this->rect();

        // local pixmap
        const bool paintOnWidget( testFlag( PaintOnWidget ) && !testFlag( Transparent ) );
        if( !paintOnWidget )
        {

            if( _currentPixmap.isNull() || _currentPixmap.size() != size() )
            { _currentPixmap = QPixmap( size() ); }

        }

        // fill
        _currentPixmap.fill( Qt::transparent );

        // copy local pixmap to current
        {

            QPainter p;

            // draw end pixmap first, provided that opacity is small enough
            if( opacity() >= 0.004 && !_endPixmap.isNull() )
            {

                // faded endPixmap if parent target is transparent and opacity is
                if( opacity() <= 0.996 && testFlag( Transparent ) )
                {

                    fade( _endPixmap, _currentPixmap, opacity(), rect );
                    p.begin( &_currentPixmap );
                    p.setClipRect( event->rect() );

                } else {

                    if( paintOnWidget ) p.begin( this );
                    else p.begin( &_currentPixmap );
                    p.setClipRect( event->rect() );
                    p.drawPixmap( QPoint(), _endPixmap );

                }

            } else {

                if( paintOnWidget ) p.begin( this );
                else p.begin( &_currentPixmap );
                p.setClipRect( event->rect() );

            }

            // draw fading start pixmap
            if( opacity() <= 0.996 && !_startPixmap.isNull() )
            {
                if( opacity() >= 0.004 )
                {

                    fade( _startPixmap, _localStartPixmap, 1.0-opacity(), rect );
                    p.drawPixmap( QPoint(), _localStartPixmap );

                } else p.drawPixmap( QPoint(), _startPixmap );

            }

            p.end();
        }

        // copy current pixmap on widget
        if( !paintOnWidget )
        {
            QPainter p( this );
            p.setClipRect( event->rect() );
            p.drawPixmap( QPoint(0,0), _currentPixmap );
            p.end();
        }
    }

    //________________________________________________
    void TransitionWidget::grabBackground( QPixmap& pixmap, QWidget* widget, QRect& rect ) const
    {
        if( !widget ) return;

        QWidgetList widgets;
        if( widget->autoFillBackground() )
        { widgets.push_back( widget ); }

        QWidget *parent(0);

        // get highest level parent
        for( parent = widget->parentWidget(); parent; parent = parent->parentWidget() )
        {

            if( !( parent->isVisible() && parent->rect().isValid() ) ) continue;

            // store in list
            widgets.push_back( parent );

            // stop at topLevel
            if( parent->isTopLevel() || parent->autoFillBackground() ) break;

        }

        if( !parent ) parent = widget;

        // painting
        QPainter p(&pixmap);
        p.setClipRect( rect );
        const QBrush backgroundBrush = parent->palette().brush( parent->backgroundRole());
        if( backgroundBrush.style() == Qt::TexturePattern)
        {

            p.drawTiledPixmap( rect, backgroundBrush.texture(), widget->mapTo( parent, rect.topLeft() ) );

        } else {

            p.fillRect( pixmap.rect(), backgroundBrush );

        }

        if( parent->isTopLevel() && parent->testAttribute(Qt::WA_StyledBackground))
        {
            QStyleOption option;
            option.initFrom(parent);
            option.rect = rect;
            option.rect.translate( widget->mapTo( parent, rect.topLeft() ) );
            p.translate(-option.rect.topLeft());
            parent->style()->drawPrimitive ( QStyle::PE_Widget, &option, &p, parent );
            p.translate(option.rect.topLeft());
        }

        // draw all widgets in parent list
        // backward
        QPaintEvent event(rect);
        for( int i = widgets.size() - 1; i>=0; i-- )
        {
            QWidget* w = widgets.at(i);
            w->render(&p,-widget->mapTo(w,rect.topLeft()),rect,0);
        }

    }

    //________________________________________________
    void TransitionWidget::grabWidget( QPixmap& pixmap, QWidget* widget, QRect& rect ) const
    { widget->render( &pixmap, pixmap.rect().topLeft(), rect, QWidget::DrawChildren ); }

    //________________________________________________
    void TransitionWidget::fade( const QPixmap& source, QPixmap& target, qreal opacity, const QRect& rect ) const
    {

        if( target.isNull() || target.size() != size() )
        { target = QPixmap( size() ); }

        // erase target
        target.fill( Qt::transparent );

        // check opacity
        if( opacity*255 < 1 ) return;

        QPainter p( &target );
        p.setClipRect( rect );

        // draw pixmap
        p.drawPixmap( QPoint(0,0), source );

        // opacity mask (0.996 corresponds to 254/255)
        if( opacity <= 0.996 )
        {
            p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
            QColor color( Qt::black );
            color.setAlphaF( opacity );
            p.fillRect(rect, color );
        }

        p.end();
        return;
    }

}
<|endoftext|>


<commit_before>/*
 * This program source code file is part of KICAD, a free EDA CAD application.
 *
 * Copyright (C) 1992-2010 jean-pierre.charras
 * Copyright (C) 1992-2010 Kicad Developers, see change_log.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
#include "wx/wx.h"
#include "wx/config.h"

#include "bitmap2cmp_gui_base.h"

#include "potracelib.h"
#include "bitmap_io.h"

#include "bitmap2component.xpm"

#define KEYWORD_FRAME_POSX wxT( "bmconverter_Pos_x" )
#define KEYWORD_FRAME_POSY wxT( "bmconverter_Pos_y" )
#define KEYWORD_FRAME_SIZEX wxT( "bmconverter_Size_x" )
#define KEYWORD_FRAME_SIZEY wxT( "bmconverter_Size_y" )

extern int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, int aFormat );

/* Class BM2CMP_FRAME_BASE
This is the main frame for this application
*/
class BM2CMP_FRAME : public BM2CMP_FRAME_BASE
{
private:
    wxImage   m_Pict_Image;
    wxBitmap  m_Pict_Bitmap;
    wxImage   m_Greyscale_Image;
    wxBitmap  m_Greyscale_Bitmap;
    wxImage   m_NB_Image;
    wxBitmap  m_BN_Bitmap;
    wxString  m_ImgFileName;
    wxSize m_FrameSize;
    wxPoint m_FramePos;
    wxConfig * m_Config;

public:
    BM2CMP_FRAME();
    ~BM2CMP_FRAME();

private:

    // Event handlers
    void OnPaint( wxPaintEvent& event );
    void OnLoadFile( wxCommandEvent& event );
    void OnExportEeschema( wxCommandEvent& event );
    void OnExportPcbnew( wxCommandEvent& event );
    void Binarize( int aThreshold );
	void OnOptionsSelection( wxCommandEvent& event );
	void OnThresholdChange( wxScrollEvent& event );
    void NegateGreyscaleImage( );
    void ExportFile( FILE* aOutfile, int aFormat );
};

BM2CMP_FRAME::BM2CMP_FRAME() : BM2CMP_FRAME_BASE( NULL )
{
    m_Config = new wxConfig();
    m_Config->Read( KEYWORD_FRAME_POSX, & m_FramePos.x, -1 );
    m_Config->Read( KEYWORD_FRAME_POSY, & m_FramePos.y, -1 );
    m_Config->Read( KEYWORD_FRAME_SIZEX, & m_FrameSize.x, -1 );
    m_Config->Read( KEYWORD_FRAME_SIZEY, & m_FrameSize.y, -1 );

    #ifdef __WINDOWS__
    SetIcon( wxICON( bitmap2component_icon ) );
    #else
    SetIcon( wxICON( bitmap2component ) );
    #endif

    wxString msg( wxT( "000000" ) );
    m_gridInfo->SetCellValue( 1, 0, msg );
    m_gridInfo->SetCellValue( 2, 0, msg );
    if( GetSizer() )
    {
        GetSizer()->SetSizeHints( this );
    }

    SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y );

    if ( m_FramePos == wxDefaultPosition )
        Centre();
}

BM2CMP_FRAME::~BM2CMP_FRAME()
{
    if( ( m_Config == NULL ) || IsIconized() )
        return;

    m_FrameSize = GetSize();
    m_FramePos  = GetPosition();

    m_Config->Write( KEYWORD_FRAME_POSX, (long) m_FramePos.x );
    m_Config->Write( KEYWORD_FRAME_POSY, (long) m_FramePos.y );
    m_Config->Write( KEYWORD_FRAME_SIZEX, (long) m_FrameSize.x );
    m_Config->Write( KEYWORD_FRAME_SIZEY, (long) m_FrameSize.y );

    delete m_Config;

    /* This needed for OSX: avoids furter OnDraw processing after this
     * destructor and before the native window is destroyed
     */
    this->Freeze( );
}

void BM2CMP_FRAME::OnPaint( wxPaintEvent& event )
{
    wxPaintDC pict_dc( m_InitialPicturePanel );
    wxPaintDC greyscale_dc( m_GreyscalePicturePanel );
    wxPaintDC nb_dc( m_BNPicturePanel );

    m_InitialPicturePanel->PrepareDC( pict_dc );
    m_GreyscalePicturePanel->PrepareDC( greyscale_dc );
    m_BNPicturePanel->PrepareDC( nb_dc );
    pict_dc.DrawBitmap( m_Pict_Bitmap, 0, 0, false );
    greyscale_dc.DrawBitmap( m_Greyscale_Bitmap, 0, 0, false );
    nb_dc.DrawBitmap( m_BN_Bitmap, 0, 0, false );
}

/* Called to load a bitmap file
 */
void BM2CMP_FRAME::OnLoadFile( wxCommandEvent& event )
{
    wxFileDialog FileDlg( this, _( "Choose Image" ), ::wxGetCwd(), wxEmptyString,
                          _( "Image Files " ) + wxImage::GetImageExtWildcard(),
                          wxFD_OPEN );
    int          diag = FileDlg.ShowModal();

    if( diag != wxID_OK )
        return;
    m_ImgFileName = FileDlg.GetPath();

    if( !m_Pict_Image.LoadFile( m_ImgFileName ) )
    {
        wxMessageBox( _( "Couldn't load image from '%s'." ), m_ImgFileName.c_str() );
        return;
    }

    m_Pict_Bitmap = wxBitmap( m_Pict_Image );

    int h  = m_Pict_Bitmap.GetHeight();
    int w  = m_Pict_Bitmap.GetWidth();
    int nb = m_Pict_Bitmap.GetDepth();

    wxString msg;
    msg.Printf( wxT( "%d" ), h );
    m_gridInfo->SetCellValue( 0, 0, msg );
    msg.Printf( wxT( "%d" ), w );
    m_gridInfo->SetCellValue( 1, 0, msg );
    msg.Printf( wxT( "%d" ), nb );
    m_gridInfo->SetCellValue( 2, 0, msg );

    m_InitialPicturePanel->SetVirtualSize( w, h );
    m_GreyscalePicturePanel->SetVirtualSize( w, h );
    m_BNPicturePanel->SetVirtualSize( w, h );

    m_Greyscale_Image.Destroy();
    m_Greyscale_Image = m_Pict_Image.ConvertToGreyscale( );
    if( m_rbOptions->GetSelection() > 0 )
        NegateGreyscaleImage( );
    m_Greyscale_Bitmap = wxBitmap( m_Greyscale_Image );

    m_NB_Image  = m_Greyscale_Image;
    Binarize( m_sliderThreshold->GetValue() );
    Refresh();
}

void BM2CMP_FRAME::Binarize( int aThreshold )
{
    unsigned int  pixin;
    unsigned char pixout;
    int           h = m_Greyscale_Image.GetHeight();
    int           w = m_Greyscale_Image.GetWidth();
    unsigned int  threshold = (aThreshold * 256) / 10;

    for( int y = 1; y < h; y++ )
        for( int x = 1; x < w; x++ )
        {
            pixin   = m_Greyscale_Image.GetGreen( x, y );
            if( pixin < threshold )
                pixout = 0;
            else
                pixout = 255;
            m_NB_Image.SetRGB( x, y, pixout, pixout, pixout );
        }

    m_BN_Bitmap = wxBitmap( m_NB_Image );
}

void BM2CMP_FRAME::NegateGreyscaleImage( )
{
    unsigned char  pix;
    int           h = m_Greyscale_Image.GetHeight();
    int           w = m_Greyscale_Image.GetWidth();

    for( int y = 1; y < h; y++ )
        for( int x = 1; x < w; x++ )
        {
            pix   = m_Greyscale_Image.GetGreen( x, y );
            pix = ~pix;
            m_Greyscale_Image.SetRGB( x, y, pix, pix, pix );
        }
}

/* Called on Normal/Negative change option */
void BM2CMP_FRAME::OnOptionsSelection( wxCommandEvent& event )
{
    NegateGreyscaleImage( );
    m_Greyscale_Bitmap = wxBitmap( m_Greyscale_Image );
    Binarize( m_sliderThreshold->GetValue() );
    Refresh();
}

void BM2CMP_FRAME::OnThresholdChange( wxScrollEvent& event )
{
    Binarize( m_sliderThreshold->GetValue() );
    Refresh();
}

void BM2CMP_FRAME::OnExportEeschema( wxCommandEvent& event )
{
    wxString     msg = _( "Schematic lib file (*.lib)|*.lib" );
    wxFileDialog FileDlg( this, _( "Create lib file" ), ::wxGetCwd(), wxEmptyString,
                          msg,
                          wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
    int          diag = FileDlg.ShowModal();

    if( diag != wxID_OK )
        return;
    wxString filename = FileDlg.GetPath();

    FILE*    outfile;
    outfile = wxFopen( filename, wxT( "w" ) );
    if( outfile == NULL )
    {
        wxString msg;
        msg.Printf( _( "File %s could not be created" ), filename.c_str() );
        wxMessageBox( msg );
        return;
    }

    ExportFile( outfile, 1 );
    fclose( outfile );
}

void BM2CMP_FRAME::OnExportPcbnew( wxCommandEvent& event )
{
    wxString     msg = _( "Footprint export file (*.emp)|*.emp" );
    wxFileDialog FileDlg( this, _( "Create footprint export file" ), ::wxGetCwd(), wxEmptyString,
                          msg,
                          wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
    int          diag = FileDlg.ShowModal();

    if( diag != wxID_OK )
        return;
    wxString filename = FileDlg.GetPath();

    FILE*    outfile;
    outfile = wxFopen( filename, wxT( "w" ) );
    if( outfile == NULL )
    {
        wxString msg;
        msg.Printf( _( "File %s could not be created" ), filename.c_str() );
        wxMessageBox( msg );
        return;
    }

    ExportFile( outfile, 0 );
    fclose( outfile );
}

void BM2CMP_FRAME::ExportFile( FILE* aOutfile, int aFormat )
{
    // Create a potrace bitmap
    int h = m_NB_Image.GetHeight();
    int w = m_NB_Image.GetWidth();
    potrace_bitmap_t* potrace_bitmap = bm_new( w, h );
    if( !potrace_bitmap )
    {
        wxString msg;
        msg.Printf( wxT( "Error allocating memory for potrace bitmap" ) );
        wxMessageBox( msg );
        return;
    }

    /* fill the bitmap with data */
    for( int y = 0; y<h; y++ )
    {
        for( int x = 0; x<w; x++ )
        {
            unsigned char pix = m_NB_Image.GetGreen( x, y );
            BM_PUT( potrace_bitmap, x, y, pix ? 1 : 0 );
        }
    }

    bitmap2component( potrace_bitmap, aOutfile, aFormat );
}

// BM_TO_CMP_APP

class BM_TO_CMP_APP : public wxApp
{
public:
    virtual bool OnInit();
};

IMPLEMENT_APP( BM_TO_CMP_APP )

///-----------------------------------------------------------------------------
// BM_TO_CMP_APP
// main program
//-----------------------------------------------------------------------------

bool BM_TO_CMP_APP::OnInit()
{
    wxInitAllImageHandlers();

    SetVendorName( wxT( "kicad" ) );

    wxFrame* frame = new BM2CMP_FRAME();
    frame->Show( true );

    return true;
}
<commit_msg>minor enhancement<commit_after>/*
 * This program source code file is part of KICAD, a free EDA CAD application.
 *
 * Copyright (C) 1992-2010 jean-pierre.charras
 * Copyright (C) 1992-2010 Kicad Developers, see change_log.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
#include "wx/wx.h"
#include "wx/config.h"
#include "wx/filename.h"

#include "bitmap2cmp_gui_base.h"

#include "potracelib.h"
#include "bitmap_io.h"

#include "bitmap2component.xpm"

#define KEYWORD_FRAME_POSX wxT( "Bmconverter_Pos_x" )
#define KEYWORD_FRAME_POSY wxT( "Bmconverter_Pos_y" )
#define KEYWORD_FRAME_SIZEX wxT( "Bmconverter_Size_x" )
#define KEYWORD_FRAME_SIZEY wxT( "Bmconverter_Size_y" )
#define KEYWORD_LAST_INPUT_FILE wxT( "Last_input" )
#define KEYWORD_LAST_OUTPUT_FILE wxT( "Last_output" )

extern int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, int aFormat );

/* Class BM2CMP_FRAME_BASE
This is the main frame for this application
*/
class BM2CMP_FRAME : public BM2CMP_FRAME_BASE
{
private:
    wxImage   m_Pict_Image;
    wxBitmap  m_Pict_Bitmap;
    wxImage   m_Greyscale_Image;
    wxBitmap  m_Greyscale_Bitmap;
    wxImage   m_NB_Image;
    wxBitmap  m_BN_Bitmap;
    wxString  m_BitmapFileName;
    wxString  m_ConvertedFileName;
    wxSize m_FrameSize;
    wxPoint m_FramePos;
    wxConfig * m_Config;

public:
    BM2CMP_FRAME();
    ~BM2CMP_FRAME();

private:

    // Event handlers
    void OnPaint( wxPaintEvent& event );
    void OnLoadFile( wxCommandEvent& event );
    void OnExportEeschema( wxCommandEvent& event );
    void OnExportPcbnew( wxCommandEvent& event );
    void Binarize( int aThreshold );
	void OnOptionsSelection( wxCommandEvent& event );
	void OnThresholdChange( wxScrollEvent& event );
    void NegateGreyscaleImage( );
    void ExportFile( FILE* aOutfile, int aFormat );
};

BM2CMP_FRAME::BM2CMP_FRAME() : BM2CMP_FRAME_BASE( NULL )
{
    m_Config = new wxConfig();
    m_Config->Read( KEYWORD_FRAME_POSX, & m_FramePos.x, -1 );
    m_Config->Read( KEYWORD_FRAME_POSY, & m_FramePos.y, -1 );
    m_Config->Read( KEYWORD_FRAME_SIZEX, & m_FrameSize.x, -1 );
    m_Config->Read( KEYWORD_FRAME_SIZEY, & m_FrameSize.y, -1 );
    m_Config->Read( KEYWORD_LAST_INPUT_FILE, &m_BitmapFileName );
    m_Config->Read( KEYWORD_LAST_OUTPUT_FILE, &m_ConvertedFileName );

    #ifdef __WINDOWS__
    SetIcon( wxICON( bitmap2component_icon ) );
    #else
    SetIcon( wxICON( bitmap2component ) );
    #endif

    wxString msg( wxT( "000000" ) );
    m_gridInfo->SetCellValue( 0, 0, msg );
    m_gridInfo->SetCellValue( 1, 0, msg );
    if( GetSizer() )
    {
        GetSizer()->SetSizeHints( this );
    }

    SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y );

    if ( m_FramePos == wxDefaultPosition )
        Centre();
}

BM2CMP_FRAME::~BM2CMP_FRAME()
{
    if( ( m_Config == NULL ) || IsIconized() )
        return;

    m_FrameSize = GetSize();
    m_FramePos  = GetPosition();

    m_Config->Write( KEYWORD_FRAME_POSX, (long) m_FramePos.x );
    m_Config->Write( KEYWORD_FRAME_POSY, (long) m_FramePos.y );
    m_Config->Write( KEYWORD_FRAME_SIZEX, (long) m_FrameSize.x );
    m_Config->Write( KEYWORD_FRAME_SIZEY, (long) m_FrameSize.y );
    m_Config->Write( KEYWORD_LAST_INPUT_FILE, m_BitmapFileName );
    m_Config->Write( KEYWORD_LAST_OUTPUT_FILE, m_ConvertedFileName );

    delete m_Config;

    /* This needed for OSX: avoids furter OnDraw processing after this
     * destructor and before the native window is destroyed
     */
    this->Freeze( );
}

void BM2CMP_FRAME::OnPaint( wxPaintEvent& event )
{
    wxPaintDC pict_dc( m_InitialPicturePanel );
    wxPaintDC greyscale_dc( m_GreyscalePicturePanel );
    wxPaintDC nb_dc( m_BNPicturePanel );

    m_InitialPicturePanel->PrepareDC( pict_dc );
    m_GreyscalePicturePanel->PrepareDC( greyscale_dc );
    m_BNPicturePanel->PrepareDC( nb_dc );
    pict_dc.DrawBitmap( m_Pict_Bitmap, 0, 0, false );
    greyscale_dc.DrawBitmap( m_Greyscale_Bitmap, 0, 0, false );
    nb_dc.DrawBitmap( m_BN_Bitmap, 0, 0, false );
}

/* Called to load a bitmap file
 */
void BM2CMP_FRAME::OnLoadFile( wxCommandEvent& event )
{
    wxFileName fn(m_BitmapFileName);
    wxString path = fn.GetPath();
    if( path.IsEmpty() || !wxDirExists(path) )
        path = wxGetCwd();

    wxFileDialog FileDlg( this, _( "Choose Image" ), path, wxEmptyString,
                          _( "Image Files " ) + wxImage::GetImageExtWildcard(),
                          wxFD_OPEN );
    int          diag = FileDlg.ShowModal();

    if( diag != wxID_OK )
        return;

    m_BitmapFileName = FileDlg.GetPath();

    if( !m_Pict_Image.LoadFile( m_BitmapFileName ) )
    {
        wxMessageBox( _( "Couldn't load image from <%s>" ), m_BitmapFileName.c_str() );
        return;
    }

    m_Pict_Bitmap = wxBitmap( m_Pict_Image );

    int h  = m_Pict_Bitmap.GetHeight();
    int w  = m_Pict_Bitmap.GetWidth();
    int nb = m_Pict_Bitmap.GetDepth();

    wxString msg;
    msg.Printf( wxT( "%d" ), h );
    m_gridInfo->SetCellValue( 0, 0, msg );
    msg.Printf( wxT( "%d" ), w );
    m_gridInfo->SetCellValue( 1, 0, msg );
    msg.Printf( wxT( "%d" ), nb );
    m_gridInfo->SetCellValue( 2, 0, msg );

    m_InitialPicturePanel->SetVirtualSize( w, h );
    m_GreyscalePicturePanel->SetVirtualSize( w, h );
    m_BNPicturePanel->SetVirtualSize( w, h );

    m_Greyscale_Image.Destroy();
    m_Greyscale_Image = m_Pict_Image.ConvertToGreyscale( );
    if( m_rbOptions->GetSelection() > 0 )
        NegateGreyscaleImage( );
    m_Greyscale_Bitmap = wxBitmap( m_Greyscale_Image );

    m_NB_Image  = m_Greyscale_Image;
    Binarize( m_sliderThreshold->GetValue() );
    Refresh();
}

void BM2CMP_FRAME::Binarize( int aThreshold )
{
    unsigned int  pixin;
    unsigned char pixout;
    int           h = m_Greyscale_Image.GetHeight();
    int           w = m_Greyscale_Image.GetWidth();
    unsigned int  threshold = (aThreshold * 256) / 10;

    for( int y = 1; y < h; y++ )
        for( int x = 1; x < w; x++ )
        {
            pixin   = m_Greyscale_Image.GetGreen( x, y );
            if( pixin < threshold )
                pixout = 0;
            else
                pixout = 255;
            m_NB_Image.SetRGB( x, y, pixout, pixout, pixout );
        }

    m_BN_Bitmap = wxBitmap( m_NB_Image );
}

void BM2CMP_FRAME::NegateGreyscaleImage( )
{
    unsigned char  pix;
    int           h = m_Greyscale_Image.GetHeight();
    int           w = m_Greyscale_Image.GetWidth();

    for( int y = 1; y < h; y++ )
        for( int x = 1; x < w; x++ )
        {
            pix   = m_Greyscale_Image.GetGreen( x, y );
            pix = ~pix;
            m_Greyscale_Image.SetRGB( x, y, pix, pix, pix );
        }
}

/* Called on Normal/Negative change option */
void BM2CMP_FRAME::OnOptionsSelection( wxCommandEvent& event )
{
    NegateGreyscaleImage( );
    m_Greyscale_Bitmap = wxBitmap( m_Greyscale_Image );
    Binarize( m_sliderThreshold->GetValue() );
    Refresh();
}

void BM2CMP_FRAME::OnThresholdChange( wxScrollEvent& event )
{
    Binarize( m_sliderThreshold->GetValue() );
    Refresh();
}

void BM2CMP_FRAME::OnExportEeschema( wxCommandEvent& event )
{
    wxFileName fn(m_ConvertedFileName);
    wxString path = fn.GetPath();
    if( path.IsEmpty() || !wxDirExists(path) )
        path = ::wxGetCwd();
    wxString     msg = _( "Schematic lib file (*.lib)|*.lib" );
    wxFileDialog FileDlg( this, _( "Create lib file" ), path, wxEmptyString,
                          msg,
                          wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
    int          diag = FileDlg.ShowModal();

    if( diag != wxID_OK )
        return;
    m_ConvertedFileName = FileDlg.GetPath();

    FILE*    outfile;
    outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) );
    if( outfile == NULL )
    {
        wxString msg;
        msg.Printf( _( "File %s could not be created" ), m_ConvertedFileName.c_str() );
        wxMessageBox( msg );
        return;
    }

    ExportFile( outfile, 1 );
    fclose( outfile );
}

void BM2CMP_FRAME::OnExportPcbnew( wxCommandEvent& event )
{
    wxFileName fn(m_ConvertedFileName);
    wxString path = fn.GetPath();
    if( path.IsEmpty() || !wxDirExists(path) )
        path = ::wxGetCwd();
    wxString     msg = _( "Footprint export file (*.emp)|*.emp" );
    wxFileDialog FileDlg( this, _( "Create footprint export file" ), path, wxEmptyString,
                          msg,
                          wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
    int          diag = FileDlg.ShowModal();

    if( diag != wxID_OK )
        return;
    m_ConvertedFileName = FileDlg.GetPath();

    FILE*    outfile;
    outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) );
    if( outfile == NULL )
    {
        wxString msg;
        msg.Printf( _( "File %s could not be created" ), m_ConvertedFileName.c_str() );
        wxMessageBox( msg );
        return;
    }

    ExportFile( outfile, 0 );
    fclose( outfile );
}

void BM2CMP_FRAME::ExportFile( FILE* aOutfile, int aFormat )
{
    // Create a potrace bitmap
    int h = m_NB_Image.GetHeight();
    int w = m_NB_Image.GetWidth();
    potrace_bitmap_t* potrace_bitmap = bm_new( w, h );
    if( !potrace_bitmap )
    {
        wxString msg;
        msg.Printf( wxT( "Error allocating memory for potrace bitmap" ) );
        wxMessageBox( msg );
        return;
    }

    /* fill the bitmap with data */
    for( int y = 0; y<h; y++ )
    {
        for( int x = 0; x<w; x++ )
        {
            unsigned char pix = m_NB_Image.GetGreen( x, y );
            BM_PUT( potrace_bitmap, x, y, pix ? 1 : 0 );
        }
    }

    bitmap2component( potrace_bitmap, aOutfile, aFormat );
}

// BM_TO_CMP_APP

class BM_TO_CMP_APP : public wxApp
{
public:
    virtual bool OnInit();
};

IMPLEMENT_APP( BM_TO_CMP_APP )

///-----------------------------------------------------------------------------
// BM_TO_CMP_APP
// main program
//-----------------------------------------------------------------------------

bool BM_TO_CMP_APP::OnInit()
{
    wxInitAllImageHandlers();

    SetVendorName( wxT( "kicad" ) );

    wxFrame* frame = new BM2CMP_FRAME();
    frame->Show( true );

    return true;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: partwnd.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: as $ $Date: 2001-11-28 11:22:48 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

// includes ******************************************************************

#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif

#include <toolkit/helper/vclunohelper.hxx>

#include "sfxsids.hrc"
#include "partwnd.hxx"
#include "bindings.hxx"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "frame.hxx"
#include "sfxuno.hxx"

/*
// class SfxPartwinFrame_Impl ------------------------------------------

class SfxPartwinFrame_Impl : public SfxUnoFrame
{
public:
    SfxPopupStatusIndicator*        pIndicator;
    SfxPartDockWnd_Impl*            pBeamer;

    virtual void     SAL_CALL               initialize(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > & aPeer) throw ( ::com::sun::star::uno::RuntimeException );
    virtual SfxFrame*               CreateFrame( Window* pParent );
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator >   SAL_CALL     getStatusIndicator(void) throw ( ::com::sun::star::uno::RuntimeException );
    void                            dispatch_Impl( const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
};

// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL SfxPartwinFrame_Impl::getStatusIndicator(void) throw ( ::com::sun::star::uno::RuntimeException )
{
    return pIndicator->GetInterface();
}

void SfxPartwinFrame_Impl::dispatch_Impl( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs )
{
    if ( !pBeamer )
        return;

    if ( rURL.Protocol.compareToAscii(".uno:") == 0 )
    {
        if ( rURL.Path.compareToAscii("Reload") == 0)
        {
            SfxUnoFrame::dispatch_Impl( rURL, rArgs );
            if ( pBeamer->IsAutoHide_Impl() )
                pBeamer->AutoShow_Impl( sal_True );
            return;
        }
    }
    else
        SfxUnoFrame::dispatch_Impl( rURL, rArgs );

    if ( rURL.Complete.len() )
    {
        if ( pBeamer->IsAutoHide_Impl() )
            pBeamer->AutoShow_Impl( sal_True );
    }
    else
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >  xTmp( this );
        SfxApplication* pApp = SFX_APP();
        pApp->SetChildWindow( SID_BROWSER, sal_False );
        pApp->GetBindings().Invalidate( SID_BROWSER );
    }
}

// -----------------------------------------------------------------------
void SAL_CALL SfxPartwinFrame_Impl::initialize( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > & aWindow ) throw ( ::com::sun::star::uno::RuntimeException )
{
    setName( rtl::OUString::createFromAscii("_partwindow") );
    SetContainerWindow_Impl( aWindow );
}

// -----------------------------------------------------------------------
SfxFrame* SfxPartwinFrame_Impl::CreateFrame( Window* pParent )
{
    return NULL;
}

*/

//****************************************************************************
// SfxPartChildWnd_Impl
//****************************************************************************

SFX_IMPL_DOCKINGWINDOW( SfxPartChildWnd_Impl, SID_BROWSER );

SfxPartChildWnd_Impl::SfxPartChildWnd_Impl
(
    Window* pParent,
    sal_uInt16 nId,
    SfxBindings* pBindings,
    SfxChildWinInfo* pInfo
)
    : SfxChildWindow( pParent, nId )
{
    // Window erzeugen
    pWindow = new SfxPartDockWnd_Impl( pBindings, this, pParent, WB_STDDOCKWIN | WB_CLIPCHILDREN | WB_SIZEABLE | WB_3DLOOK );
    eChildAlignment = SFX_ALIGN_TOP;
    ((SfxDockingWindow*)pWindow)->SetFloatingSize( Size( 240, 240 ) );
    pWindow->SetSizePixel( Size( 240, 240 ) );

    ( ( SfxDockingWindow* ) pWindow )->Initialize( pInfo );
}

SfxPartChildWnd_Impl::~SfxPartChildWnd_Impl()
{
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = GetFrame();

    // If xFrame=NULL release pMgr! Because this window lives longer then the manager!
    // In these case we got a xFrame->dispose() call from outside ... and has release our
    // frame reference in our own DisposingListener.
    // But don't do it, if xFrame already exist. Then dispose() must come from inside ...
    // and we need a valid pMgr for further operations ...
    SfxPartDockWnd_Impl* pWin = (SfxPartDockWnd_Impl*) pWindow;
    if( pWin != NULL && !xFrame.is() )
        pWin->ReleaseChildWindow_Impl();

    // Release frame and window.
    // If frame reference is valid here ... start dieing from inside by calling dispose().
    SetFrame( NULL );
    pWindow = NULL;
    if( xFrame.is() )
        xFrame->dispose();
}

sal_Bool SfxPartChildWnd_Impl::QueryClose()
{
    return ( (SfxPartDockWnd_Impl*)pWindow )->QueryClose();
}

//****************************************************************************
// SfxPartDockWnd_Impl
//****************************************************************************

SfxPartDockWnd_Impl::SfxPartDockWnd_Impl
(
    SfxBindings* pBindings,
    SfxChildWindow* pChildWin,
    Window* pParent,
    WinBits nBits
)
    : SfxDockingWindow( pBindings, pChildWin, pParent, nBits )
{
    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > xFrame(
            ::comphelper::getProcessServiceFactory()->createInstance(
            DEFINE_CONST_UNICODE("com.sun.star.frame.Frame") ), ::com::sun::star::uno::UNO_QUERY );
    xFrame->initialize( VCLUnoHelper::GetInterface ( this ) );
    pChildWin->SetFrame( xFrame );
    if ( pBindings->GetDispatcher() )
    {
        ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFramesSupplier >
                xSupp ( pBindings->GetDispatcher()->GetFrame()->GetFrame()->GetFrameInterface(), ::com::sun::star::uno::UNO_QUERY );
        if ( xSupp.is() )
            xSupp->getFrames()->append( xFrame );
    }
    else
        DBG_ERROR("Bindings without Dispatcher!");
}

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

SfxPartDockWnd_Impl::~SfxPartDockWnd_Impl()
{
}

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

Rectangle impl_Rectangle_Struct2Object( const ::com::sun::star::awt::Rectangle& aRectangleStruct )
{
    return Rectangle(aRectangleStruct.X,aRectangleStruct.Y,aRectangleStruct.Width,aRectangleStruct.Height);
}

void SfxPartDockWnd_Impl::Resize()

/*  [Beschreibung]
    Anpassung der Gr"osse der Controls an die neue Windowgr"osse
*/

{
    SfxDockingWindow::Resize();
}

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

sal_Bool SfxPartDockWnd_Impl::QueryClose()
{
    sal_Bool bClose = sal_True;
    SfxChildWindow* pChild = GetChildWindow_Impl();
    if( pChild )
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = pChild->GetFrame();
        if( xFrame.is() )
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >  xCtrl = xFrame->getController();
            if( xCtrl.is() )
                bClose = xCtrl->suspend( sal_True );
        }
    }

    return bClose;
}

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

long SfxPartDockWnd_Impl::Notify( NotifyEvent& rEvt )
{
    if( rEvt.GetType() == EVENT_GETFOCUS )
    {
        SfxChildWindow* pChild = GetChildWindow_Impl();
        if( pChild )
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = pChild->GetFrame();
            if( xFrame.is() )
                xFrame->activate();
        }
    }

    return SfxDockingWindow::Notify( rEvt );
}

void SfxPartDockWnd_Impl::FillInfo( SfxChildWinInfo& rInfo ) const
{
    SfxDockingWindow::FillInfo( rInfo );
    rInfo.bVisible = sal_False;
}

<commit_msg>#96252# 'better' beamer dispose<commit_after>/*************************************************************************
 *
 *  $RCSfile: partwnd.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: as $ $Date: 2002-01-07 12:12:09 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

// includes ******************************************************************

#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif

#include <toolkit/helper/vclunohelper.hxx>

#include "sfxsids.hrc"
#include "partwnd.hxx"
#include "bindings.hxx"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "frame.hxx"
#include "sfxuno.hxx"

/*
// class SfxPartwinFrame_Impl ------------------------------------------

class SfxPartwinFrame_Impl : public SfxUnoFrame
{
public:
    SfxPopupStatusIndicator*        pIndicator;
    SfxPartDockWnd_Impl*            pBeamer;

    virtual void     SAL_CALL               initialize(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > & aPeer) throw ( ::com::sun::star::uno::RuntimeException );
    virtual SfxFrame*               CreateFrame( Window* pParent );
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator >   SAL_CALL     getStatusIndicator(void) throw ( ::com::sun::star::uno::RuntimeException );
    void                            dispatch_Impl( const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
};

// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL SfxPartwinFrame_Impl::getStatusIndicator(void) throw ( ::com::sun::star::uno::RuntimeException )
{
    return pIndicator->GetInterface();
}

void SfxPartwinFrame_Impl::dispatch_Impl( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs )
{
    if ( !pBeamer )
        return;

    if ( rURL.Protocol.compareToAscii(".uno:") == 0 )
    {
        if ( rURL.Path.compareToAscii("Reload") == 0)
        {
            SfxUnoFrame::dispatch_Impl( rURL, rArgs );
            if ( pBeamer->IsAutoHide_Impl() )
                pBeamer->AutoShow_Impl( sal_True );
            return;
        }
    }
    else
        SfxUnoFrame::dispatch_Impl( rURL, rArgs );

    if ( rURL.Complete.len() )
    {
        if ( pBeamer->IsAutoHide_Impl() )
            pBeamer->AutoShow_Impl( sal_True );
    }
    else
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >  xTmp( this );
        SfxApplication* pApp = SFX_APP();
        pApp->SetChildWindow( SID_BROWSER, sal_False );
        pApp->GetBindings().Invalidate( SID_BROWSER );
    }
}

// -----------------------------------------------------------------------
void SAL_CALL SfxPartwinFrame_Impl::initialize( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > & aWindow ) throw ( ::com::sun::star::uno::RuntimeException )
{
    setName( rtl::OUString::createFromAscii("_partwindow") );
    SetContainerWindow_Impl( aWindow );
}

// -----------------------------------------------------------------------
SfxFrame* SfxPartwinFrame_Impl::CreateFrame( Window* pParent )
{
    return NULL;
}

*/

//****************************************************************************
// SfxPartChildWnd_Impl
//****************************************************************************

SFX_IMPL_DOCKINGWINDOW( SfxPartChildWnd_Impl, SID_BROWSER );

SfxPartChildWnd_Impl::SfxPartChildWnd_Impl
(
    Window* pParent,
    sal_uInt16 nId,
    SfxBindings* pBindings,
    SfxChildWinInfo* pInfo
)
    : SfxChildWindow( pParent, nId )
{
    // Window erzeugen
    pWindow = new SfxPartDockWnd_Impl( pBindings, this, pParent, WB_STDDOCKWIN | WB_CLIPCHILDREN | WB_SIZEABLE | WB_3DLOOK );
    eChildAlignment = SFX_ALIGN_TOP;
    ((SfxDockingWindow*)pWindow)->SetFloatingSize( Size( 240, 240 ) );
    pWindow->SetSizePixel( Size( 240, 240 ) );

    ( ( SfxDockingWindow* ) pWindow )->Initialize( pInfo );
}

SfxPartChildWnd_Impl::~SfxPartChildWnd_Impl()
{
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = GetFrame();

    // If xFrame=NULL release pMgr! Because this window lives longer then the manager!
    // In these case we got a xFrame->dispose() call from outside ... and has release our
    // frame reference in our own DisposingListener.
    // But don't do it, if xFrame already exist. Then dispose() must come from inside ...
    // and we need a valid pMgr for further operations ...
    SfxPartDockWnd_Impl* pWin = (SfxPartDockWnd_Impl*) pWindow;
    if( pWin != NULL && !xFrame.is() )
        pWin->ReleaseChildWindow_Impl();

    // Release frame and window.
    // If frame reference is valid here ... start dieing from inside by calling dispose().
    SetFrame( NULL );
    pWindow = NULL;
    if ( pWin && xFrame == pWin->GetBindings().GetActiveFrame() )
        pWin->GetBindings().SetActiveFrame( GetFrame() );
    if( xFrame.is() )
        xFrame->dispose();
}

sal_Bool SfxPartChildWnd_Impl::QueryClose()
{
    return ( (SfxPartDockWnd_Impl*)pWindow )->QueryClose();
}

//****************************************************************************
// SfxPartDockWnd_Impl
//****************************************************************************

SfxPartDockWnd_Impl::SfxPartDockWnd_Impl
(
    SfxBindings* pBindings,
    SfxChildWindow* pChildWin,
    Window* pParent,
    WinBits nBits
)
    : SfxDockingWindow( pBindings, pChildWin, pParent, nBits )
{
    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > xFrame(
            ::comphelper::getProcessServiceFactory()->createInstance(
            DEFINE_CONST_UNICODE("com.sun.star.frame.Frame") ), ::com::sun::star::uno::UNO_QUERY );
    xFrame->initialize( VCLUnoHelper::GetInterface ( this ) );
    pChildWin->SetFrame( xFrame );
    if ( pBindings->GetDispatcher() )
    {
        ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFramesSupplier >
                xSupp ( pBindings->GetDispatcher()->GetFrame()->GetFrame()->GetFrameInterface(), ::com::sun::star::uno::UNO_QUERY );
        if ( xSupp.is() )
            xSupp->getFrames()->append( xFrame );
    }
    else
        DBG_ERROR("Bindings without Dispatcher!");
}

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

SfxPartDockWnd_Impl::~SfxPartDockWnd_Impl()
{
}

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

Rectangle impl_Rectangle_Struct2Object( const ::com::sun::star::awt::Rectangle& aRectangleStruct )
{
    return Rectangle(aRectangleStruct.X,aRectangleStruct.Y,aRectangleStruct.Width,aRectangleStruct.Height);
}

void SfxPartDockWnd_Impl::Resize()

/*  [Beschreibung]
    Anpassung der Gr"osse der Controls an die neue Windowgr"osse
*/

{
    SfxDockingWindow::Resize();
}

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

sal_Bool SfxPartDockWnd_Impl::QueryClose()
{
    sal_Bool bClose = sal_True;
    SfxChildWindow* pChild = GetChildWindow_Impl();
    if( pChild )
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = pChild->GetFrame();
        if( xFrame.is() )
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >  xCtrl = xFrame->getController();
            if( xCtrl.is() )
                bClose = xCtrl->suspend( sal_True );
        }
    }

    return bClose;
}

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

long SfxPartDockWnd_Impl::Notify( NotifyEvent& rEvt )
{
    if( rEvt.GetType() == EVENT_GETFOCUS )
    {
        SfxChildWindow* pChild = GetChildWindow_Impl();
        if( pChild )
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = pChild->GetFrame();
            if( xFrame.is() )
                xFrame->activate();
        }
    }

    return SfxDockingWindow::Notify( rEvt );
}

void SfxPartDockWnd_Impl::FillInfo( SfxChildWinInfo& rInfo ) const
{
    SfxDockingWindow::FillInfo( rInfo );
    rInfo.bVisible = sal_False;
}

<|endoftext|>


<commit_before>// Copyright (c) 2019 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chain.h>
#include <chainparams.h>
#include <consensus/activation.h>
#include <util/system.h>

#include <test/util/setup_common.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(activation_tests, BasicTestingSetup)

static void SetMTP(std::array<CBlockIndex, 12> &blocks, int64_t mtp) {
    size_t len = blocks.size();

    for (size_t i = 0; i < len; ++i) {
        blocks[i].nTime = mtp + (i - (len / 2));
    }

    BOOST_CHECK_EQUAL(blocks.back().GetMedianTimePast(), mtp);
}

BOOST_AUTO_TEST_CASE(isgravitonenabled) {
    const auto params = CreateChainParams(CBaseChainParams::MAIN);
    const auto &consensus = params->GetConsensus();

    BOOST_CHECK(!IsGravitonEnabled(consensus, nullptr));

    std::array<CBlockIndex, 4> blocks;
    blocks[0].nHeight = consensus.gravitonHeight - 2;
    for (size_t i = 1; i < blocks.size(); ++i) {
        blocks[i].pprev = &blocks[i - 1];
        blocks[i].nHeight = blocks[i - 1].nHeight + 1;
    }
    BOOST_CHECK(!IsGravitonEnabled(consensus, &blocks[0]));
    BOOST_CHECK(!IsGravitonEnabled(consensus, &blocks[1]));
    BOOST_CHECK(IsGravitonEnabled(consensus, &blocks[2]));
    BOOST_CHECK(IsGravitonEnabled(consensus, &blocks[3]));
}

BOOST_AUTO_TEST_CASE(isphononenabled) {
    const Consensus::Params &consensus = Params().GetConsensus();
    BOOST_CHECK(!IsPhononEnabled(consensus, nullptr));

    std::array<CBlockIndex, 4> blocks;
    blocks[0].nHeight = consensus.phononHeight - 2;
    for (size_t i = 1; i < blocks.size(); ++i) {
        blocks[i].pprev = &blocks[i - 1];
        blocks[i].nHeight = blocks[i - 1].nHeight + 1;
    }
    BOOST_CHECK(!IsPhononEnabled(consensus, &blocks[0]));
    BOOST_CHECK(!IsPhononEnabled(consensus, &blocks[1]));
    BOOST_CHECK(IsPhononEnabled(consensus, &blocks[2]));
    BOOST_CHECK(IsPhononEnabled(consensus, &blocks[3]));
}

BOOST_AUTO_TEST_CASE(isaxionenabled) {
    const Consensus::Params &params = Params().GetConsensus();
    const auto activation =
        gArgs.GetArg("-axionactivationtime", params.axionActivationTime);
    SetMockTime(activation - 1000000);

    BOOST_CHECK(!IsAxionEnabled(params, nullptr));

    std::array<CBlockIndex, 12> blocks;
    for (size_t i = 1; i < blocks.size(); ++i) {
        blocks[i].pprev = &blocks[i - 1];
    }
    BOOST_CHECK(!IsAxionEnabled(params, &blocks.back()));

    SetMTP(blocks, activation - 1);
    BOOST_CHECK(!IsAxionEnabled(params, &blocks.back()));

    SetMTP(blocks, activation);
    BOOST_CHECK(IsAxionEnabled(params, &blocks.back()));

    SetMTP(blocks, activation + 1);
    BOOST_CHECK(IsAxionEnabled(params, &blocks.back()));
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>[refactor] extract function for past activation tests<commit_after>// Copyright (c) 2019 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chain.h>
#include <chainparams.h>
#include <consensus/activation.h>
#include <util/system.h>

#include <test/util/setup_common.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(activation_tests, BasicTestingSetup)

static void SetMTP(std::array<CBlockIndex, 12> &blocks, int64_t mtp) {
    size_t len = blocks.size();

    for (size_t i = 0; i < len; ++i) {
        blocks[i].nTime = mtp + (i - (len / 2));
    }

    BOOST_CHECK_EQUAL(blocks.back().GetMedianTimePast(), mtp);
}

static void testPastActivation(
    std::function<bool(const Consensus::Params &, const CBlockIndex *)> func,
    const Consensus::Params &params, int activationHeight) {
    BOOST_CHECK(!func(params, nullptr));

    std::array<CBlockIndex, 4> blocks;
    blocks[0].nHeight = activationHeight - 2;
    for (size_t i = 1; i < blocks.size(); ++i) {
        blocks[i].pprev = &blocks[i - 1];
        blocks[i].nHeight = blocks[i - 1].nHeight + 1;
    }

    BOOST_CHECK(!func(params, &blocks[0]));
    BOOST_CHECK(!func(params, &blocks[1]));
    BOOST_CHECK(func(params, &blocks[2]));
    BOOST_CHECK(func(params, &blocks[3]));
}

BOOST_AUTO_TEST_CASE(test_previous_activations_by_height) {
    const auto params = CreateChainParams(CBaseChainParams::MAIN);
    const auto consensus = params->GetConsensus();

    testPastActivation(IsGravitonEnabled, consensus, consensus.gravitonHeight);
    testPastActivation(IsPhononEnabled, consensus, consensus.phononHeight);
}

BOOST_AUTO_TEST_CASE(isaxionenabled) {
    const Consensus::Params &params = Params().GetConsensus();
    const auto activation =
        gArgs.GetArg("-axionactivationtime", params.axionActivationTime);
    SetMockTime(activation - 1000000);

    BOOST_CHECK(!IsAxionEnabled(params, nullptr));

    std::array<CBlockIndex, 12> blocks;
    for (size_t i = 1; i < blocks.size(); ++i) {
        blocks[i].pprev = &blocks[i - 1];
    }
    BOOST_CHECK(!IsAxionEnabled(params, &blocks.back()));

    SetMTP(blocks, activation - 1);
    BOOST_CHECK(!IsAxionEnabled(params, &blocks.back()));

    SetMTP(blocks, activation);
    BOOST_CHECK(IsAxionEnabled(params, &blocks.back()));

    SetMTP(blocks, activation + 1);
    BOOST_CHECK(IsAxionEnabled(params, &blocks.back()));
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgstreamercaptureservice_maemo.h"
#include "qgstreamercapturesession_maemo.h"
#include "qgstreamerrecordercontrol_maemo.h"
#include "qgstreamermediacontainercontrol_maemo.h"
#include "qgstreameraudioencode_maemo.h"
#include "qgstreamervideoencode_maemo.h"
#include "qgstreamerbushelper.h"
#include "qgstreamercapturemetadatacontrol_maemo.h"

#include "qgstreameraudioinputendpointselector.h"
#include "qgstreamervideoinputdevicecontrol.h"

#include "qgstreamervideooverlay.h"
#include "qgstreamervideorenderer.h"

#include "qgstreamervideowidget.h"

#include <qmediaserviceprovider.h>

#include <QtCore/qdebug.h>

class QGstreamerVideoRendererWrapper : public QGstreamerElementFactory
{
public:
    QGstreamerVideoRendererWrapper(QGstreamerVideoRendererInterface *videoRenderer)
        :m_videoRenderer(videoRenderer),
         m_bin(0),
         m_element(0),
         m_colorspace(0)
    {
    }

    virtual ~QGstreamerVideoRendererWrapper()
    {
        if (m_bin)
            gst_object_unref(GST_OBJECT(m_bin));
    }

    GstElement *buildElement()
    {
#ifdef Q_WS_MAEMO_5
        return m_element = m_videoRenderer->videoSink();
#endif
        if (m_bin == NULL) {
            GstBin * bin = GST_BIN(gst_bin_new(NULL));

            m_colorspace = gst_element_factory_make("ffmpegcolorspace", NULL);
            m_element = m_videoRenderer->videoSink();

            gst_bin_add(bin, m_colorspace);
            gst_bin_add(bin, m_element);
            gst_element_link(m_colorspace, m_element);

            // add ghostpads
            GstPad *pad = gst_element_get_static_pad(m_colorspace, "sink");
            gst_element_add_pad(GST_ELEMENT(bin), gst_ghost_pad_new("sink", pad));
            gst_object_unref(GST_OBJECT(pad));

            m_bin = GST_ELEMENT(bin);
        }

        m_videoRenderer->precessNewStream();

        gst_object_ref(GST_OBJECT(m_bin));
        return m_bin;
    }

    void prepareWinId()
    {
        m_videoRenderer->precessNewStream();
    }

private:
    QGstreamerVideoRendererInterface *m_videoRenderer;

    GstElement *m_bin;
    GstElement *m_element;
    GstElement *m_colorspace;
};

QGstreamerCaptureService::QGstreamerCaptureService(const QString &service, QObject *parent):
    QMediaService(parent)
{
    static bool initialized = false;
    if (!initialized) {
        initialized = true;
        gst_init(NULL, NULL);
    }

    m_captureSession = 0;
    m_cameraControl = 0;
    m_metaDataControl = 0;

    m_audioInputEndpointSelector = 0;
    m_videoInputDevice = 0;

    m_videoRenderer = 0;
    m_videoRendererFactory = 0;
    m_videoWindow = 0;
    m_videoWindowFactory = 0;
    m_videoWidgetControl = 0;
    m_videoWidgetFactory = 0;
    m_imageCaptureControl = 0;

    if (service == Q_MEDIASERVICE_AUDIOSOURCE) {
        m_captureSession = new QGstreamerCaptureSession(QGstreamerCaptureSession::Audio, this);
    }

    bool captureVideo = false;

    if (captureVideo) {
        m_captureSession = new QGstreamerCaptureSession(QGstreamerCaptureSession::AudioAndVideo, this);
        //TODO:m_captureSession->setVideoInput(m_cameraControl);
        m_videoInputDevice = new QGstreamerVideoInputDeviceControl(m_captureSession);

        //TODO:connect(m_videoInputDevice, SIGNAL(selectedDeviceChanged(QString)),
        //        m_cameraControl, SLOT(setDevice(QString)));

        //TODO:if (m_videoInputDevice->deviceCount())
        //    m_cameraControl->setDevice(m_videoInputDevice->deviceName(m_videoInputDevice->selectedDevice()));

        m_videoRenderer = new QGstreamerVideoRenderer(this);
        m_videoRendererFactory = new QGstreamerVideoRendererWrapper(m_videoRenderer);
        m_videoWindow = new QGstreamerVideoOverlay(this);
        m_videoWindowFactory = new QGstreamerVideoRendererWrapper(m_videoWindow);

        m_videoWidgetControl = new QGstreamerVideoWidgetControl(this);
        m_videoWidgetFactory = new QGstreamerVideoRendererWrapper(m_videoWidgetControl);

    }

    if (!m_captureSession) {
        qWarning() << "Service type is not supported:" << service;
        return;
    }

    m_audioInputEndpointSelector = new QGstreamerAudioInputEndpointSelector(this);
    connect(m_audioInputEndpointSelector, SIGNAL(activeEndpointChanged(QString)), m_captureSession, SLOT(setCaptureDevice(QString)));

    if (m_captureSession && m_audioInputEndpointSelector->availableEndpoints().size() > 0)
        m_captureSession->setCaptureDevice(m_audioInputEndpointSelector->defaultEndpoint());

    m_metaDataControl = new QGstreamerCaptureMetaDataControl(this);
    connect(m_metaDataControl, SIGNAL(metaDataChanged(QMap<QByteArray,QVariant>)),
            m_captureSession, SLOT(setMetaData(QMap<QByteArray,QVariant>)));
}

QGstreamerCaptureService::~QGstreamerCaptureService()
{
}

QMediaControl *QGstreamerCaptureService::requestControl(const char *name)
{
    if (qstrcmp(name, QVideoRendererControl_iid) == 0)
        return m_videoRenderer;

    if (qstrcmp(name, QVideoWindowControl_iid) == 0)
        return m_videoWindow;

    if (qstrcmp(name, QVideoWidgetControl_iid) == 0)
        return m_videoWidgetControl;

    if (qstrcmp(name,QAudioEndpointSelector_iid) == 0)
        return m_audioInputEndpointSelector;

    if (qstrcmp(name,QVideoDeviceControl_iid) == 0)
        return m_videoInputDevice;

    if (qstrcmp(name,QMediaRecorderControl_iid) == 0)
        return m_captureSession->recorderControl();

    if (qstrcmp(name,QAudioEncoderControl_iid) == 0)
        return m_captureSession->audioEncodeControl();

    if (qstrcmp(name,QVideoEncoderControl_iid) == 0)
        return m_captureSession->videoEncodeControl();

    if (qstrcmp(name,QMediaContainerControl_iid) == 0)
        return m_captureSession->mediaContainerControl();

    if (qstrcmp(name,QMetaDataWriterControl_iid) == 0)
        return m_metaDataControl;

    return 0;
}

void QGstreamerCaptureService::releaseControl(QMediaControl *control)
{
    if (control && control == m_videoOutput) {
        m_videoOutput = 0;
        m_captureSession->setVideoPreview(0);
    }
}

<commit_msg>Updated maemo capture service with controls API changes.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgstreamercaptureservice_maemo.h"
#include "qgstreamercapturesession_maemo.h"
#include "qgstreamerrecordercontrol_maemo.h"
#include "qgstreamermediacontainercontrol_maemo.h"
#include "qgstreameraudioencode_maemo.h"
#include "qgstreamervideoencode_maemo.h"
#include "qgstreamerbushelper.h"
#include "qgstreamercapturemetadatacontrol_maemo.h"

#include "qgstreameraudioinputendpointselector.h"
#include "qgstreamervideoinputdevicecontrol.h"

#include "qgstreamervideooverlay.h"
#include "qgstreamervideorenderer.h"

#include "qgstreamervideowidget.h"

#include <qmediaserviceprovider.h>

#include <QtCore/qdebug.h>

class QGstreamerVideoRendererWrapper : public QGstreamerElementFactory
{
public:
    QGstreamerVideoRendererWrapper(QGstreamerVideoRendererInterface *videoRenderer)
        :m_videoRenderer(videoRenderer),
         m_bin(0),
         m_element(0),
         m_colorspace(0)
    {
    }

    virtual ~QGstreamerVideoRendererWrapper()
    {
        if (m_bin)
            gst_object_unref(GST_OBJECT(m_bin));
    }

    GstElement *buildElement()
    {
#ifdef Q_WS_MAEMO_5
        return m_element = m_videoRenderer->videoSink();
#endif
        if (m_bin == NULL) {
            GstBin * bin = GST_BIN(gst_bin_new(NULL));

            m_colorspace = gst_element_factory_make("ffmpegcolorspace", NULL);
            m_element = m_videoRenderer->videoSink();

            gst_bin_add(bin, m_colorspace);
            gst_bin_add(bin, m_element);
            gst_element_link(m_colorspace, m_element);

            // add ghostpads
            GstPad *pad = gst_element_get_static_pad(m_colorspace, "sink");
            gst_element_add_pad(GST_ELEMENT(bin), gst_ghost_pad_new("sink", pad));
            gst_object_unref(GST_OBJECT(pad));

            m_bin = GST_ELEMENT(bin);
        }

        m_videoRenderer->precessNewStream();

        gst_object_ref(GST_OBJECT(m_bin));
        return m_bin;
    }

    void prepareWinId()
    {
        m_videoRenderer->precessNewStream();
    }

private:
    QGstreamerVideoRendererInterface *m_videoRenderer;

    GstElement *m_bin;
    GstElement *m_element;
    GstElement *m_colorspace;
};

QGstreamerCaptureService::QGstreamerCaptureService(const QString &service, QObject *parent):
    QMediaService(parent)
{
    static bool initialized = false;
    if (!initialized) {
        initialized = true;
        gst_init(NULL, NULL);
    }

    m_captureSession = 0;
    m_cameraControl = 0;
    m_metaDataControl = 0;

    m_audioInputEndpointSelector = 0;
    m_videoInputDevice = 0;

    m_videoRenderer = 0;
    m_videoRendererFactory = 0;
    m_videoWindow = 0;
    m_videoWindowFactory = 0;
    m_videoWidgetControl = 0;
    m_videoWidgetFactory = 0;
    m_imageCaptureControl = 0;

    if (service == Q_MEDIASERVICE_AUDIOSOURCE) {
        m_captureSession = new QGstreamerCaptureSession(QGstreamerCaptureSession::Audio, this);
    }

    bool captureVideo = false;

    if (captureVideo) {
        m_captureSession = new QGstreamerCaptureSession(QGstreamerCaptureSession::AudioAndVideo, this);
        //TODO:m_captureSession->setVideoInput(m_cameraControl);
        m_videoInputDevice = new QGstreamerVideoInputDeviceControl(m_captureSession);

        //TODO:connect(m_videoInputDevice, SIGNAL(selectedDeviceChanged(QString)),
        //        m_cameraControl, SLOT(setDevice(QString)));

        //TODO:if (m_videoInputDevice->deviceCount())
        //    m_cameraControl->setDevice(m_videoInputDevice->deviceName(m_videoInputDevice->selectedDevice()));

        m_videoRenderer = new QGstreamerVideoRenderer(this);
        m_videoRendererFactory = new QGstreamerVideoRendererWrapper(m_videoRenderer);
        m_videoWindow = new QGstreamerVideoOverlay(this);
        m_videoWindowFactory = new QGstreamerVideoRendererWrapper(m_videoWindow);

        m_videoWidgetControl = new QGstreamerVideoWidgetControl(this);
        m_videoWidgetFactory = new QGstreamerVideoRendererWrapper(m_videoWidgetControl);
    }

    if (!m_captureSession) {
        qWarning() << "Service type is not supported:" << service;
        return;
    }

    m_audioInputEndpointSelector = new QGstreamerAudioInputEndpointSelector(this);
    connect(m_audioInputEndpointSelector, SIGNAL(activeEndpointChanged(QString)), m_captureSession, SLOT(setCaptureDevice(QString)));

    if (m_captureSession && m_audioInputEndpointSelector->availableEndpoints().size() > 0)
        m_captureSession->setCaptureDevice(m_audioInputEndpointSelector->defaultEndpoint());

    m_metaDataControl = new QGstreamerCaptureMetaDataControl(this);
    connect(m_metaDataControl, SIGNAL(metaDataChanged(QMap<QByteArray,QVariant>)),
            m_captureSession, SLOT(setMetaData(QMap<QByteArray,QVariant>)));
}

QGstreamerCaptureService::~QGstreamerCaptureService()
{
}

QMediaControl *QGstreamerCaptureService::requestControl(const char *name)
{
    if (!m_captureSession)
        return 0;

    if (!m_videoOutput) {
        if (qstrcmp(name, QVideoRendererControl_iid) == 0) {
            m_videoOutput = m_videoRenderer;
            m_captureSession->setVideoPreview(m_videoRendererFactory);
        } else if (qstrcmp(name, QVideoWindowControl_iid) == 0) {
            m_videoOutput = m_videoWindow;
            m_captureSession->setVideoPreview(m_videoWindowFactory);
        } else if (qstrcmp(name, QVideoWidgetControl_iid) == 0) {
            m_captureSession->setVideoPreview(m_videoWidgetFactory);
            m_videoOutput = m_videoWidgetControl;
        }

        if (m_videoOutput)
            return m_videoOutput;
    }

    if (qstrcmp(name,QAudioEndpointSelector_iid) == 0)
        return m_audioInputEndpointSelector;

    if (qstrcmp(name,QVideoDeviceControl_iid) == 0)
        return m_videoInputDevice;

    if (qstrcmp(name,QMediaRecorderControl_iid) == 0)
        return m_captureSession->recorderControl();

    if (qstrcmp(name,QAudioEncoderControl_iid) == 0)
        return m_captureSession->audioEncodeControl();

    if (qstrcmp(name,QVideoEncoderControl_iid) == 0)
        return m_captureSession->videoEncodeControl();

    if (qstrcmp(name,QMediaContainerControl_iid) == 0)
        return m_captureSession->mediaContainerControl();

    if (qstrcmp(name,QMetaDataWriterControl_iid) == 0)
        return m_metaDataControl;

    return 0;
}

void QGstreamerCaptureService::releaseControl(QMediaControl *control)
{
    if (control && control == m_videoOutput) {
        m_videoOutput = 0;
        m_captureSession->setVideoPreview(0);
    }
}

<|endoftext|>