<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salgdiutils.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-05 16:01:22 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif

#include <basebmp/scanlineformats.hxx>
#include <basebmp/color.hxx>
#include <basegfx/range/b2drectangle.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/vector/b2ivector.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <boost/bind.hpp>

#include <vcl/svapp.hxx>

#include "saldata.hxx"

// ----------------------------------------------------------------------

void AquaSalGraphics::SetWindowGraphics( CarbonViewRef rView, CarbonWindowRef rWindow, bool bScreenCompatible )
{
    mrView      = rView;
    mrWindow    = rWindow;
    mbScreen    = bScreenCompatible;

    mbWindow    = true;
    mbPrinter   = false;
    mbVirDev    = false;
}

void AquaSalGraphics::SetPrinterGraphics( CGContextRef xContext, long nDPIX, long nDPIY )
{
    mrView      = 0;
    mbScreen    = false;

    mbWindow    = false;
    mbPrinter   = true;
    mbVirDev    = false;

    mrContext   = xContext;
    mnDPIX      = nDPIX;
    mnDPIY      = nDPIY;

    if( mrContext )
    {
        CGContextSetFillColorSpace( mrContext, mrRGBColorSpace );
        CGContextSetStrokeColorSpace( mrContext, mrRGBColorSpace );
        CGContextSaveGState( mrContext );
        SetState();
    }
}

static void nil_free( void* )
{
}

void AquaSalGraphics::SetVirDevGraphics( CGContextRef xContext, bool bScreenCompatible )
{
    mrView      = 0;
    mbScreen    = bScreenCompatible;

    mbWindow    = false;
    mbPrinter   = false;
    mbVirDev    = true;

    mrContext   = xContext;
    sal_uInt8* pMemory = NULL;
    if( mrContext )
    {
        pMemory = reinterpret_cast<sal_uInt8*>(CGBitmapContextGetData( mrContext ));
        CGContextSetFillColorSpace( mrContext, mrRGBColorSpace );
        CGContextSetStrokeColorSpace( mrContext, mrRGBColorSpace );
        CGContextSaveGState( mrContext );
        SetState();
    }
    maContextMemory.reset( pMemory, boost::bind( nil_free, _1 ) );
}

// ----------------------------------------------------------------------

void AquaSalGraphics::SetState()
{
    CGContextRestoreGState( mrContext );
    CGContextSaveGState( mrContext );
    // set up clipping area
    if( mrClippingPath )
    {
        CGContextBeginPath( mrContext );                // discard any existing path
        CGContextAddPath( mrContext, mrClippingPath );  // set the current path to the clipping path
        CGContextClip( mrContext );                     // use it for clipping
    }

    // set RGB colorspace and line and fill colors
    CGContextSetFillColor( mrContext, mpFillColor );
    CGContextSetStrokeColor( mrContext, mpLineColor );
    if( mbXORMode && (mbWindow || mbVirDev) )
    {
        CGContextSetBlendMode(mrContext, kCGBlendModeDifference);
        int nWidth  = CGBitmapContextGetWidth(mrContext);
        int nHeight = CGBitmapContextGetHeight(mrContext);
        if( ! maXORDevice )
        {
            maXORDevice = basebmp::createBitmapDevice( basegfx::B2IVector( nWidth, nHeight ),
                                                       mbWindow,
                                                       basebmp::Format::THIRTYTWO_BIT_TC_MASK_ARGB,
                                                       maContextMemory,
                                                       basebmp::PaletteMemorySharedVector() );
            if( mrClippingPath && maClippingRects.size() == 1 )
            {
                /*
                * optimization: the case with only one clip rectangle is quite common
                * in this case it is much cheaper to constrain the XOR device to a smaller
                * area than to clip every pixel with the mask
                */
                maXORClipMask.reset();
                CGRect aBounds( maClippingRects.front() );
                basegfx::B2IRange aRect( aBounds.origin.x, aBounds.origin.y,
                                         aBounds.origin.x+aBounds.size.width,
                                         aBounds.origin.y+aBounds.size.height );
                maXORDevice = basebmp::subsetBitmapDevice( maXORDevice, aRect );
            }
        }
        if( mrClippingPath )
        {
            if( ! maXORClipMask && maClippingRects.size() > 1 )
            {
                maXORClipMask = basebmp::createBitmapDevice( basegfx::B2IVector( nWidth, nHeight ),
                                                             mbWindow,
                                                             basebmp::Format::ONE_BIT_MSB_GREY );
                maXORClipMask->clear( basebmp::Color(0xffffffff) );
                for( std::vector<CGRect>::const_iterator it = maClippingRects.begin(); it != maClippingRects.end(); ++it )
                {
                    basegfx::B2DRectangle aRect( it->origin.x, it->origin.y,
                                                 it->origin.x+it->size.width,
                                                 it->origin.y+it->size.height );
                    maXORClipMask->fillPolyPolygon( basegfx::B2DPolyPolygon( basegfx::tools::createPolygonFromRect( aRect ) ),
                                                    basebmp::Color( 0 ),
                                                    basebmp::DrawMode_PAINT
                                                    );
                }
            }
        }
        else
            maXORClipMask.reset();
    }

    CGContextSetShouldAntialias( mrContext, false );

}

// ----------------------------------------------------------------------

bool AquaSalGraphics::CheckContext()
{
    if( mrWindow != NULL )
    {
        Rect windowBounds;
        GetWindowPortBounds( mrWindow, &windowBounds );
        const unsigned int nWidth = windowBounds.right - windowBounds.left;
        const unsigned int nHeight = windowBounds.bottom - windowBounds.top;

        CGContextRef rReleaseContext = 0;
        unsigned int nReleaseContextWidth = 0;
        unsigned int nReleaseContextHeight = 0;

        boost::shared_array<sal_uInt8> aOldMem;
        if( mrContext )
        {
            nReleaseContextWidth = CGBitmapContextGetWidth(mrContext);
            nReleaseContextHeight = CGBitmapContextGetHeight(mrContext);
            // check if window size changed and we need to create a new bitmap context
            if( (nReleaseContextWidth != nWidth)  || (nReleaseContextHeight != nHeight) )
            {
                rReleaseContext = mrContext;
                mrContext = 0;
                aOldMem = maContextMemory;
                maXORDevice.reset();
                maXORClipMask.reset();
            }
        }

        if( !mrContext )
        {
            maContextMemory.reset( reinterpret_cast<sal_uInt8*>( rtl_allocateMemory( nWidth * 4 * nHeight ) ),
                                   boost::bind( rtl_freeMemory, _1 ) );
            if( maContextMemory )
            {
                mrContext = CGBitmapContextCreate( maContextMemory.get(), nWidth, nHeight, 8, nWidth * 4, mrRGBColorSpace, kCGImageAlphaNoneSkipFirst );

                if( mrContext )
                {
                    // copy bitmap data to new context
                    if( rReleaseContext )
                    {
                        CGRect aBounds;
                        aBounds.origin.x = aBounds.origin.y = 0;
                        aBounds.size.width = nReleaseContextWidth;
                        aBounds.size.height = nReleaseContextHeight;
                        CGImageRef xImage = CGBitmapContextCreateImage( rReleaseContext );
                        CGContextDrawImage( mrContext, aBounds, xImage );
                        CGImageRelease(xImage);
                    }

                    CGContextTranslateCTM( mrContext, 0, nHeight );
                    CGContextScaleCTM( mrContext, 1.0, -1.0 );
                    CGContextSetFillColorSpace( mrContext, mrRGBColorSpace );
                    CGContextSetStrokeColorSpace( mrContext, mrRGBColorSpace );
                    CGContextSaveGState( mrContext );
                    SetState();
                }
                else
                {
                    maContextMemory.reset(); // free memory again
                }
            }
        }

        if( rReleaseContext ) // released memory runs out of scope and is then freed
            CFRelease( rReleaseContext );
    }
    if( mrContext )
    {
        if( mbXORMode )
        {
            if( ! maXORDevice )
                SetState();
        }
        return true;
    }
    else
    {
        AquaLog("<<<WARNING>>> AquaSalGraphics::CheckContext() FAILED!!!!\n" );
        return false;
    }
}

void AquaSalGraphics::RefreshRect(float lX, float lY, float lWidth, float lHeight)
{
    if( ! mbWindow ) // view only on Window graphics
        return;

    AquaLog("-->%s refresh %d - %d - %d - %d\n", __func__, static_cast<int>(lX), static_cast<int>(lY), static_cast<int>(lWidth), static_cast<int>(lHeight));

    // Refresh windows rect content
    HIRect aHIRect;
    aHIRect.origin.x = static_cast<int>(lX);
    aHIRect.origin.y = static_cast<int>(lY);
    aHIRect.size.width = static_cast<int>(lWidth);
    aHIRect.size.height = static_cast<int>(lHeight);
    OSStatus retVal = HIViewSetNeedsDisplayInRect(mrView,&aHIRect,true);
    if (retVal)
        AquaLog( "FIXME: HIViewSetNeedsDisplayInRect returned %d (mrView is %p)\n", (int) retVal, mrView);

    Rect aRect;
    aRect.left   = (short)lX;
    aRect.top    = (short)lY;
    aRect.right  = (short)(lX + lWidth );
    aRect.bottom = (short)(lY + lHeight );
    InvalWindowRect(mrWindow, &aRect);
}

void AquaSalGraphics::Flush()
{
    if( mbWindow )
    {
        UpdateWindow();
    }
}

CGPoint* AquaSalGraphics::makeCGptArray(ULONG nPoints, const SalPoint*  pPtAry)
{
    AquaLog("-->%s\n",__func__);
    CGPoint *CGpoints = new (CGPoint[nPoints]);
    if ( CGpoints )
      {
        for(ULONG i=0;i<nPoints;i++)
          {
            CGpoints[i].x = (float)(pPtAry[i].mnX);
            CGpoints[i].y = (float)(pPtAry[i].mnY);
          }
      }
    return CGpoints;
}

// -----------------------------------------------------------------------

void AquaSalGraphics::UpdateWindow()
{
    if( mrContext != NULL && mrWindow != NULL )
    {
        SetPortWindowPort(mrWindow);
        CGContextRef xWindowContext = 0;
        if( noErr == QDBeginCGContext (GetWindowPort (mrWindow), &xWindowContext))
        {
            Rect windowBounds;
            GetWindowPortBounds( mrWindow, &windowBounds);
            CGImageRef xImage = CGBitmapContextCreateImage( mrContext );
            CGContextDrawImage(xWindowContext, CGRectMake(windowBounds.left, windowBounds.top, windowBounds.right - windowBounds.left, windowBounds.bottom - windowBounds.top ), xImage);
            CGImageRelease(xImage);
            CGContextFlush( xWindowContext );
            QDEndCGContext (GetWindowPort(mrWindow), &xWindowContext);
        }
    }
}

// -----------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS aquavcl02 (1.8.262); FILE MERGED 2007/07/11 10:50:18 pjanik 1.8.262.3: RESYNC: (1.8-1.10); FILE MERGED 2007/07/10 08:14:43 pl 1.8.262.2: #i79424# reuse colorspace 2007/07/02 11:53:46 pl 1.8.262.1: join from aquavcl01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salgdiutils.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-08-03 14:02:31 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif

#include <basebmp/scanlineformats.hxx>
#include <basebmp/color.hxx>
#include <basegfx/range/b2drectangle.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/vector/b2ivector.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <boost/bind.hpp>

#include <vcl/svapp.hxx>

#include "saldata.hxx"

// ----------------------------------------------------------------------

void AquaSalGraphics::SetWindowGraphics( CarbonViewRef rView, CarbonWindowRef rWindow, bool bScreenCompatible )
{
    mrView      = rView;
    mrWindow    = rWindow;
    mbScreen    = bScreenCompatible;

    mbWindow    = true;
    mbPrinter   = false;
    mbVirDev    = false;
}

void AquaSalGraphics::SetPrinterGraphics( CGContextRef xContext, long nDPIX, long nDPIY )
{
    mrView      = 0;
    mbScreen    = false;

    mbWindow    = false;
    mbPrinter   = true;
    mbVirDev    = false;

    mrContext   = xContext;
    mnDPIX      = nDPIX;
    mnDPIY      = nDPIY;

    if( mrContext )
    {
        CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );
        CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );
        CGContextSaveGState( mrContext );
        SetState();
    }
}

static void nil_free( void* )
{
}

void AquaSalGraphics::SetVirDevGraphics( CGContextRef xContext, bool bScreenCompatible )
{
    mrView      = 0;
    mbScreen    = bScreenCompatible;

    mbWindow    = false;
    mbPrinter   = false;
    mbVirDev    = true;

    mrContext   = xContext;
    sal_uInt8* pMemory = NULL;
    if( mrContext )
    {
        pMemory = reinterpret_cast<sal_uInt8*>(CGBitmapContextGetData( mrContext ));
        CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );
        CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );
        CGContextSaveGState( mrContext );
        SetState();
    }
    maContextMemory.reset( pMemory, boost::bind( nil_free, _1 ) );
}

// ----------------------------------------------------------------------

void AquaSalGraphics::SetState()
{
    CGContextRestoreGState( mrContext );
    CGContextSaveGState( mrContext );
    // set up clipping area
    if( mrClippingPath )
    {
        CGContextBeginPath( mrContext );                // discard any existing path
        CGContextAddPath( mrContext, mrClippingPath );  // set the current path to the clipping path
        CGContextClip( mrContext );                     // use it for clipping
    }

    // set RGB colorspace and line and fill colors
    CGContextSetFillColor( mrContext, mpFillColor );
    CGContextSetStrokeColor( mrContext, mpLineColor );
    if( mbXORMode && (mbWindow || mbVirDev) )
    {
        CGContextSetBlendMode(mrContext, kCGBlendModeDifference);
        int nWidth  = CGBitmapContextGetWidth(mrContext);
        int nHeight = CGBitmapContextGetHeight(mrContext);
        if( ! maXORDevice )
        {
            maXORDevice = basebmp::createBitmapDevice( basegfx::B2IVector( nWidth, nHeight ),
                                                       mbWindow,
                                                       basebmp::Format::THIRTYTWO_BIT_TC_MASK_ARGB,
                                                       maContextMemory,
                                                       basebmp::PaletteMemorySharedVector() );
            if( mrClippingPath && maClippingRects.size() == 1 )
            {
                /*
                * optimization: the case with only one clip rectangle is quite common
                * in this case it is much cheaper to constrain the XOR device to a smaller
                * area than to clip every pixel with the mask
                */
                maXORClipMask.reset();
                CGRect aBounds( maClippingRects.front() );
                basegfx::B2IRange aRect( aBounds.origin.x, aBounds.origin.y,
                                         aBounds.origin.x+aBounds.size.width,
                                         aBounds.origin.y+aBounds.size.height );
                maXORDevice = basebmp::subsetBitmapDevice( maXORDevice, aRect );
            }
        }
        if( mrClippingPath )
        {
            if( ! maXORClipMask && maClippingRects.size() > 1 )
            {
                maXORClipMask = basebmp::createBitmapDevice( basegfx::B2IVector( nWidth, nHeight ),
                                                             mbWindow,
                                                             basebmp::Format::ONE_BIT_MSB_GREY );
                maXORClipMask->clear( basebmp::Color(0xffffffff) );
                for( std::vector<CGRect>::const_iterator it = maClippingRects.begin(); it != maClippingRects.end(); ++it )
                {
                    basegfx::B2DRectangle aRect( it->origin.x, it->origin.y,
                                                 it->origin.x+it->size.width,
                                                 it->origin.y+it->size.height );
                    maXORClipMask->fillPolyPolygon( basegfx::B2DPolyPolygon( basegfx::tools::createPolygonFromRect( aRect ) ),
                                                    basebmp::Color( 0 ),
                                                    basebmp::DrawMode_PAINT
                                                    );
                }
            }
        }
        else
            maXORClipMask.reset();
    }

    CGContextSetShouldAntialias( mrContext, false );

}

// ----------------------------------------------------------------------

bool AquaSalGraphics::CheckContext()
{
    if( mrWindow != NULL )
    {
        Rect windowBounds;
        GetWindowPortBounds( mrWindow, &windowBounds );
        const unsigned int nWidth = windowBounds.right - windowBounds.left;
        const unsigned int nHeight = windowBounds.bottom - windowBounds.top;

        CGContextRef rReleaseContext = 0;
        unsigned int nReleaseContextWidth = 0;
        unsigned int nReleaseContextHeight = 0;

        boost::shared_array<sal_uInt8> aOldMem;
        if( mrContext )
        {
            nReleaseContextWidth = CGBitmapContextGetWidth(mrContext);
            nReleaseContextHeight = CGBitmapContextGetHeight(mrContext);
            // check if window size changed and we need to create a new bitmap context
            if( (nReleaseContextWidth != nWidth)  || (nReleaseContextHeight != nHeight) )
            {
                rReleaseContext = mrContext;
                mrContext = 0;
                aOldMem = maContextMemory;
                maXORDevice.reset();
                maXORClipMask.reset();
            }
        }

        if( !mrContext )
        {
            maContextMemory.reset( reinterpret_cast<sal_uInt8*>( rtl_allocateMemory( nWidth * 4 * nHeight ) ),
                                   boost::bind( rtl_freeMemory, _1 ) );
            if( maContextMemory )
            {
                mrContext = CGBitmapContextCreate( maContextMemory.get(), nWidth, nHeight, 8, nWidth * 4, GetSalData()->mxRGBSpace, kCGImageAlphaNoneSkipFirst );

                if( mrContext )
                {
                    // copy bitmap data to new context
                    if( rReleaseContext )
                    {
                        CGRect aBounds;
                        aBounds.origin.x = aBounds.origin.y = 0;
                        aBounds.size.width = nReleaseContextWidth;
                        aBounds.size.height = nReleaseContextHeight;
                        CGImageRef xImage = CGBitmapContextCreateImage( rReleaseContext );
                        CGContextDrawImage( mrContext, aBounds, xImage );
                        CGImageRelease(xImage);
                    }

                    CGContextTranslateCTM( mrContext, 0, nHeight );
                    CGContextScaleCTM( mrContext, 1.0, -1.0 );
                    CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );
                    CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );
                    CGContextSaveGState( mrContext );
                    SetState();
                }
                else
                {
                    maContextMemory.reset(); // free memory again
                }
            }
        }

        if( rReleaseContext ) // released memory runs out of scope and is then freed
            CFRelease( rReleaseContext );
    }
    if( mrContext )
    {
        if( mbXORMode )
        {
            if( ! maXORDevice )
                SetState();
        }
        return true;
    }
    else
    {
        AquaLog("<<<WARNING>>> AquaSalGraphics::CheckContext() FAILED!!!!\n" );
        return false;
    }
}

void AquaSalGraphics::RefreshRect(float lX, float lY, float lWidth, float lHeight)
{
    if( ! mbWindow ) // view only on Window graphics
        return;

    AquaLog("-->%s refresh %d - %d - %d - %d\n", __func__, static_cast<int>(lX), static_cast<int>(lY), static_cast<int>(lWidth), static_cast<int>(lHeight));

    // Refresh windows rect content
    HIRect aHIRect;
    aHIRect.origin.x = static_cast<int>(lX);
    aHIRect.origin.y = static_cast<int>(lY);
    aHIRect.size.width = static_cast<int>(lWidth);
    aHIRect.size.height = static_cast<int>(lHeight);
    OSStatus retVal = HIViewSetNeedsDisplayInRect(mrView,&aHIRect,true);
    if (retVal)
        AquaLog( "FIXME: HIViewSetNeedsDisplayInRect returned %d (mrView is %p)\n", (int) retVal, mrView);

    Rect aRect;
    aRect.left   = (short)lX;
    aRect.top    = (short)lY;
    aRect.right  = (short)(lX + lWidth );
    aRect.bottom = (short)(lY + lHeight );
    InvalWindowRect(mrWindow, &aRect);
}

void AquaSalGraphics::Flush()
{
    if( mbWindow )
    {
        UpdateWindow();
    }
}

CGPoint* AquaSalGraphics::makeCGptArray(ULONG nPoints, const SalPoint*  pPtAry)
{
    AquaLog("-->%s\n",__func__);
    CGPoint *CGpoints = new (CGPoint[nPoints]);
    if ( CGpoints )
      {
        for(ULONG i=0;i<nPoints;i++)
          {
            CGpoints[i].x = (float)(pPtAry[i].mnX);
            CGpoints[i].y = (float)(pPtAry[i].mnY);
          }
      }
    return CGpoints;
}

// -----------------------------------------------------------------------

void AquaSalGraphics::UpdateWindow()
{
    if( mrContext != NULL && mrWindow != NULL )
    {
        SetPortWindowPort(mrWindow);
        CGContextRef xWindowContext = 0;
        if( noErr == QDBeginCGContext (GetWindowPort (mrWindow), &xWindowContext))
        {
            Rect windowBounds;
            GetWindowPortBounds( mrWindow, &windowBounds);
            CGImageRef xImage = CGBitmapContextCreateImage( mrContext );
            CGContextDrawImage(xWindowContext, CGRectMake(windowBounds.left, windowBounds.top, windowBounds.right - windowBounds.left, windowBounds.bottom - windowBounds.top ), xImage);
            CGImageRelease(xImage);
            CGContextFlush( xWindowContext );
            QDEndCGContext (GetWindowPort(mrWindow), &xWindowContext);
        }
    }
}

// -----------------------------------------------------------------------

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_VCL_UNX_GENERIC_GDI_GCACH_XPEER_HXX
#define INCLUDED_VCL_UNX_GENERIC_GDI_GCACH_XPEER_HXX

#include "generic/glyphcache.hxx"

class X11GlyphPeer : public GlyphCachePeer
{
public:
    X11GlyphPeer();
    virtual ~X11GlyphPeer();
};

class X11GlyphCache : public GlyphCache
{
public:
    X11GlyphCache( X11GlyphPeer& );
    X11GlyphPeer& GetPeer()
    {
        return static_cast<X11GlyphPeer&>(mrPeer);
    }
    static X11GlyphCache& GetInstance();
    static void  KillInstance();
};

#endif // INCLUDED_VCL_UNX_GENERIC_GDI_GCACH_XPEER_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>unused GetPeer inline<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_VCL_UNX_GENERIC_GDI_GCACH_XPEER_HXX
#define INCLUDED_VCL_UNX_GENERIC_GDI_GCACH_XPEER_HXX

#include "generic/glyphcache.hxx"

class X11GlyphPeer : public GlyphCachePeer
{
public:
    X11GlyphPeer();
    virtual ~X11GlyphPeer();
};

class X11GlyphCache : public GlyphCache
{
public:
    X11GlyphCache( X11GlyphPeer& );
    static X11GlyphCache& GetInstance();
    static void  KillInstance();
};

#endif // INCLUDED_VCL_UNX_GENERIC_GDI_GCACH_XPEER_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before><commit_msg>coverity#708670 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>#include <Bull/Core/Memory/ByteVector.hpp>

namespace Bull
{
    ByteVector::ByteVector(std::size_t size) :
        ByteVector(size, 0)
    {
        /// Nothing
    }

    ByteVector::ByteVector(std::size_t size, Uint8 value) :
        MemoryVector<Uint8>(size, value)
    {
        /// Nothing
    }

    String ByteVector::toString() const
    {
        return String(reinterpret_cast<const char*>(getBuffer(), getCapacity()));
    }
}<commit_msg>[Core/ByteVector] Fix toString method<commit_after>#include <Bull/Core/Memory/ByteVector.hpp>

namespace Bull
{
    ByteVector::ByteVector(std::size_t size) :
        ByteVector(size, 0)
    {
        /// Nothing
    }

    ByteVector::ByteVector(std::size_t size, Uint8 value) :
        MemoryVector<Uint8>(size, value)
    {
        /// Nothing
    }

    String ByteVector::toString() const
    {
        return String(reinterpret_cast<const char*>(getBuffer()), getCapacity());
    }
}<|endoftext|>


<commit_before>/*
 * SchemeSmob.c
 *
 * Scheme small objects (SMOBS) for opencog -- core functions.
 *
 * Copyright (c) 2008, 2013, 2014, 2015 Linas Vepstas <linas@linas.org>
 */

#ifdef HAVE_GUILE

#include <cstddef>
#include <libguile.h>

#include <opencog/atomspace/AtomSpace.h>
#include "SchemePrimitive.h"
#include "SchemeSmob.h"

using namespace opencog;

/**
 * Just one scheme smob type is used to implement the interface.
 *
 * The cog_misc_tag is used to store all structures, such as atoms
 * and truth values. It is assumed that these structures are all
 * ephemeral (garbage-collected), including the Handles.  Note that
 * atoms in the atomspace have a concrete existence outside of the
 * scheme shell. By contrast, truth values created by the scheme
 * shell are garbage collected by the shell.
 *
 * The type of the "misc" structure is stored in the flag bits;
 * thus, handling is dispatched based on these flags.
 *
 * XXX TODO:
 * The cog_misc_tag should be replaced by a tag-per-class (i.e. we
 * should have a separate tag for handles, tv's, etc.) This would
 * simplify that code, and probably improve performance just a bit.
 */

scm_t_bits SchemeSmob::cog_misc_tag;
std::atomic_flag SchemeSmob::is_inited = ATOMIC_FLAG_INIT;
SCM SchemeSmob::_radix_ten;

void SchemeSmob::init()
{
	if (is_inited.test_and_set()) return;

	init_smob_type();
	scm_c_define_module("opencog", register_procs, NULL);
	scm_c_use_module("opencog");

	atomspace_fluid = scm_make_fluid();
	atomspace_fluid = scm_permanent_object(atomspace_fluid);
	_radix_ten = scm_from_int8(10);
}

SchemeSmob::SchemeSmob()
{
	init();
}

void opencog_guile_init(void)
{
	SchemeSmob::init();
}

/* ============================================================== */

void SchemeSmob::init_smob_type(void)
{
	// A SMOB type for everything, incuding atoms.
	cog_misc_tag = scm_make_smob_type ("opencog-misc", sizeof (scm_t_bits));
	scm_set_smob_print (cog_misc_tag, print_misc);
	scm_set_smob_equalp (cog_misc_tag, equalp_misc);
	// scm_set_smob_mark (cog_misc_tag, mark_misc);
	scm_set_smob_free (cog_misc_tag, free_misc);
}

/* ============================================================== */

SCM SchemeSmob::equalp_misc(SCM a, SCM b)
{
	// If they're not something we know about, let scheme sort it out.
	// (Actualy, this should never happen ...)
	if (not SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, a))
		return scm_equal_p(a, b);

	// If the types don't match, they can't be equal.
	scm_t_bits ta = SCM_SMOB_FLAGS(a);
	scm_t_bits tb = SCM_SMOB_FLAGS(b);
	if (ta != tb)
		return SCM_BOOL_F;

	switch (ta)
	{
		default: // Should never happen.
		case 0:  // Should never happen.
			return SCM_BOOL_F;
		case COG_AS:
		{
			AtomSpace* as = (AtomSpace *) SCM_SMOB_DATA(a);
			AtomSpace* bs = (AtomSpace *) SCM_SMOB_DATA(b);
			scm_remember_upto_here_1(a);
			scm_remember_upto_here_1(b);
			/* Just a simple pointer comparison */
			if (as == bs) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
		case COG_AV:
		{
			AttentionValue* av = (AttentionValue *) SCM_SMOB_DATA(a);
			AttentionValue* bv = (AttentionValue *) SCM_SMOB_DATA(b);
			scm_remember_upto_here_1(a);
			scm_remember_upto_here_1(b);
			if (av == bv) return SCM_BOOL_T;
			if (*av == *bv) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
		case COG_EXTEND:
		{
			// We compare pointers here, only.
			PrimitiveEnviron* av = (PrimitiveEnviron *) SCM_SMOB_DATA(a);
			PrimitiveEnviron* bv = (PrimitiveEnviron *) SCM_SMOB_DATA(b);
			scm_remember_upto_here_1(a);
			scm_remember_upto_here_1(b);
			if (av == bv) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
		case COG_HANDLE:
		{
			Handle ha(scm_to_handle(a));
			Handle hb(scm_to_handle(b));
			if (ha == hb) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
		case COG_TV:
		{
			TruthValue* av = (TruthValue *) SCM_SMOB_DATA(a);
			TruthValue* bv = (TruthValue *) SCM_SMOB_DATA(b);
			scm_remember_upto_here_1(a);
			scm_remember_upto_here_1(b);
			if (av == bv) return SCM_BOOL_T;
			if (*av == *bv) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
	}
}

/* ============================================================== */

void SchemeSmob::throw_exception(const char *msg, const char * func)
{
	if (msg) {
		// Should we even bother to log this?  Probably not ...
		logger().info("Guile caught C++ exception: %s", msg);

		// scm_misc_error(fe->get_name(), msg, SCM_EOL);
		scm_throw(
			scm_from_utf8_symbol("C++-EXCEPTION"),
			scm_cons(
				scm_from_utf8_string(func),
				scm_cons(
					scm_from_utf8_string(msg),
					SCM_EOL)));
		// Hmm. scm_throw never returns.
	}
	else
	{
		// scm_misc_error(fe->get_name(), "unknown C++ exception", SCM_EOL);
		scm_error_scm(
			scm_from_utf8_symbol("C++ exception"),
			scm_from_utf8_string(func),
			scm_from_utf8_string("unknown C++ exception"),
			SCM_EOL,
			SCM_EOL);
		logger().error("Guile caught unknown C++ exception");
	}
}

/* ============================================================== */

#ifdef HAVE_GUILE2
 #define C(X) ((scm_t_subr) X)
#else
 #define C(X) ((SCM (*) ()) X)
#endif

void SchemeSmob::register_procs(void*)
{
	register_proc("cog-atom",              1, 0, 0, C(ss_atom));
	register_proc("cog-handle",            1, 0, 0, C(ss_handle));
	register_proc("cog-undefined-handle",  0, 0, 0, C(ss_undefined_handle));
	register_proc("cog-new-value",         1, 0, 1, C(ss_new_value));
	register_proc("cog-new-node",          2, 0, 1, C(ss_new_node));
	register_proc("cog-new-link",          1, 0, 1, C(ss_new_link));
	register_proc("cog-node",              2, 0, 1, C(ss_node));
	register_proc("cog-link",              1, 0, 1, C(ss_link));
	register_proc("cog-delete",            1, 0, 1, C(ss_delete));
	register_proc("cog-delete-recursive",  1, 0, 1, C(ss_delete_recursive));
	register_proc("cog-purge",             1, 0, 1, C(ss_purge));
	register_proc("cog-purge-recursive",   1, 0, 1, C(ss_purge_recursive));
	register_proc("cog-value?",            1, 0, 1, C(ss_value_p));
	register_proc("cog-atom?",             1, 0, 1, C(ss_atom_p));
	register_proc("cog-node?",             1, 0, 1, C(ss_node_p));
	register_proc("cog-link?",             1, 0, 1, C(ss_link_p));

	// property setters on atoms
	register_proc("cog-set-av!",           2, 0, 0, C(ss_set_av));
	register_proc("cog-set-tv!",           2, 0, 0, C(ss_set_tv));
	register_proc("cog-merge-tv!",         2, 0, 0, C(ss_merge_tv));
	register_proc("cog-merge-hi-conf-tv!", 2, 0, 0, C(ss_merge_hi_conf_tv));
	register_proc("cog-inc-vlti!",         1, 0, 0, C(ss_inc_vlti));
	register_proc("cog-dec-vlti!",         1, 0, 0, C(ss_dec_vlti));

	// property getters on atoms
	register_proc("cog-name",              1, 0, 0, C(ss_name));
	register_proc("cog-type",              1, 0, 0, C(ss_type));
	register_proc("cog-arity",             1, 0, 0, C(ss_arity));
	register_proc("cog-incoming-set",      1, 0, 0, C(ss_incoming_set));
	register_proc("cog-outgoing-set",      1, 0, 0, C(ss_outgoing_set));
	register_proc("cog-tv",                1, 0, 0, C(ss_tv));
	register_proc("cog-av",                1, 0, 0, C(ss_av));
	register_proc("cog-as",                1, 0, 0, C(ss_as));

	// Truth-values
	register_proc("cog-new-stv",           2, 0, 0, C(ss_new_stv));
	register_proc("cog-new-ctv",           3, 0, 0, C(ss_new_ctv));
	register_proc("cog-new-itv",           3, 0, 0, C(ss_new_itv));
	register_proc("cog-new-ptv",           3, 0, 0, C(ss_new_ptv));
	register_proc("cog-new-ftv",           2, 0, 0, C(ss_new_ftv));
	register_proc("cog-tv?",               1, 0, 0, C(ss_tv_p));
	register_proc("cog-stv?",              1, 0, 0, C(ss_stv_p));
	register_proc("cog-ctv?",              1, 0, 0, C(ss_ctv_p));
	register_proc("cog-itv?",              1, 0, 0, C(ss_itv_p));
	register_proc("cog-ptv?",              1, 0, 0, C(ss_ptv_p));
	register_proc("cog-ftv?",              1, 0, 0, C(ss_ftv_p));
	register_proc("cog-tv->alist",         1, 0, 0, C(ss_tv_get_value));
	register_proc("cog-tv-mean",           1, 0, 0, C(ss_tv_get_mean));
	register_proc("cog-tv-confidence",     1, 0, 0, C(ss_tv_get_confidence));
	register_proc("cog-tv-count",          1, 0, 0, C(ss_tv_get_count));

	// Atom Spaces
	register_proc("cog-new-atomspace",     0, 1, 0, C(ss_new_as));
	register_proc("cog-atomspace?",        1, 0, 0, C(ss_as_p));
	register_proc("cog-atomspace",         0, 0, 0, C(ss_get_as));
	register_proc("cog-set-atomspace!",    1, 0, 0, C(ss_set_as));
	register_proc("cog-atomspace-env",     1, 0, 0, C(ss_as_env));
	register_proc("cog-atomspace-uuid",    1, 0, 0, C(ss_as_uuid));
	register_proc("cog-atomspace-clear",   1, 0, 0, C(ss_as_clear));

	// Attention values
	register_proc("cog-new-av",            3, 0, 0, C(ss_new_av));
	register_proc("cog-av?",               1, 0, 0, C(ss_av_p));
	register_proc("cog-av->alist",         1, 0, 0, C(ss_av_get_value));

	// AttentionalFocus
	register_proc("cog-af-boundary",       0, 0, 0, C(ss_af_boundary));
	register_proc("cog-set-af-boundary!",  1, 0, 0, C(ss_set_af_boundary));
	register_proc("cog-af",                0, 0, 0, C(ss_af));

	// Atom types
	register_proc("cog-get-types",         0, 0, 0, C(ss_get_types));
	register_proc("cog-type->int",         1, 0, 0, C(ss_get_type));
	register_proc("cog-type?",             1, 0, 0, C(ss_type_p));
	register_proc("cog-value-type?",       1, 0, 0, C(ss_value_type_p));
	register_proc("cog-node-type?",        1, 0, 0, C(ss_node_type_p));
	register_proc("cog-link-type?",        1, 0, 0, C(ss_link_type_p));
	register_proc("cog-get-subtypes",      1, 0, 0, C(ss_get_subtypes));
	register_proc("cog-subtype?",          2, 0, 0, C(ss_subtype_p));

	// Iterators
	register_proc("cog-map-type",          2, 0, 0, C(ss_map_type));
}

void SchemeSmob::register_proc(const char* name, int req, int opt, int rst, scm_t_subr fcn)
{
	scm_c_define_gsubr(name, req, opt, rst, fcn);
	scm_c_export(name, NULL);
}

#endif
/* ===================== END OF FILE ============================ */
<commit_msg>Some code is throwing something .. unexpected.<commit_after>/*
 * SchemeSmob.c
 *
 * Scheme small objects (SMOBS) for opencog -- core functions.
 *
 * Copyright (c) 2008, 2013, 2014, 2015 Linas Vepstas <linas@linas.org>
 */

#ifdef HAVE_GUILE

#include <cstddef>
#include <libguile.h>

#include <opencog/atomspace/AtomSpace.h>
#include "SchemePrimitive.h"
#include "SchemeSmob.h"

using namespace opencog;

/**
 * Just one scheme smob type is used to implement the interface.
 *
 * The cog_misc_tag is used to store all structures, such as atoms
 * and truth values. It is assumed that these structures are all
 * ephemeral (garbage-collected), including the Handles.  Note that
 * atoms in the atomspace have a concrete existence outside of the
 * scheme shell. By contrast, truth values created by the scheme
 * shell are garbage collected by the shell.
 *
 * The type of the "misc" structure is stored in the flag bits;
 * thus, handling is dispatched based on these flags.
 *
 * XXX TODO:
 * The cog_misc_tag should be replaced by a tag-per-class (i.e. we
 * should have a separate tag for handles, tv's, etc.) This would
 * simplify that code, and probably improve performance just a bit.
 */

scm_t_bits SchemeSmob::cog_misc_tag;
std::atomic_flag SchemeSmob::is_inited = ATOMIC_FLAG_INIT;
SCM SchemeSmob::_radix_ten;

void SchemeSmob::init()
{
	if (is_inited.test_and_set()) return;

	init_smob_type();
	scm_c_define_module("opencog", register_procs, NULL);
	scm_c_use_module("opencog");

	atomspace_fluid = scm_make_fluid();
	atomspace_fluid = scm_permanent_object(atomspace_fluid);
	_radix_ten = scm_from_int8(10);
}

SchemeSmob::SchemeSmob()
{
	init();
}

void opencog_guile_init(void)
{
	SchemeSmob::init();
}

/* ============================================================== */

void SchemeSmob::init_smob_type(void)
{
	// A SMOB type for everything, incuding atoms.
	cog_misc_tag = scm_make_smob_type ("opencog-misc", sizeof (scm_t_bits));
	scm_set_smob_print (cog_misc_tag, print_misc);
	scm_set_smob_equalp (cog_misc_tag, equalp_misc);
	// scm_set_smob_mark (cog_misc_tag, mark_misc);
	scm_set_smob_free (cog_misc_tag, free_misc);
}

/* ============================================================== */

SCM SchemeSmob::equalp_misc(SCM a, SCM b)
{
	// If they're not something we know about, let scheme sort it out.
	// (Actualy, this should never happen ...)
	if (not SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, a))
		return scm_equal_p(a, b);

	// If the types don't match, they can't be equal.
	scm_t_bits ta = SCM_SMOB_FLAGS(a);
	scm_t_bits tb = SCM_SMOB_FLAGS(b);
	if (ta != tb)
		return SCM_BOOL_F;

	switch (ta)
	{
		default: // Should never happen.
		case 0:  // Should never happen.
			return SCM_BOOL_F;
		case COG_AS:
		{
			AtomSpace* as = (AtomSpace *) SCM_SMOB_DATA(a);
			AtomSpace* bs = (AtomSpace *) SCM_SMOB_DATA(b);
			scm_remember_upto_here_1(a);
			scm_remember_upto_here_1(b);
			/* Just a simple pointer comparison */
			if (as == bs) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
		case COG_AV:
		{
			AttentionValue* av = (AttentionValue *) SCM_SMOB_DATA(a);
			AttentionValue* bv = (AttentionValue *) SCM_SMOB_DATA(b);
			scm_remember_upto_here_1(a);
			scm_remember_upto_here_1(b);
			if (av == bv) return SCM_BOOL_T;
			if (*av == *bv) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
		case COG_EXTEND:
		{
			// We compare pointers here, only.
			PrimitiveEnviron* av = (PrimitiveEnviron *) SCM_SMOB_DATA(a);
			PrimitiveEnviron* bv = (PrimitiveEnviron *) SCM_SMOB_DATA(b);
			scm_remember_upto_here_1(a);
			scm_remember_upto_here_1(b);
			if (av == bv) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
		case COG_HANDLE:
		{
			Handle ha(scm_to_handle(a));
			Handle hb(scm_to_handle(b));
			if (ha == hb) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
		case COG_TV:
		{
			TruthValue* av = (TruthValue *) SCM_SMOB_DATA(a);
			TruthValue* bv = (TruthValue *) SCM_SMOB_DATA(b);
			scm_remember_upto_here_1(a);
			scm_remember_upto_here_1(b);
			if (av == bv) return SCM_BOOL_T;
			if (*av == *bv) return SCM_BOOL_T;
			return SCM_BOOL_F;
		}
	}
}

/* ============================================================== */

void SchemeSmob::throw_exception(const char *msg, const char * func)
{
	if (msg and msg[0] != 0)
	{
		// Should we even bother to log this?  Probably not ...
		logger().info("Guile caught C++ exception: %s", msg);

		// scm_misc_error(fe->get_name(), msg, SCM_EOL);
		scm_throw(
			scm_from_utf8_symbol("C++-EXCEPTION"),
			scm_cons(
				scm_from_utf8_string(func),
				scm_cons(
					scm_from_utf8_string(msg),
					SCM_EOL)));
		// Hmm. scm_throw never returns.
	}
	else
	{
		// scm_misc_error(fe->get_name(), "unknown C++ exception", SCM_EOL);
		scm_error_scm(
			scm_from_utf8_symbol("C++ exception"),
			scm_from_utf8_string(func),
			scm_from_utf8_string("unknown C++ exception"),
			SCM_EOL,
			SCM_EOL);
		logger().error("Guile caught unknown C++ exception");
	}
}

/* ============================================================== */

#ifdef HAVE_GUILE2
 #define C(X) ((scm_t_subr) X)
#else
 #define C(X) ((SCM (*) ()) X)
#endif

void SchemeSmob::register_procs(void*)
{
	register_proc("cog-atom",              1, 0, 0, C(ss_atom));
	register_proc("cog-handle",            1, 0, 0, C(ss_handle));
	register_proc("cog-undefined-handle",  0, 0, 0, C(ss_undefined_handle));
	register_proc("cog-new-value",         1, 0, 1, C(ss_new_value));
	register_proc("cog-new-node",          2, 0, 1, C(ss_new_node));
	register_proc("cog-new-link",          1, 0, 1, C(ss_new_link));
	register_proc("cog-node",              2, 0, 1, C(ss_node));
	register_proc("cog-link",              1, 0, 1, C(ss_link));
	register_proc("cog-delete",            1, 0, 1, C(ss_delete));
	register_proc("cog-delete-recursive",  1, 0, 1, C(ss_delete_recursive));
	register_proc("cog-purge",             1, 0, 1, C(ss_purge));
	register_proc("cog-purge-recursive",   1, 0, 1, C(ss_purge_recursive));
	register_proc("cog-value?",            1, 0, 1, C(ss_value_p));
	register_proc("cog-atom?",             1, 0, 1, C(ss_atom_p));
	register_proc("cog-node?",             1, 0, 1, C(ss_node_p));
	register_proc("cog-link?",             1, 0, 1, C(ss_link_p));

	// property setters on atoms
	register_proc("cog-set-av!",           2, 0, 0, C(ss_set_av));
	register_proc("cog-set-tv!",           2, 0, 0, C(ss_set_tv));
	register_proc("cog-merge-tv!",         2, 0, 0, C(ss_merge_tv));
	register_proc("cog-merge-hi-conf-tv!", 2, 0, 0, C(ss_merge_hi_conf_tv));
	register_proc("cog-inc-vlti!",         1, 0, 0, C(ss_inc_vlti));
	register_proc("cog-dec-vlti!",         1, 0, 0, C(ss_dec_vlti));

	// property getters on atoms
	register_proc("cog-name",              1, 0, 0, C(ss_name));
	register_proc("cog-type",              1, 0, 0, C(ss_type));
	register_proc("cog-arity",             1, 0, 0, C(ss_arity));
	register_proc("cog-incoming-set",      1, 0, 0, C(ss_incoming_set));
	register_proc("cog-outgoing-set",      1, 0, 0, C(ss_outgoing_set));
	register_proc("cog-tv",                1, 0, 0, C(ss_tv));
	register_proc("cog-av",                1, 0, 0, C(ss_av));
	register_proc("cog-as",                1, 0, 0, C(ss_as));

	// Truth-values
	register_proc("cog-new-stv",           2, 0, 0, C(ss_new_stv));
	register_proc("cog-new-ctv",           3, 0, 0, C(ss_new_ctv));
	register_proc("cog-new-itv",           3, 0, 0, C(ss_new_itv));
	register_proc("cog-new-ptv",           3, 0, 0, C(ss_new_ptv));
	register_proc("cog-new-ftv",           2, 0, 0, C(ss_new_ftv));
	register_proc("cog-tv?",               1, 0, 0, C(ss_tv_p));
	register_proc("cog-stv?",              1, 0, 0, C(ss_stv_p));
	register_proc("cog-ctv?",              1, 0, 0, C(ss_ctv_p));
	register_proc("cog-itv?",              1, 0, 0, C(ss_itv_p));
	register_proc("cog-ptv?",              1, 0, 0, C(ss_ptv_p));
	register_proc("cog-ftv?",              1, 0, 0, C(ss_ftv_p));
	register_proc("cog-tv->alist",         1, 0, 0, C(ss_tv_get_value));
	register_proc("cog-tv-mean",           1, 0, 0, C(ss_tv_get_mean));
	register_proc("cog-tv-confidence",     1, 0, 0, C(ss_tv_get_confidence));
	register_proc("cog-tv-count",          1, 0, 0, C(ss_tv_get_count));

	// Atom Spaces
	register_proc("cog-new-atomspace",     0, 1, 0, C(ss_new_as));
	register_proc("cog-atomspace?",        1, 0, 0, C(ss_as_p));
	register_proc("cog-atomspace",         0, 0, 0, C(ss_get_as));
	register_proc("cog-set-atomspace!",    1, 0, 0, C(ss_set_as));
	register_proc("cog-atomspace-env",     1, 0, 0, C(ss_as_env));
	register_proc("cog-atomspace-uuid",    1, 0, 0, C(ss_as_uuid));
	register_proc("cog-atomspace-clear",   1, 0, 0, C(ss_as_clear));

	// Attention values
	register_proc("cog-new-av",            3, 0, 0, C(ss_new_av));
	register_proc("cog-av?",               1, 0, 0, C(ss_av_p));
	register_proc("cog-av->alist",         1, 0, 0, C(ss_av_get_value));

	// AttentionalFocus
	register_proc("cog-af-boundary",       0, 0, 0, C(ss_af_boundary));
	register_proc("cog-set-af-boundary!",  1, 0, 0, C(ss_set_af_boundary));
	register_proc("cog-af",                0, 0, 0, C(ss_af));

	// Atom types
	register_proc("cog-get-types",         0, 0, 0, C(ss_get_types));
	register_proc("cog-type->int",         1, 0, 0, C(ss_get_type));
	register_proc("cog-type?",             1, 0, 0, C(ss_type_p));
	register_proc("cog-value-type?",       1, 0, 0, C(ss_value_type_p));
	register_proc("cog-node-type?",        1, 0, 0, C(ss_node_type_p));
	register_proc("cog-link-type?",        1, 0, 0, C(ss_link_type_p));
	register_proc("cog-get-subtypes",      1, 0, 0, C(ss_get_subtypes));
	register_proc("cog-subtype?",          2, 0, 0, C(ss_subtype_p));

	// Iterators
	register_proc("cog-map-type",          2, 0, 0, C(ss_map_type));
}

void SchemeSmob::register_proc(const char* name, int req, int opt, int rst, scm_t_subr fcn)
{
	scm_c_define_gsubr(name, req, opt, rst, fcn);
	scm_c_export(name, NULL);
}

#endif
/* ===================== END OF FILE ============================ */
<|endoftext|>


<commit_before>#include <cmath>

#include <Bull/Window/JoystickManager.hpp>

namespace Bull
{
    namespace prv
    {
        JoystickManager::JoystickManager() :
            m_keyrepeat(true),
            m_threshold(0.f),
            m_repeatDelay(0.f)
        {
            /// Nothing
        }

        void JoystickManager::processEvents(std::queue<WindowEvent>& eventQueue)
        {
            for(unsigned int i = 0; i < Joystick::Count; i++)
            {
                processJoystick(i, eventQueue);
            }
        }

        void JoystickManager::enableKeyRepeat(bool enable)
        {
            m_keyrepeat = enable;
        }

        bool JoystickManager::isKeyRepeatEnable() const
        {
            return m_keyrepeat;
        }

        void JoystickManager::setThreshold(float threshold)
        {
            m_threshold = threshold;
        }

        float JoystickManager::getThreshold() const
        {
            return m_threshold;
        }

        void JoystickManager::setRepeatDelay(const Time& delay)
        {
            m_repeatDelay = delay;
        }

        const Time& JoystickManager::getRepeatDelay()
        {
            return m_repeatDelay;
        }

        void JoystickManager::processJoystick(Uint8 joystick, std::queue<WindowEvent>& eventQueue)
        {
            JoystickState state(joystick);
            JoystickState cached = m_stateCache[joystick];

            if(!state.connected && !cached.connected)
            {
                return;
            }

            if(state.connected != cached.connected)
            {
                WindowEvent e;

                e.type = (state.connected) ? WindowEvent::JoystickConnected : WindowEvent::JoystickDisconnected;

                e.joystickConnection.joystick = joystick;

                eventQueue.push(e);
            }

            for(unsigned int i = 0; i < state.buttons.size(); i++)
            {
                if(cached.buttons[i].second.isRunning())
                {
                    state.buttons[i].second = cached.buttons[i].second;
                }

                if(state.buttons[i].first != cached.buttons[i].first)
                {
                    WindowEvent e;
                    e.type = (state.buttons[i].first) ? WindowEvent::JoystickButtonDown : WindowEvent::JoystickButtonUp;

                    e.joystickButton.joystick = joystick;
                    e.joystickButton.button   = static_cast<Uint8>(i);

                    eventQueue.push(e);

                    if(e.type == WindowEvent::JoystickButtonDown)
                    {
                        state.buttons[i].second.start();
                    }
                    else
                    {
                        state.buttons[i].second.restart();
                    }
                }
                else if(state.buttons[i].first &&
                        cached.buttons[i].first &&
                        m_keyrepeat &&
                        cached.buttons[i].second.getElapsedTime() > m_repeatDelay)
                {
                    WindowEvent e;
                    e.type = WindowEvent::JoystickButtonDown;

                    e.joystickButton.joystick = joystick;
                    e.joystickButton.button   = static_cast<Uint8>(i);

                    eventQueue.push(e);

                    state.buttons[i].second.restart();
                }
            }

            for(unsigned int i = 0; i < state.axes.size(); i++)
            {
                float relative = state.axes[i] - cached.axes[i];

                if(state.axes[i] != cached.axes[i] && std::abs(relative) > m_threshold)
                {
                    WindowEvent e;

                    e.type = WindowEvent::JoystickMoved;

                    e.joystickMoved.joystick = joystick;
                    e.joystickMoved.axis     = static_cast<Joystick::Axis>(i);
                    e.joystickMoved.position = state.axes[i];
                    e.joystickMoved.relative = relative;

                    eventQueue.push(e);
                }
            }

            m_stateCache[joystick] = state;
        }
    }
}
<commit_msg>[Core/NonMovable] Add NonMovable pattern<commit_after>#include <cmath>

#include <Bull/Window/JoystickManager.hpp>

namespace Bull
{
    namespace prv
    {
        JoystickManager::JoystickManager() :
            m_keyrepeat(true),
            m_threshold(0.f),
            m_repeatDelay(0.f)
        {
            /// Nothing
        }

        void JoystickManager::processEvents(std::queue<WindowEvent>& eventQueue)
        {
            for(Uint8 i = 0; i < Joystick::Count; i++)
            {
                processJoystick(i, eventQueue);
            }
        }

        void JoystickManager::enableKeyRepeat(bool enable)
        {
            m_keyrepeat = enable;
        }

        bool JoystickManager::isKeyRepeatEnable() const
        {
            return m_keyrepeat;
        }

        void JoystickManager::setThreshold(float threshold)
        {
            m_threshold = threshold;
        }

        float JoystickManager::getThreshold() const
        {
            return m_threshold;
        }

        void JoystickManager::setRepeatDelay(const Time& delay)
        {
            m_repeatDelay = delay;
        }

        const Time& JoystickManager::getRepeatDelay()
        {
            return m_repeatDelay;
        }

        void JoystickManager::processJoystick(Uint8 joystick, std::queue<WindowEvent>& eventQueue)
        {
            JoystickState state(joystick);
            JoystickState cached = m_stateCache[joystick];

            if(!state.connected && !cached.connected)
            {
                return;
            }

            if(state.connected != cached.connected)
            {
                WindowEvent e;

                e.type = (state.connected) ? WindowEvent::JoystickConnected : WindowEvent::JoystickDisconnected;

                e.joystickConnection.joystick = joystick;

                eventQueue.push(e);
            }

            for(unsigned int i = 0; i < state.buttons.size(); i++)
            {
                if(cached.buttons[i].second.isRunning())
                {
                    state.buttons[i].second = cached.buttons[i].second;
                }

                if(state.buttons[i].first != cached.buttons[i].first)
                {
                    WindowEvent e;
                    e.type = (state.buttons[i].first) ? WindowEvent::JoystickButtonDown : WindowEvent::JoystickButtonUp;

                    e.joystickButton.joystick = joystick;
                    e.joystickButton.button   = static_cast<Uint8>(i);

                    eventQueue.push(e);

                    if(e.type == WindowEvent::JoystickButtonDown)
                    {
                        state.buttons[i].second.start();
                    }
                    else
                    {
                        state.buttons[i].second.restart();
                    }
                }
                else if(state.buttons[i].first &&
                        cached.buttons[i].first &&
                        m_keyrepeat &&
                        cached.buttons[i].second.getElapsedTime() > m_repeatDelay)
                {
                    WindowEvent e;
                    e.type = WindowEvent::JoystickButtonDown;

                    e.joystickButton.joystick = joystick;
                    e.joystickButton.button   = static_cast<Uint8>(i);

                    eventQueue.push(e);

                    state.buttons[i].second.restart();
                }
            }

            for(unsigned int i = 0; i < state.axes.size(); i++)
            {
                float relative = state.axes[i] - cached.axes[i];

                if(state.axes[i] != cached.axes[i] && std::abs(relative) > m_threshold)
                {
                    WindowEvent e;

                    e.type = WindowEvent::JoystickMoved;

                    e.joystickMoved.joystick = joystick;
                    e.joystickMoved.axis     = static_cast<Joystick::Axis>(i);
                    e.joystickMoved.position = state.axes[i];
                    e.joystickMoved.relative = relative;

                    eventQueue.push(e);
                }
            }

            m_stateCache[joystick] = state;
        }
    }
}
<|endoftext|>


<commit_before>/*
// Copyright (c) 2018 Intel Corporation
//
// 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 <iomanip>
#include <vector>
#include <memory>
#include <string>
#include <cstdlib>
#include <vector>

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <inference_engine.hpp>

// window height and width 4:3 ratio
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
#define WINDOW_NAME "simple_classifier_cpp_camera - Press any key to quit"

using namespace InferenceEngine;

#define TEXTGREEN  '\033[1;32m'
#define TEXTRED '\033[1;31m'
#define TEXTNOCOLOR '\033[0m'
#define TEXTYELLOW '\033[1;33m'

const std::string DEVICE = "MYRIAD";
std::vector<std::string> labels;
const unsigned int MAX_PATH = 256;

const int FONT = cv::FONT_HERSHEY_SIMPLEX;
const float FONT_SIZE = 0.5;
const cv::Scalar BLUE = cv::Scalar(255, 0, 0, 255);
const cv::Scalar GREEN = cv::Scalar(0, 255, 0, 255);
unsigned int SKIP_AFTER = 5;

void getNetworkLabels(std::string labelsDir, std::vector<std::string>* labelsVector)
{
    char filename[MAX_PATH];
    strncpy(filename, labelsDir.c_str(), MAX_PATH);
    FILE* cat_file = fopen(filename, "r");
    if (cat_file == nullptr) {
        std::cerr << "Could not find Category file." << std::endl;
        exit(1);
    }

    char cat_line[255];
    while (fgets(cat_line , 255 , cat_file) != NULL) {
        if (cat_line[strlen(cat_line) - 1] == '\n')
            cat_line[strlen(cat_line) - 1] = '\0';
        labelsVector->push_back(std::string(cat_line));
    }
    fclose (cat_file);
}

int main(int argc, char *argv[]) {
    try {
        if (argc != 3) {
            std::cout << "Usage : ./simple_classifier_cpp_camera <path_to_model> <path_to_labels>" << std::endl;
            return EXIT_FAILURE;
        }
        std::cout << "\n Press any key to quit.\n";
        const std::string input_model{argv[1]};
        const std::string labels_file{argv[2]};

        cv::Mat frame;
        int key;
        cv::VideoCapture capture;

        // Set up the camera
        capture.open(0);
        capture.set(cv::CAP_PROP_FRAME_WIDTH, WINDOW_WIDTH);
        capture.set(cv::CAP_PROP_FRAME_HEIGHT, WINDOW_HEIGHT);

        // Set up the display window
        cv::namedWindow(WINDOW_NAME, cv::WINDOW_AUTOSIZE);
        cv::resizeWindow(WINDOW_NAME, WINDOW_WIDTH, WINDOW_HEIGHT);
        cv::moveWindow(WINDOW_NAME, 0, 0);

        // Create the ie core object
        Core ie;

        // --------------------Load IR Generated by ModelOptimizer (.xml and .bin files)------------------------
        // Read the xml and bin files, set the batch size and get the network object
        CNNNetReader network_reader;
        network_reader.ReadNetwork(input_model);
        network_reader.ReadWeights(input_model.substr(0, input_model.size() - 4) + ".bin");
        network_reader.getNetwork().setBatchSize(1);
        CNNNetwork network = network_reader.getNetwork();

        // -----------------------------Prepare input blobs-----------------------------------------------------

        auto input_info = network.getInputsInfo().begin()->second;
        // Get the input node name
        auto input_name = network.getInputsInfo().begin()->first;

        input_info->setPrecision(Precision::U8);

        // ---------------------------Prepare output blobs------------------------------------------------------

        auto output_info = network.getOutputsInfo().begin()->second;
        // Get the output node name
        auto output_name = network.getOutputsInfo().begin()->first;

        output_info->setPrecision(Precision::FP32);

        // -------------------------Loading model to the plugin and then infer----------------------------------
        // Create executable network object by loading the network via ie core api
        auto executable_network = ie.LoadNetwork(network, DEVICE);
        // Create the inference request
        auto infer_request = executable_network.CreateInferRequestPtr();
        // Set the precision for the input
        auto input = infer_request->GetBlob(input_name);
        auto input_data = input->buffer().as<PrecisionTrait<Precision::U8>::value_type*>();

        // Get various input dimension values
        unsigned int channels_number = input->getTensorDesc().getDims().at(1);
        unsigned int net_input_height = input->getTensorDesc().getDims().at(2);
        unsigned int net_input_width = input->getTensorDesc().getDims().at(3);

        unsigned int frame_count = 0;
        // Main loop
        while (true)
        {
            // Read a frame
            capture >> frame;
            if (frame_count++ >= SKIP_AFTER) {
    	        capture >> frame;
                frame_count = 0;
            }
            // Flip the image horizontally
            cv::flip(frame, frame, 1);
            cv::Mat imgInput;
            // Image preprocessing
            cv::resize(frame, imgInput, cv::Size(net_input_height, net_input_width));
            // Buffer for input
            size_t image_size = net_input_height * net_input_width;
            // Fill the buffer with the input image data
            for (size_t pid = 0; pid < image_size; ++pid) {
                for (size_t ch = 0; ch < channels_number; ++ch) {
                    input_data[ch * image_size + pid] = imgInput.at<cv::Vec3b>(pid)[ch];
                }
            }

            /* Running the request synchronously */
            infer_request->StartAsync();
            if (OK == infer_request->Wait(IInferRequest::WaitMode::RESULT_READY)) {
                // ---------------------------Postprocess output blobs--------------------------------------------------
                // Get the inference results
                auto output = infer_request->GetBlob(output_name);
                auto output_data = output->buffer().as<PrecisionTrait<Precision::FP32>::value_type*>();
                // How many results should we display?
                unsigned int results_to_display = 1;

                /*  This is to sort output probabilities and put it to results vector */
                std::vector<unsigned> results;
                TopResults(results_to_display, *output, results);

                // Read the network labels
                getNetworkLabels(labels_file, &labels);

                // Get the top result
                auto result = output_data[results[0]];
                // Put together the result text that we will display
                std::string resultText = labels[results.at(0)] + " - " + std::to_string((int)(result*100)) + "%";
                // Determine the text size
                cv::Size text_size = cv::getTextSize(resultText, cv::FONT_HERSHEY_SIMPLEX, FONT_SIZE, 0, 0);
                // Draw a gray rectangle for text background
                cv::rectangle(frame, cv::Point2f(0,WINDOW_HEIGHT-20), cv::Point2f(WINDOW_WIDTH, WINDOW_HEIGHT), cv::Scalar(75,75,75), cv::FILLED);
                // Calculate the coordinate to print the text so that the text is centered
                int print_text_width = (int)((WINDOW_WIDTH - text_size.width)/2);
                // Put the text in the frame
                cv::putText(frame, resultText, cv::Point2f(print_text_width, WINDOW_HEIGHT-5), FONT, FONT_SIZE, GREEN, 1);
            }
            // Display the image in the window
            imshow(WINDOW_NAME, frame);

            // If the user presses the break key exit the loop
            key = cv::waitKey(1);
            if (key != -1) {
                break;
            }
        }
        cv::destroyAllWindows();
    } catch (const std::exception & ex) {
      std::cerr << ex.what() << std::endl;
      return EXIT_FAILURE;
    }
    std::cout << "\n Finished.\n";
    return EXIT_SUCCESS;
}

<commit_msg>Rewritten to get rid of apache license<commit_after>// Simple classifier cpp camera

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <inference_engine.hpp>
#include <vector>

using namespace InferenceEngine;

#define DEVICE "MYRIAD"

// window properties
#define WINDOW_NAME "simple_classifier_cpp_camera - Press any key to quit"
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480

// text properties
const int FONT = cv::FONT_HERSHEY_SIMPLEX;
const float FONT_SIZE = 0.5;
const cv::Scalar BLUE = cv::Scalar(255, 0, 0, 255);
const cv::Scalar GREEN = cv::Scalar(0, 255, 0, 255);

std::vector<std::string> labels;
const unsigned int MAX_PATH = 256;
unsigned int SKIP_AFTER = 5;

// *************************************************************************
// Read the network labels from the provided labels file
// *************************************************************************
void getNetworkLabels(std::string labelsDir, std::vector<std::string>* labelsVector)
{
    char filename[MAX_PATH];
    strncpy(filename, labelsDir.c_str(), MAX_PATH);
    FILE* cat_file = fopen(filename, "r");
    if (cat_file == nullptr) {
        std::cerr << "Could not find Category file." << std::endl;
        exit(1);
    }

    char cat_line[255];
    while (fgets(cat_line , 255 , cat_file) != NULL) {
        if (cat_line[strlen(cat_line) - 1] == '\n')
            cat_line[strlen(cat_line) - 1] = '\0';
        labelsVector->push_back(std::string(cat_line));
    }
    fclose (cat_file);
}

// *************************************************************************
// Entrypoint for the application
// *************************************************************************
int main(int argc, char *argv[]) {
    cv::Mat imgInput;
    unsigned int frameCount = 0;

    if (argc != 3) {
        std::cout << " ./simple_classifier_cpp <XML FILE> <LABELS> ";
        exit(1);
    }
    // Get all of the parameters that we need to run the inference
    std::string XML = argv[1];
    std::string BIN = XML.substr(0, XML.length()-3) + "bin";
    std::string LABELS = argv[2];

    cv::Mat frame;
    int key;
    cv::VideoCapture capture;

    // Set up the camera
    capture.open(0);
    capture.set(cv::CAP_PROP_FRAME_WIDTH, WINDOW_WIDTH);
    capture.set(cv::CAP_PROP_FRAME_HEIGHT, WINDOW_HEIGHT);

    // Set up the display window
    cv::namedWindow(WINDOW_NAME, cv::WINDOW_AUTOSIZE);
    cv::resizeWindow(WINDOW_NAME, WINDOW_WIDTH, WINDOW_HEIGHT);
    cv::moveWindow(WINDOW_NAME, 0, 0);

    // Read the labels
    getNetworkLabels(LABELS, &labels);

    // ----------------------- Create IE core object and read the network ----------------------- //
    // Create the inference engine core object
    Core ie_core;
    // Create a network reader and read in the network and weights
    CNNNetReader networkReader;
    networkReader.ReadNetwork(XML);
    networkReader.ReadWeights(BIN);
    auto network = networkReader.getNetwork();

    // ----------------------- Set up the network input ----------------------- //
    InputsDataMap inputDataMap(network.getInputsInfo());
    InputInfo::Ptr& inputInfo = inputDataMap.begin()->second;
    // Get the input node name
    std::string inputLayerName = inputDataMap.begin()->first;
    // Set precision for the input
    inputInfo->setPrecision(Precision::U8);

    // ----------------------- Set up the network output ----------------------- //
    OutputsDataMap outputDataMap(network.getOutputsInfo());
    auto outputData = outputDataMap.begin()->second;
    // Get the output node name
    std::string outputLayerName = outputDataMap.begin()->first;
    // Set precision for output
    outputData->setPrecision(Precision::FP32);

    // ----------------------- Load the network and create the inference request ----------------------- //
    // Load the network to the device (default: Myriad)
    auto executableNetwork = ie_core.LoadNetwork(network, DEVICE);
    // Create the inference request
    auto inferenceRequest = executableNetwork.CreateInferRequestPtr();

    // ----------------------- 5. Prepare the input data ----------------------- //
    // Create buffer to hold input data
    auto inputBlob = inferenceRequest->GetBlob(inputLayerName);
    auto inputData = inputBlob->buffer().as<PrecisionTrait<Precision::U8>::value_type*>();

    // Get the input dimensions for the network
    auto inputDims = inferenceRequest->GetBlob(inputLayerName)->getTensorDesc().getDims();
    unsigned int inputNumberOfChannels = inputDims.at(1);
    unsigned int inputHeight = inputDims.at(2);
    unsigned int inputWidth = inputDims.at(3);

    while (true) {

        // Use OpenCV to read in an image

        capture >> frame;
        if (frameCount++ >= SKIP_AFTER) {
            capture >> frame;
            frameCount = 0;
        }
        // Flip the image horizontally
        cv::flip(frame, frame, 1);
        // Resize the input image in accordance to the network input size
        cv::resize(frame, imgInput, cv::Size(inputHeight, inputWidth));

        // Prepare to fill the buffer with the image data
        size_t imageSize = inputHeight * inputWidth;
        // Fills buffer with the image data. This data will be sent to the device for inference
        for (size_t pixelIndex = 0; pixelIndex < imageSize; ++pixelIndex) {
            for (size_t channel = 0; channel < inputNumberOfChannels; ++channel) {
                inputData[channel * imageSize + pixelIndex] = imgInput.at<cv::Vec3b>(pixelIndex)[channel];
            }
        }

        // ----------------------- 6. Make the inference ----------------------- //
        inferenceRequest->StartAsync();
        if (OK == inferenceRequest->Wait(IInferRequest::WaitMode::RESULT_READY)) {
            // ----------------------- 7. Process the results ----------------------- //
            // Get the inference results
            auto inferenceResults = inferenceRequest->GetBlob(outputLayerName);
            // Get all of the confidence scores.
            auto scores = inferenceResults->buffer().as<PrecisionTrait<Precision::FP32>::value_type*>();

            // Sort the results and get the number of desired top results
            std::vector<unsigned> sortedResults; // This vector will hold all of the top sorted results
            unsigned int resultsToDisplay = 1;   // How many results should return?
            TopResults(resultsToDisplay, *inferenceResults, sortedResults);

            // Get the top result
            auto topScore = scores[sortedResults[0]] * 100;
            // Put together the result text that we will display
            std::string resultText = labels[sortedResults.at(0)] + " - " + std::to_string((int)(topScore)) + "%";
            // Determine the text size
            cv::Size textSize = cv::getTextSize(resultText, cv::FONT_HERSHEY_SIMPLEX, FONT_SIZE, 0, 0);
            // Draw a gray rectangle for text background
            cv::rectangle(frame, cv::Point2f(0,WINDOW_HEIGHT-20), cv::Point2f(WINDOW_WIDTH, WINDOW_HEIGHT), cv::Scalar(75,75,75), cv::FILLED);
            // Calculate the coordinate to print the text so that the text is centered
            int printTextWidth = (int)((WINDOW_WIDTH - textSize.width)/2);
            // Put the text in the frame
            cv::putText(frame, resultText, cv::Point2f(printTextWidth, WINDOW_HEIGHT-5), FONT, FONT_SIZE, GREEN, 1);
        }

        // Display the image in the window
        imshow(WINDOW_NAME, frame);

        // If the user presses the break key exit the loop
        key = cv::waitKey(1);
        if (key != -1) {
            break;
        }
    }
    cv::destroyAllWindows();
    std::cout << "\n Finished.\n";
}
<|endoftext|>


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

#ifndef _SALUNX_H
#include <salunx.h>
#endif
#ifndef _VCL_VCLENUM_HXX
#include <enum.hxx>
#endif

class Xlfd;
class AttributeProvider;
class ImplFontData;
class ByteString;

// --------------------------------------------------------------------------
//
//  classes for Xlfd handling that contain more than a single encoding.
//  Members that may vary through different encodings are stored in
//  a mpEncodingInfo member. There are three different classes:
//  true scalable fonts (truetype and type1) scalable bitmap fonts
//  (the ugly ones) and bitmap fonts. The ExtendedXlfd stores all the members
//  that are specific to a font outline
//  ( e.g. adobe-times-roman-medium-r-normal- * -p- * )
//  and specifies the interface.
//
// --------------------------------------------------------------------------

// base class

class VirtualXlfd;
class XlfdStorage;

class ExtendedXlfd {

    friend VirtualXlfd;
    friend XlfdStorage;

    public:
                             ExtendedXlfd();
        virtual             ~ExtendedXlfd();
        virtual Bool        AddEncoding( const Xlfd *pXlfd );
        Bool                HasEncoding( rtl_TextEncoding nEncoding ) const;
        int                 GetEncodingIdx( rtl_TextEncoding nEncoding ) const;
        unsigned short      NumEncodings() const
                                    { return mnEncodings; }
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                       rtl_TextEncoding nEncoding ) const ;
        virtual void        ToString( ByteString &rString,
                                      unsigned short nPixelSize,
                                     char* pMatricsString,
                                       rtl_TextEncoding nEncoding  ) const;

        virtual void        ToImplFontData( ImplFontData *pFontData ) const ;
        virtual FontType    GetFontType() const { return TYPE_DONTKNOW; }
        FontFamily          GetFamily() const;
        FontWeight          GetWeight() const;
        FontItalic          GetItalic() const;
        FontWidth           GetWidth() const;
        virtual FontPitch   GetSpacing() const;
        virtual FontPitch   GetSpacing( rtl_TextEncoding nEnc ) const;
        rtl_TextEncoding    GetAsciiEncoding( int *pAsciiRange = NULL ) const;
        rtl_TextEncoding    GetEncoding() const;
        rtl_TextEncoding    GetEncoding( int i ) const;

        int                 GetFontCodeRanges( sal_uInt32* pCodePairs ) const;

        #if OSL_DEBUG_LEVEL > 1
        void                Dump() const;
        #endif

    protected:

        AttributeProvider*  mpFactory;

    #ifdef GCC
    public:
    #endif

        unsigned short      mnFoundry;
        unsigned short      mnFamily;
        unsigned short      mnWeight;
        unsigned short      mnSlant;
        unsigned short      mnSetwidth;

    #ifdef GCC
    protected:
    #endif

        unsigned short      mnEncodings;
        struct EncodingInfo {
            unsigned char       mcSpacing;
            unsigned short      mnResolutionX;
            unsigned short      mnResolutionY;
            unsigned short      mnAddstyle;
            unsigned short      mnCharset;

            rtl_TextEncoding    mnEncoding;

            EncodingInfo&       operator= ( const Xlfd *pXlfd );
            EncodingInfo&       operator= ( const EncodingInfo& rInfo );
        } *mpEncodingInfo;
};

// class to handle scalable bitmap fonts

class ScalableBitmapXlfd : public ExtendedXlfd {

    public:
                            ScalableBitmapXlfd();
        virtual             ~ScalableBitmapXlfd();
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    rtl_TextEncoding nEncoding ) const;
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    char* pMatricsString,
                                    rtl_TextEncoding nEncoding ) const;

        virtual void        ToImplFontData( ImplFontData *pFontData ) const;
        virtual FontType    GetFontType() const
                                    { return TYPE_SCALABLE; }
};

// class to handle true bitmap fonts

class ScalableXlfd;

class BitmapXlfd : public ExtendedXlfd {

    public:
                            BitmapXlfd();
                            ~BitmapXlfd();
        Bool                AddEncoding( const Xlfd *pXlfd );
        Bool                AddEncoding( const ScalableXlfd *pXlfd );
        unsigned short      GetPixelSize() const
                                    { return mnPixelSize; }
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    rtl_TextEncoding nEncoding ) const;
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    char* pMatricsString,
                                    rtl_TextEncoding nEncoding ) const;
        virtual void        ToImplFontData( ImplFontData *pFontData ) const ;
        virtual FontType    GetFontType() const
                                    { return TYPE_RASTER; }
    protected:

        unsigned short      mnPixelSize;
        unsigned short      mnPointSize;
        unsigned short      mnAverageWidth;
};

// class to handle true scalable fonts

class ScalableXlfd : public ExtendedXlfd {

    friend class BitmapXlfd;

    public:
                            ScalableXlfd();
        virtual             ~ScalableXlfd();
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    rtl_TextEncoding nEncoding ) const;

        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    char* pMatricsString,
                                    rtl_TextEncoding  nEncoding ) const;
        virtual void        ToImplFontData( ImplFontData *pFontData ) const ;
        virtual FontType    GetFontType() const
                                    { return TYPE_SCALABLE; }
};

// class to maintain a list of fonts ( bitmap and scalable )

class XlfdStorage {

    public:
                            XlfdStorage();
                            ~XlfdStorage();

        void                Dispose();
        void                Reset();

        void                Add( const ExtendedXlfd *pXlfd );
        void                Add( const XlfdStorage *pXlfd );
        unsigned short      GetCount() const
                                    { return mnCount; }
        const ExtendedXlfd* Get(int nIdx) const;
        #if OSL_DEBUG_LEVEL > 1
        void                Dump() const ;
        #endif

    protected:

        void                Enlarge();

        unsigned short      mnCount;
        unsigned short      mnSize;
        const ExtendedXlfd**
                            mpList;
};

// list of fonts specific for bitmap fonts

class BitmapXlfdStorage : public XlfdStorage {

    public:

        void                AddBitmapFont( const Xlfd *pXlfd );
};

/* Virtual font for User Interface */

class VirtualXlfd : public ExtendedXlfd
{
    private:

        int                 GetFontQuality (unsigned short nFamily);

    public:
                             VirtualXlfd();
        virtual             ~VirtualXlfd();
        virtual Bool        AddEncoding( const Xlfd *pXlfd );
        void                FilterInterfaceFont (const Xlfd *pXlfd);
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                       rtl_TextEncoding nEncoding ) const ;
        virtual void        ToString( ByteString &rString,
                                      unsigned short nPixelSize,
                                     char* pMatricsString,
                                       rtl_TextEncoding nEncoding  ) const;

        virtual void        ToImplFontData( ImplFontData *pFontData ) const ;
        virtual FontType    GetFontType() const
                                    { return TYPE_SCALABLE; }
    protected:

        struct ExtEncodingInfo {

            unsigned short      mnFoundry;
            unsigned short      mnFamily;
            unsigned short      mnWeight;
            unsigned short      mnSlant;
            unsigned short      mnSetwidth;

            ExtEncodingInfo&    operator= ( const Xlfd *pXlfd );
            ExtEncodingInfo&    operator= ( const ExtEncodingInfo& rInfo );
        } *mpExtEncodingInfo;

    friend class ExtEncodingInfo;
};

#endif /* XLFD_EXTENDED_HXX */

<commit_msg>INTEGRATION: CWS geordi2q10 (1.9.208); FILE MERGED 2003/11/27 10:28:52 rt 1.9.208.1: #111934#: join CWS vcl7pp1r2<commit_after>/*************************************************************************
 *
 *  $RCSfile: xlfd_extd.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2003-12-01 09:58:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef XLFD_EXTENDED_HXX
#define XLFD_EXTENDED_HXX

#ifndef _SALUNX_H
#include <salunx.h>
#endif
#ifndef _VCL_VCLENUM_HXX
#include <enum.hxx>
#endif

class Xlfd;
class AttributeProvider;
class ImplFontData;
class ByteString;

// --------------------------------------------------------------------------
//
//  classes for Xlfd handling that contain more than a single encoding.
//  Members that may vary through different encodings are stored in
//  a mpEncodingInfo member. There are three different classes:
//  true scalable fonts (truetype and type1) scalable bitmap fonts
//  (the ugly ones) and bitmap fonts. The ExtendedXlfd stores all the members
//  that are specific to a font outline
//  ( e.g. adobe-times-roman-medium-r-normal- * -p- * )
//  and specifies the interface.
//
// --------------------------------------------------------------------------

// base class

class VirtualXlfd;
class XlfdStorage;

class ExtendedXlfd {

    friend VirtualXlfd;
    friend XlfdStorage;

    public:
                             ExtendedXlfd();
        virtual             ~ExtendedXlfd();
        virtual Bool        AddEncoding( const Xlfd *pXlfd );
        Bool                HasEncoding( rtl_TextEncoding nEncoding ) const;
        int                 GetEncodingIdx( rtl_TextEncoding nEncoding ) const;
        unsigned short      NumEncodings() const
                                    { return mnEncodings; }
        virtual unsigned short  GetPixelSize( int nOrigPixelSize ) const
                                    { return nOrigPixelSize; }
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                       rtl_TextEncoding nEncoding ) const ;
        virtual void        ToString( ByteString &rString,
                                      unsigned short nPixelSize,
                                     char* pMatricsString,
                                       rtl_TextEncoding nEncoding  ) const;

        virtual void        ToImplFontData( ImplFontData *pFontData ) const ;
        virtual FontType    GetFontType() const { return TYPE_DONTKNOW; }
        FontFamily          GetFamily() const;
        FontWeight          GetWeight() const;
        FontItalic          GetItalic() const;
        FontWidth           GetWidth() const;
        virtual FontPitch   GetSpacing() const;
        virtual FontPitch   GetSpacing( rtl_TextEncoding nEnc ) const;
        rtl_TextEncoding    GetAsciiEncoding( int *pAsciiRange = NULL ) const;
        rtl_TextEncoding    GetEncoding() const;
        rtl_TextEncoding    GetEncoding( int i ) const;

        int                 GetFontCodeRanges( sal_uInt32* pCodePairs ) const;

        #if OSL_DEBUG_LEVEL > 1
        void                Dump() const;
        #endif

    protected:

        AttributeProvider*  mpFactory;

    #ifdef GCC
    public:
    #endif

        unsigned short      mnFoundry;
        unsigned short      mnFamily;
        unsigned short      mnWeight;
        unsigned short      mnSlant;
        unsigned short      mnSetwidth;

    #ifdef GCC
    protected:
    #endif

        unsigned short      mnEncodings;
        struct EncodingInfo {
            unsigned char       mcSpacing;
            unsigned short      mnResolutionX;
            unsigned short      mnResolutionY;
            unsigned short      mnAddstyle;
            unsigned short      mnCharset;

            rtl_TextEncoding    mnEncoding;

            EncodingInfo&       operator= ( const Xlfd *pXlfd );
            EncodingInfo&       operator= ( const EncodingInfo& rInfo );
        } *mpEncodingInfo;
};

// class to handle scalable bitmap fonts

class ScalableBitmapXlfd : public ExtendedXlfd {

    public:
                            ScalableBitmapXlfd();
        virtual             ~ScalableBitmapXlfd();
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    rtl_TextEncoding nEncoding ) const;
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    char* pMatricsString,
                                    rtl_TextEncoding nEncoding ) const;

        virtual void        ToImplFontData( ImplFontData *pFontData ) const;
        virtual FontType    GetFontType() const
                                    { return TYPE_SCALABLE; }
};

// class to handle true bitmap fonts

class ScalableXlfd;

class BitmapXlfd : public ExtendedXlfd {

    public:
                            BitmapXlfd();
                            ~BitmapXlfd();
        Bool                AddEncoding( const Xlfd *pXlfd );
        Bool                AddEncoding( const ScalableXlfd *pXlfd );
        virtual unsigned short  GetPixelSize( int ) const
                                    { return mnPixelSize; }
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    rtl_TextEncoding nEncoding ) const;
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    char* pMatricsString,
                                    rtl_TextEncoding nEncoding ) const;
        virtual void        ToImplFontData( ImplFontData *pFontData ) const ;
        virtual FontType    GetFontType() const
                                    { return TYPE_RASTER; }
    protected:

        unsigned short      mnPixelSize;
        unsigned short      mnPointSize;
        unsigned short      mnAverageWidth;
};

// class to handle true scalable fonts

class ScalableXlfd : public ExtendedXlfd {

    friend class BitmapXlfd;

    public:
                            ScalableXlfd();
        virtual             ~ScalableXlfd();
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    rtl_TextEncoding nEncoding ) const;

        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                    char* pMatricsString,
                                    rtl_TextEncoding  nEncoding ) const;
        virtual void        ToImplFontData( ImplFontData *pFontData ) const ;
        virtual FontType    GetFontType() const
                                    { return TYPE_SCALABLE; }
};

// class to maintain a list of fonts ( bitmap and scalable )

class XlfdStorage {

    public:
                            XlfdStorage();
                            ~XlfdStorage();

        void                Dispose();
        void                Reset();

        void                Add( const ExtendedXlfd *pXlfd );
        void                Add( const XlfdStorage *pXlfd );
        unsigned short      GetCount() const
                                    { return mnCount; }
        const ExtendedXlfd* Get(int nIdx) const;
        #if OSL_DEBUG_LEVEL > 1
        void                Dump() const ;
        #endif

    protected:

        void                Enlarge();

        unsigned short      mnCount;
        unsigned short      mnSize;
        const ExtendedXlfd**
                            mpList;
};

// list of fonts specific for bitmap fonts

class BitmapXlfdStorage : public XlfdStorage {

    public:

        void                AddBitmapFont( const Xlfd *pXlfd );
};

/* Virtual font for User Interface */

class VirtualXlfd : public ExtendedXlfd
{
    private:

        int                 GetFontQuality (unsigned short nFamily);

    public:
                             VirtualXlfd();
        virtual             ~VirtualXlfd();
        virtual Bool        AddEncoding( const Xlfd *pXlfd );
        void                FilterInterfaceFont (const Xlfd *pXlfd);
        virtual void        ToString( ByteString &rString,
                                    unsigned short nPixelSize,
                                       rtl_TextEncoding nEncoding ) const ;
        virtual void        ToString( ByteString &rString,
                                      unsigned short nPixelSize,
                                     char* pMatricsString,
                                       rtl_TextEncoding nEncoding  ) const;

        virtual void        ToImplFontData( ImplFontData *pFontData ) const ;
        virtual FontType    GetFontType() const
                                    { return TYPE_SCALABLE; }
    protected:

        struct ExtEncodingInfo {

            unsigned short      mnFoundry;
            unsigned short      mnFamily;
            unsigned short      mnWeight;
            unsigned short      mnSlant;
            unsigned short      mnSetwidth;

            ExtEncodingInfo&    operator= ( const Xlfd *pXlfd );
            ExtEncodingInfo&    operator= ( const ExtEncodingInfo& rInfo );
        } *mpExtEncodingInfo;

    friend class ExtEncodingInfo;
};

#endif /* XLFD_EXTENDED_HXX */

<|endoftext|>