<commit_before>/*************************************************************************
 *
 *  $RCSfile: sdclient.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:48:34 $
 *
 *  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 _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif

#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _CLIENT_HXX //autogen
#include <so3/client.hxx>
#endif
#ifndef _IPENV_HXX //autogen
#include <so3/ipenv.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif

#pragma hdrstop

#include "misc.hxx"

#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif

#include "strings.hrc"

#include "sdclient.hxx"
#include "viewshel.hxx"
#include "drviewsh.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) :
    SfxInPlaceClient(pSdViewShell, pWindow),
    pViewShell(pSdViewShell),
    pSdrOle2Obj(pObj),
    pSdrGrafObj(NULL),
    pOutlinerParaObj (NULL)
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

__EXPORT SdClient::~SdClient()
{
}

/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/

void __EXPORT SdClient::RequestObjAreaPixel(const Rectangle& rRect)
{
    Window* pWin = pViewShell->GetWindow();
    Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ),
                        pWin->PixelToLogic( rRect.GetSize() ) );

    SdView* pView = pViewShell->GetView();
    Rectangle aWorkArea( pView->GetWorkArea() );

    if (!aWorkArea.IsInside(aObjRect))
    {
        // Position korrigieren
        Point aPos = aObjRect.TopLeft();
        Size  aSize = aObjRect.GetSize();
        Point aWorkAreaTL = aWorkArea.TopLeft();
        Point aWorkAreaBR = aWorkArea.BottomRight();

        aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
        aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
        aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
        aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());

        aObjRect.SetPos(aPos);

        SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()->
                                              LogicToPixel(aObjRect) );
    }
    else
    {
        SfxInPlaceClient::RequestObjAreaPixel(rRect);
    }

    const SdrMarkList& rMarkList = pView->GetMarkList();

    if (rMarkList.GetMarkCount() == 1)
    {
        SdrMark* pMark = rMarkList.GetMark(0);
        SdrObject* pObj = pMark->GetObj();

        Rectangle aOldRect( pObj->GetLogicRect() );

        if ( aObjRect != aOldRect )
        {
            // Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied
            // (getrennt fuer Position und Groesse)
            Size aOnePixel = pWin->PixelToLogic( Size(1, 1) );
            Size aLogicSize = aObjRect.GetSize();
            Rectangle aNewRect = aOldRect;
            Size aNewSize = aNewRect.GetSize();

            if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() )
                aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) );
            if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() )
                aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) );

            if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() )
                aNewSize.Width() = aLogicSize.Width();
            if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() )
                aNewSize.Height() = aLogicSize.Height();

            aNewRect.SetSize( aNewSize );

            if ( aNewRect != aOldRect )     // veraendert nur, wenn mindestens 1 Pixel
                pObj->SetLogicRect( aNewRect );
        }
    }
}

/*************************************************************************
|*
|*
|*
\************************************************************************/

void __EXPORT SdClient::ViewChanged(USHORT nAspect)
{
    // Eventuell neues MetaFile holen
    SfxInPlaceClient::ViewChanged(nAspect);

    if (pViewShell->GetActiveWindow())
    {
        SdView* pView = pViewShell->GetView();

        if (pView)
        {
            // Der sichtbare Ausschnitt hat sich eventuell geaendert
            SvEmbeddedObject* pObj = GetEmbedObj();
            Rectangle aObjVisArea = OutputDevice::LogicToLogic(
                                    pObj->GetVisArea(), pObj->GetMapUnit(),
                                    MAP_100TH_MM );
            Size aVisSize = aObjVisArea.GetSize();

            SvClientData* pClientData = GetEnv();

            if (pClientData)
            {
                Fraction aFractX = pClientData->GetScaleWidth();
                Fraction aFractY = pClientData->GetScaleHeight();
                aFractX *= aVisSize.Width();
                aFractY *= aVisSize.Height();
                aVisSize = Size( (long) aFractX, (long) aFractY );

                Rectangle aLogicRect = pSdrOle2Obj->GetLogicRect();
                Rectangle aObjArea = aLogicRect;

                // Dokument-Groesse vom Server
                aObjArea.SetSize(aObjVisArea.GetSize());
                pClientData->SetObjArea(aObjArea);

                if (aLogicRect.GetSize() != aVisSize)
                {
                    aLogicRect.SetSize(aVisSize);
                    pSdrOle2Obj->SetLogicRect(aLogicRect);
                    pSdrOle2Obj->SendRepaintBroadcast();
                }
            }
        }
    }
}

/*************************************************************************
|*
|* InPlace-Objekt aktivieren / deaktivieren
|*
\************************************************************************/

void __EXPORT SdClient::UIActivate(BOOL bActivate)
{
    SfxInPlaceClient::UIActivate(bActivate);

    if (!bActivate)
    {
#ifdef STARIMAGE_AVAILABLE
        if (pSdrGrafObj && pViewShell->GetActiveWindow())
        {
            // Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht
            pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect());
            SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef();
            pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) );
            SdView* pView = pViewShell->GetView();
            SdrPageView* pPV = pView->GetPageViewPvNum(0);
            SdrPage* pPg = pPV->GetPage();
            delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() );
            pSdrGrafObj = NULL;
        }
#endif
    }
}

/*************************************************************************
|*
|* Daten fuer eine ggf. spaeter zu erzeugende View
|*
\************************************************************************/

void __EXPORT SdClient::MakeViewData()
{
    SfxInPlaceClient::MakeViewData();

    SvClientData* pCD = GetClientData();

    if (pCD)
    {
        SvEmbeddedObject* pObj = GetEmbedObj();
        Rectangle aObjVisArea = OutputDevice::LogicToLogic(
                                    pObj->GetVisArea(), pObj->GetMapUnit(),
                                    MAP_100TH_MM );
        Size aVisSize = aObjVisArea.GetSize();
        Fraction aFractX = pCD->GetScaleWidth();
        Fraction aFractY = pCD->GetScaleHeight();
        aFractX *= aVisSize.Width();
        aFractY *= aVisSize.Height();
        pCD->SetSizeScale(aFractX, aFractY);

        Rectangle aObjArea = pSdrOle2Obj->GetLogicRect();
        pCD->SetObjArea(aObjArea);
    }
}

/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/

void __EXPORT SdClient::MakeVisible()
{
    SfxInPlaceClient::MakeVisible();

    if (pViewShell->ISA(SdDrawViewShell))
    {
        ((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(),
                                                     *pViewShell->GetActiveWindow());
    }
}

<commit_msg>#91555#: rounding errors<commit_after>/*************************************************************************
 *
 *  $RCSfile: sdclient.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ka $ $Date: 2001-08-29 13:55:44 $
 *
 *  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 _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif

#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _CLIENT_HXX //autogen
#include <so3/client.hxx>
#endif
#ifndef _IPENV_HXX //autogen
#include <so3/ipenv.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif

#pragma hdrstop

#include "misc.hxx"

#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif

#include "strings.hrc"

#include "sdclient.hxx"
#include "viewshel.hxx"
#include "drviewsh.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) :
    SfxInPlaceClient(pSdViewShell, pWindow),
    pViewShell(pSdViewShell),
    pSdrOle2Obj(pObj),
    pSdrGrafObj(NULL),
    pOutlinerParaObj (NULL)
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

__EXPORT SdClient::~SdClient()
{
}

/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/

void __EXPORT SdClient::RequestObjAreaPixel(const Rectangle& rRect)
{
    Window* pWin = pViewShell->GetWindow();
    Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ),
                        pWin->PixelToLogic( rRect.GetSize() ) );

    SdView* pView = pViewShell->GetView();
    Rectangle aWorkArea( pView->GetWorkArea() );

    if (!aWorkArea.IsInside(aObjRect))
    {
        // Position korrigieren
        Point aPos = aObjRect.TopLeft();
        Size  aSize = aObjRect.GetSize();
        Point aWorkAreaTL = aWorkArea.TopLeft();
        Point aWorkAreaBR = aWorkArea.BottomRight();

        aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
        aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
        aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
        aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());

        aObjRect.SetPos(aPos);

        SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()->
                                              LogicToPixel(aObjRect) );
    }
    else
    {
        SfxInPlaceClient::RequestObjAreaPixel(rRect);
    }

    const SdrMarkList& rMarkList = pView->GetMarkList();

    if (rMarkList.GetMarkCount() == 1)
    {
        SdrMark* pMark = rMarkList.GetMark(0);
        SdrObject* pObj = pMark->GetObj();

        Rectangle aOldRect( pObj->GetLogicRect() );

        if ( aObjRect != aOldRect )
        {
            // Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied
            // (getrennt fuer Position und Groesse)
            Size aOnePixel = pWin->PixelToLogic( Size(1, 1) );
            Size aLogicSize = aObjRect.GetSize();
            Rectangle aNewRect = aOldRect;
            Size aNewSize = aNewRect.GetSize();

            if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() )
                aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) );
            if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() )
                aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) );

            if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() )
                aNewSize.Width() = aLogicSize.Width();
            if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() )
                aNewSize.Height() = aLogicSize.Height();

            aNewRect.SetSize( aNewSize );

            if ( aNewRect != aOldRect )     // veraendert nur, wenn mindestens 1 Pixel
                pObj->SetLogicRect( aNewRect );
        }
    }
}

/*************************************************************************
|*
|*
|*
\************************************************************************/

void __EXPORT SdClient::ViewChanged(USHORT nAspect)
{
    // Eventuell neues MetaFile holen
    SfxInPlaceClient::ViewChanged(nAspect);

    if (pViewShell->GetActiveWindow())
    {
        SdView* pView = pViewShell->GetView();

        if (pView)
        {
            // Der sichtbare Ausschnitt hat sich eventuell geaendert
            SvEmbeddedObject*   pObj = GetEmbedObj();
            const MapMode       aMap100( MAP_100TH_MM );
            Rectangle           aObjVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(),
                                                                         pObj->GetMapUnit(),
                                                                         aMap100 ) );
            Size                aVisSize( aObjVisArea.GetSize() );
            SvClientData*       pClientData = GetEnv();

            if( pClientData )
            {
                Fraction aFractX( pClientData->GetScaleWidth() );
                Fraction aFractY( pClientData->GetScaleHeight() );

                aVisSize = Size( (long) ( aFractX *= aVisSize.Width() ), (long) ( aFractY *= aVisSize.Height() ) );

                Rectangle aLogicRect( pSdrOle2Obj->GetLogicRect() );
                Rectangle aObjArea( aLogicRect );

                aObjArea.SetSize( aObjVisArea.GetSize() );
                pClientData->SetObjArea( aObjArea );

                const Size aVisSizePix( Application::GetDefaultDevice()->LogicToPixel( aVisSize, aMap100 ) );
                const Size aObjSizePix( Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) );

                if( aVisSizePix != aObjSizePix )
                {
                    aLogicRect.SetSize(aVisSize);
                    pSdrOle2Obj->SetLogicRect(aLogicRect);
                    pSdrOle2Obj->SendRepaintBroadcast();
                }
            }
        }
    }
}

/*************************************************************************
|*
|* InPlace-Objekt aktivieren / deaktivieren
|*
\************************************************************************/

void __EXPORT SdClient::UIActivate(BOOL bActivate)
{
    SfxInPlaceClient::UIActivate(bActivate);

    if (!bActivate)
    {
#ifdef STARIMAGE_AVAILABLE
        if (pSdrGrafObj && pViewShell->GetActiveWindow())
        {
            // Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht
            pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect());
            SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef();
            pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) );
            SdView* pView = pViewShell->GetView();
            SdrPageView* pPV = pView->GetPageViewPvNum(0);
            SdrPage* pPg = pPV->GetPage();
            delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() );
            pSdrGrafObj = NULL;
        }
#endif
    }
}

/*************************************************************************
|*
|* Daten fuer eine ggf. spaeter zu erzeugende View
|*
\************************************************************************/

void __EXPORT SdClient::MakeViewData()
{
    SfxInPlaceClient::MakeViewData();

    SvClientData* pCD = GetClientData();

    if (pCD)
    {
        SvEmbeddedObject* pObj = GetEmbedObj();
        Rectangle aObjVisArea = OutputDevice::LogicToLogic(
                                    pObj->GetVisArea(), pObj->GetMapUnit(),
                                    MAP_100TH_MM );
        Size aVisSize = aObjVisArea.GetSize();
        Fraction aFractX = pCD->GetScaleWidth();
        Fraction aFractY = pCD->GetScaleHeight();
        aFractX *= aVisSize.Width();
        aFractY *= aVisSize.Height();
        pCD->SetSizeScale(aFractX, aFractY);

        Rectangle aObjArea = pSdrOle2Obj->GetLogicRect();
        pCD->SetObjArea(aObjArea);
    }
}

/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/

void __EXPORT SdClient::MakeVisible()
{
    SfxInPlaceClient::MakeVisible();

    if (pViewShell->ISA(SdDrawViewShell))
    {
        ((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(),
                                                     *pViewShell->GetActiveWindow());
    }
}

<|endoftext|>


<commit_before>/*
   Copyright (C) 2014-2017 Alexandr Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

 */

#include "AesCtr.hpp"
#include "CTcpTransport.hpp"
#include "CRawStream.hpp"

#include <QHostAddress>
#include <QTimer>

#include <QLoggingCategory>

using namespace Telegram;

#ifndef Q_FALLTHROUGH
#define Q_FALLTHROUGH() (void)0
#endif

Q_LOGGING_CATEGORY(c_loggingTcpTransport, "telegram.transport.tcp", QtWarningMsg)

static const quint32 tcpTimeout = 15 * 1000;

CTcpTransport::CTcpTransport(QObject *parent) :
    CTelegramTransport(parent),
    m_socket(nullptr),
    m_timeoutTimer(new QTimer(this))
{
    m_timeoutTimer->setInterval(tcpTimeout);
    connect(m_timeoutTimer, &QTimer::timeout, this, &CTcpTransport::onTimeout);
}

CTcpTransport::~CTcpTransport()
{
    if (m_socket && m_socket->isWritable()) {
        m_socket->waitForBytesWritten(100);
        m_socket->disconnectFromHost();
    }
}

QString CTcpTransport::remoteAddress() const
{
    return m_socket ? m_socket->peerAddress().toString() : QString();
}

void CTcpTransport::connectToHost(const QString &ipAddress, quint32 port)
{
    qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << ipAddress << port;
    m_socket->connectToHost(ipAddress, port);
}

void CTcpTransport::disconnectFromHost()
{
    qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO;
    if (m_socket) {
        m_socket->disconnectFromHost();
    }
}

CTcpTransport::SessionType CTcpTransport::sessionType() const
{
    return m_sessionType;
}

void CTcpTransport::sendPackageImplementation(const QByteArray &payload)
{
    // quint32 length (included length itself + packet number + crc32 + payload (MUST be divisible by 4)
    // quint32 packet number
    // quint32 CRC32 (length, quint32 packet number, payload)
    // Payload

    // Abridged version:
    // quint8: 0xef
    // DataLength / 4 < 0x7f ?
    //      (quint8: Packet length / 4) :
    //      (quint8: 0x7f, quint24: Packet length / 4)
    // Payload

    if (payload.length() % 4) {
        qCCritical(c_loggingTcpTransport) << Q_FUNC_INFO
                                            << "Invalid outgoing package! "
                                               "The payload size is not divisible by four!";
    }

    QByteArray package;
    package.reserve(payload.size() + 4);
    const quint32 length = payload.length() / 4;
    if (length < 0x7f) {
        package.append(char(length));
    } else {
        package.append(char(0x7f));
        package.append(reinterpret_cast<const char *>(&length), 3);
    }
    package.append(payload);

    if (m_writeAesContext && m_writeAesContext->hasKey()) {
        package = m_writeAesContext->crypt(package);
    }

    m_socket->write(package);
}

void CTcpTransport::setSessionType(CTcpTransport::SessionType sessionType)
{
    m_sessionType = sessionType;
}

void CTcpTransport::setCryptoKeysSourceData(const QByteArray &source, SourceRevertion revertion)
{
    if (source.size() != (Crypto::AesCtrContext::KeySize + Crypto::AesCtrContext::IvecSize)) {
        qCWarning(c_loggingTcpTransport) << Q_FUNC_INFO << "Invalid input data (size mismatch)";
        return;
    }
    QByteArray reversed = source;
    std::reverse(reversed.begin(), reversed.end());
    const auto setSourceData = [](const QByteArray &source, Crypto::AesCtrContext *&context) {
        if (!context) {
            context = new Crypto::AesCtrContext();
        }
        context->setKey(source.left(Crypto::AesCtrContext::KeySize));
        context->setIVec(source.mid(Crypto::AesCtrContext::KeySize));
    };
    if (revertion == DirectIsReadReversedIsWrite) {
        setSourceData(source, m_readAesContext);
        setSourceData(reversed, m_writeAesContext);
    } else { // Server, DirectIsWriteReversedIsRead
        setSourceData(source, m_writeAesContext);
        setSourceData(reversed, m_readAesContext);
    }
    const char *className = metaObject()->className();
    if (strstr(className, "Server")) {
        m_readAesContext->setDescription(QByteArrayLiteral("server read"));
        m_writeAesContext->setDescription(QByteArrayLiteral("server write"));
    } else if (strstr(className, "Client")) {
        m_readAesContext->setDescription(QByteArrayLiteral("client read"));
        m_writeAesContext->setDescription(QByteArrayLiteral("client write"));
    }
}

void CTcpTransport::setState(QAbstractSocket::SocketState newState)
{
    qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << newState;
    switch (newState) {
    case QAbstractSocket::HostLookupState:
    case QAbstractSocket::ConnectingState:
        m_timeoutTimer->start();
        break;
    case QAbstractSocket::ConnectedState:
        m_expectedLength = 0;
        setSessionType(Unknown);
        Q_FALLTHROUGH();
    default:
        m_timeoutTimer->stop();
        break;
    }
    CTelegramTransport::setState(newState);
}

void CTcpTransport::onReadyRead()
{
    qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << m_socket->bytesAvailable();
    readEvent();
    if (m_sessionType == Unknown) {
        qCCritical(c_loggingTcpTransport) << "Unknown session type!";
        return;
    }
    while ((m_socket->bytesAvailable() > 0) || !m_readBuffer.isEmpty()) {
        if (m_socket->bytesAvailable() > 0) {
            QByteArray allData = m_socket->readAll();
            if (m_readAesContext) {
                allData = m_readAesContext->crypt(allData);
            }
            m_readBuffer.append(allData);
        }

        CRawStreamEx bufferStream(m_readBuffer);
        if (m_expectedLength == 0) {
            quint8 length_t1;
            bufferStream >> length_t1;
            if (length_t1 < char(0x7f)) {
                m_expectedLength = length_t1;
            } else if (length_t1 == char(0x7f)) {
                QByteArray nextThree = bufferStream.readBytes(3);
                char *lengthCharPointer = reinterpret_cast<char *>(&m_expectedLength);
                lengthCharPointer[0] = nextThree.at(0);
                lengthCharPointer[1] = nextThree.at(1);
                lengthCharPointer[2] = nextThree.at(2);
            } else {
                qCWarning(c_loggingTcpTransport) << "Invalid package size byte" << hex << showbase << length_t1;
                qCWarning(c_loggingTcpTransport) << "Buffer:" << m_readBuffer.toHex();
            }
            m_expectedLength *= 4;
        }
        if (bufferStream.bytesAvailable() < static_cast<qint64>(m_expectedLength)) {
            qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO << "Ready read, but only "
                                             << bufferStream.bytesAvailable() << "bytes available ("
                                             << m_expectedLength << "bytes expected)";
            return;
        }
        const QByteArray readPackage = bufferStream.readBytes(m_expectedLength);
        m_readBuffer = bufferStream.readAll();
        m_expectedLength = 0;
        qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO
                                         << "Received a package (" << readPackage.size() << " bytes)";
        emit packageReceived(readPackage);
    }
}

void CTcpTransport::onTimeout()
{
    qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO << m_socket->peerName() << m_socket->peerPort();
    emit timeout();
    m_socket->disconnectFromHost();
}

void CTcpTransport::onSocketErrorOccurred(QAbstractSocket::SocketError error)
{
    setError(error, m_socket->errorString());
}

void CTcpTransport::setSocket(QAbstractSocket *socket)
{
    if (m_socket) {
        qCCritical(c_loggingTcpTransport()) << Q_FUNC_INFO << "An attempt to set a socket twice";
    }
    m_socket = socket;
    connect(m_socket, &QAbstractSocket::stateChanged, this, &CTcpTransport::setState);
    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(onSocketErrorOccurred(QAbstractSocket::SocketError)));
    connect(m_socket, &QIODevice::readyRead, this, &CTcpTransport::onReadyRead);
}
<commit_msg>CTcpTransport: Hide warning on destruct<commit_after>/*
   Copyright (C) 2014-2017 Alexandr Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

 */

#include "AesCtr.hpp"
#include "CTcpTransport.hpp"
#include "CRawStream.hpp"

#include <QHostAddress>
#include <QTimer>

#include <QLoggingCategory>

using namespace Telegram;

#ifndef Q_FALLTHROUGH
#define Q_FALLTHROUGH() (void)0
#endif

Q_LOGGING_CATEGORY(c_loggingTcpTransport, "telegram.transport.tcp", QtWarningMsg)

static const quint32 tcpTimeout = 15 * 1000;

CTcpTransport::CTcpTransport(QObject *parent) :
    CTelegramTransport(parent),
    m_socket(nullptr),
    m_timeoutTimer(new QTimer(this))
{
    m_timeoutTimer->setInterval(tcpTimeout);
    connect(m_timeoutTimer, &QTimer::timeout, this, &CTcpTransport::onTimeout);
}

CTcpTransport::~CTcpTransport()
{
    if (m_socket && m_socket->isWritable() && m_socket->isOpen()
            && m_socket->state() != QAbstractSocket::UnconnectedState) {
        m_socket->waitForBytesWritten(100);
        m_socket->disconnectFromHost();
    }
}

QString CTcpTransport::remoteAddress() const
{
    return m_socket ? m_socket->peerAddress().toString() : QString();
}

void CTcpTransport::connectToHost(const QString &ipAddress, quint32 port)
{
    qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << ipAddress << port;
    m_socket->connectToHost(ipAddress, port);
}

void CTcpTransport::disconnectFromHost()
{
    qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO;
    if (m_socket) {
        m_socket->disconnectFromHost();
    }
}

CTcpTransport::SessionType CTcpTransport::sessionType() const
{
    return m_sessionType;
}

void CTcpTransport::sendPackageImplementation(const QByteArray &payload)
{
    // quint32 length (included length itself + packet number + crc32 + payload (MUST be divisible by 4)
    // quint32 packet number
    // quint32 CRC32 (length, quint32 packet number, payload)
    // Payload

    // Abridged version:
    // quint8: 0xef
    // DataLength / 4 < 0x7f ?
    //      (quint8: Packet length / 4) :
    //      (quint8: 0x7f, quint24: Packet length / 4)
    // Payload

    if (payload.length() % 4) {
        qCCritical(c_loggingTcpTransport) << Q_FUNC_INFO
                                            << "Invalid outgoing package! "
                                               "The payload size is not divisible by four!";
    }

    QByteArray package;
    package.reserve(payload.size() + 4);
    const quint32 length = payload.length() / 4;
    if (length < 0x7f) {
        package.append(char(length));
    } else {
        package.append(char(0x7f));
        package.append(reinterpret_cast<const char *>(&length), 3);
    }
    package.append(payload);

    if (m_writeAesContext && m_writeAesContext->hasKey()) {
        package = m_writeAesContext->crypt(package);
    }

    m_socket->write(package);
}

void CTcpTransport::setSessionType(CTcpTransport::SessionType sessionType)
{
    m_sessionType = sessionType;
}

void CTcpTransport::setCryptoKeysSourceData(const QByteArray &source, SourceRevertion revertion)
{
    if (source.size() != (Crypto::AesCtrContext::KeySize + Crypto::AesCtrContext::IvecSize)) {
        qCWarning(c_loggingTcpTransport) << Q_FUNC_INFO << "Invalid input data (size mismatch)";
        return;
    }
    QByteArray reversed = source;
    std::reverse(reversed.begin(), reversed.end());
    const auto setSourceData = [](const QByteArray &source, Crypto::AesCtrContext *&context) {
        if (!context) {
            context = new Crypto::AesCtrContext();
        }
        context->setKey(source.left(Crypto::AesCtrContext::KeySize));
        context->setIVec(source.mid(Crypto::AesCtrContext::KeySize));
    };
    if (revertion == DirectIsReadReversedIsWrite) {
        setSourceData(source, m_readAesContext);
        setSourceData(reversed, m_writeAesContext);
    } else { // Server, DirectIsWriteReversedIsRead
        setSourceData(source, m_writeAesContext);
        setSourceData(reversed, m_readAesContext);
    }
    const char *className = metaObject()->className();
    if (strstr(className, "Server")) {
        m_readAesContext->setDescription(QByteArrayLiteral("server read"));
        m_writeAesContext->setDescription(QByteArrayLiteral("server write"));
    } else if (strstr(className, "Client")) {
        m_readAesContext->setDescription(QByteArrayLiteral("client read"));
        m_writeAesContext->setDescription(QByteArrayLiteral("client write"));
    }
}

void CTcpTransport::setState(QAbstractSocket::SocketState newState)
{
    qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << newState;
    switch (newState) {
    case QAbstractSocket::HostLookupState:
    case QAbstractSocket::ConnectingState:
        m_timeoutTimer->start();
        break;
    case QAbstractSocket::ConnectedState:
        m_expectedLength = 0;
        setSessionType(Unknown);
        Q_FALLTHROUGH();
    default:
        m_timeoutTimer->stop();
        break;
    }
    CTelegramTransport::setState(newState);
}

void CTcpTransport::onReadyRead()
{
    qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << m_socket->bytesAvailable();
    readEvent();
    if (m_sessionType == Unknown) {
        qCCritical(c_loggingTcpTransport) << "Unknown session type!";
        return;
    }
    while ((m_socket->bytesAvailable() > 0) || !m_readBuffer.isEmpty()) {
        if (m_socket->bytesAvailable() > 0) {
            QByteArray allData = m_socket->readAll();
            if (m_readAesContext) {
                allData = m_readAesContext->crypt(allData);
            }
            m_readBuffer.append(allData);
        }

        CRawStreamEx bufferStream(m_readBuffer);
        if (m_expectedLength == 0) {
            quint8 length_t1;
            bufferStream >> length_t1;
            if (length_t1 < char(0x7f)) {
                m_expectedLength = length_t1;
            } else if (length_t1 == char(0x7f)) {
                QByteArray nextThree = bufferStream.readBytes(3);
                char *lengthCharPointer = reinterpret_cast<char *>(&m_expectedLength);
                lengthCharPointer[0] = nextThree.at(0);
                lengthCharPointer[1] = nextThree.at(1);
                lengthCharPointer[2] = nextThree.at(2);
            } else {
                qCWarning(c_loggingTcpTransport) << "Invalid package size byte" << hex << showbase << length_t1;
                qCWarning(c_loggingTcpTransport) << "Buffer:" << m_readBuffer.toHex();
            }
            m_expectedLength *= 4;
        }
        if (bufferStream.bytesAvailable() < static_cast<qint64>(m_expectedLength)) {
            qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO << "Ready read, but only "
                                             << bufferStream.bytesAvailable() << "bytes available ("
                                             << m_expectedLength << "bytes expected)";
            return;
        }
        const QByteArray readPackage = bufferStream.readBytes(m_expectedLength);
        m_readBuffer = bufferStream.readAll();
        m_expectedLength = 0;
        qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO
                                         << "Received a package (" << readPackage.size() << " bytes)";
        emit packageReceived(readPackage);
    }
}

void CTcpTransport::onTimeout()
{
    qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO << m_socket->peerName() << m_socket->peerPort();
    emit timeout();
    m_socket->disconnectFromHost();
}

void CTcpTransport::onSocketErrorOccurred(QAbstractSocket::SocketError error)
{
    setError(error, m_socket->errorString());
}

void CTcpTransport::setSocket(QAbstractSocket *socket)
{
    if (m_socket) {
        qCCritical(c_loggingTcpTransport()) << Q_FUNC_INFO << "An attempt to set a socket twice";
    }
    m_socket = socket;
    connect(m_socket, &QAbstractSocket::stateChanged, this, &CTcpTransport::setState);
    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(onSocketErrorOccurred(QAbstractSocket::SocketError)));
    connect(m_socket, &QIODevice::readyRead, this, &CTcpTransport::onReadyRead);
}
<|endoftext|>


<commit_before>#include "VBOMesh.h"

#include "AttributeSet.h"

#include "GLBlaat/GLBuffer.h"
#include "GLBlaat/GLProgram.h"

#include <vector>
#include <map>
#include <string>
#include <cassert>
#include <iostream>

// These might be missing with older GLEW headers
#ifndef GL_FLOAT_MAT2x3
#define GL_FLOAT_MAT2x3 0x8B65
#define GL_FLOAT_MAT2x4 0x8B66
#define GL_FLOAT_MAT3x2 0x8B67
#define GL_FLOAT_MAT3x4 0x8B68
#define GL_FLOAT_MAT4x2 0x8B69
#define GL_FLOAT_MAT4x3 0x8B6A
#endif

namespace NQVTK
{
	// ------------------------------------------------------------------------
	VBOMesh::VBOMesh()
	{
	}

	// ------------------------------------------------------------------------
	VBOMesh::~VBOMesh()
	{
		// Delete the attribute sets
		for (AttributeMap::iterator it = attributeSets.begin();
			it != attributeSets.end(); ++it)
		{
			delete it->second;
		}
	}

	// ------------------------------------------------------------------------
	void VBOMesh::BindAttributes() const
	{
		for (AttributeMap::const_iterator it = attributeSets.begin();
			it != attributeSets.end(); ++it)
		{
			it->second->Bind();
		}
	}

	// ------------------------------------------------------------------------
	void VBOMesh::UnbindAttributes() const
	{
		for (AttributeMap::const_iterator it = attributeSets.begin();
			it != attributeSets.end(); ++it)
		{
			it->second->Unbind();
		}
	}

	// ------------------------------------------------------------------------
	void VBOMesh::SetupAttributes(
		const std::vector<GLAttributeInfo> requiredAttribs)
	{
		// Clear all attributes
		for (AttributeMap::iterator it = this->customAttribs.begin();
			it != this->customAttribs.end(); ++it)
		{
			it->second->DontUse();
		}
		// Set attributes used by the program
		for (std::vector<GLAttributeInfo>::const_iterator it =
			requiredAttribs.begin(); it != requiredAttribs.end(); ++it)
		{
			if (it->index >= 0)
			{
				AttributeMap::iterator ait = customAttribs.find(it->name);
				if (ait != customAttribs.end())
				{
					ait->second->UseAsVertexAttrib(it->index);
				}
				else
				{
					// Set a default value for the attribute
					// It seems we can ignore the size, as array elements are listed
					// separately in requiredAttribs.
					// Matrices seem to be listed once; rows need to be set separately
					// TODO: type for mat4 is returned as vec4, how to distinguish?
					std::vector<float> zeroes;
					zeroes.resize(4 * 4);
					switch (it->type)
					{
						case GL_FLOAT:
							glVertexAttrib1fv(it->index, &zeroes[0]);
							break;

						case GL_FLOAT_MAT4x2:
							glVertexAttrib2fv(it->index + 3, &zeroes[0]);
						case GL_FLOAT_MAT3x2:
							glVertexAttrib2fv(it->index + 2, &zeroes[0]);
						case GL_FLOAT_MAT2:
							glVertexAttrib2fv(it->index + 1, &zeroes[0]);
						case GL_FLOAT_VEC2:
							glVertexAttrib2fv(it->index, &zeroes[0]);
							break;

						case GL_FLOAT_MAT4x3:
							glVertexAttrib3fv(it->index + 3, &zeroes[0]);
						case GL_FLOAT_MAT3:
							glVertexAttrib3fv(it->index + 2, &zeroes[0]);
						case GL_FLOAT_MAT2x3:
							glVertexAttrib3fv(it->index + 1, &zeroes[0]);
						case GL_FLOAT_VEC3:
							glVertexAttrib3fv(it->index, &zeroes[0]);
							break;

						case GL_FLOAT_MAT4:
							glVertexAttrib4fv(it->index + 3, &zeroes[0]);
						case GL_FLOAT_MAT3x4:
							glVertexAttrib4fv(it->index + 2, &zeroes[0]);
						case GL_FLOAT_MAT2x4:
							glVertexAttrib4fv(it->index + 1, &zeroes[0]);
						case GL_FLOAT_VEC4:
							glVertexAttrib4fv(it->index, &zeroes[0]);
							break;

						default:
							std::cerr << "Error! Attribute " << it->name <<
								" has unsupported type " << it->type << std::endl;
					}
				}
			}
		}
	}

	// ------------------------------------------------------------------------
	void VBOMesh::AddAttributeSet(const std::string &name,
		AttributeSet *attribSet, bool isCustom)
	{
		AttributeSet *oldSet = attributeSets[name];
		assert(!oldSet);
		if (oldSet) delete oldSet;
		attributeSets[name] = attribSet;

		if (isCustom)
		{
			customAttribs[name] = attribSet;
		}
	}

	// ------------------------------------------------------------------------
	AttributeSet *VBOMesh::GetAttributeSet(const std::string &name)
	{
		AttributeMap::iterator it = attributeSets.find(name);
		if (it != attributeSets.end())
		{
			return it->second;
		}
		return 0;
	}

	// ------------------------------------------------------------------------
	AttributeSet *VBOMesh::ReplaceAttributeSet(const std::string &name,
		AttributeSet *attribSet)
	{
		AttributeMap::iterator it = attributeSets.find(name);
		assert(it != attributeSets.end());
		AttributeSet *oldSet = it->second;
		it->second = attribSet;
		// Check the custom sets
		it = customAttribs.find(name);
		if (it != customAttribs.end())
		{
			it->second = attribSet;
		}
		return oldSet;
	}
}
<commit_msg>Removed unhelpful assert.<commit_after>#include "VBOMesh.h"

#include "AttributeSet.h"

#include "GLBlaat/GLBuffer.h"
#include "GLBlaat/GLProgram.h"

#include <vector>
#include <map>
#include <string>
#include <cassert>
#include <iostream>

// These might be missing with older GLEW headers
#ifndef GL_FLOAT_MAT2x3
#define GL_FLOAT_MAT2x3 0x8B65
#define GL_FLOAT_MAT2x4 0x8B66
#define GL_FLOAT_MAT3x2 0x8B67
#define GL_FLOAT_MAT3x4 0x8B68
#define GL_FLOAT_MAT4x2 0x8B69
#define GL_FLOAT_MAT4x3 0x8B6A
#endif

namespace NQVTK
{
	// ------------------------------------------------------------------------
	VBOMesh::VBOMesh()
	{
	}

	// ------------------------------------------------------------------------
	VBOMesh::~VBOMesh()
	{
		// Delete the attribute sets
		for (AttributeMap::iterator it = attributeSets.begin();
			it != attributeSets.end(); ++it)
		{
			delete it->second;
		}
	}

	// ------------------------------------------------------------------------
	void VBOMesh::BindAttributes() const
	{
		for (AttributeMap::const_iterator it = attributeSets.begin();
			it != attributeSets.end(); ++it)
		{
			it->second->Bind();
		}
	}

	// ------------------------------------------------------------------------
	void VBOMesh::UnbindAttributes() const
	{
		for (AttributeMap::const_iterator it = attributeSets.begin();
			it != attributeSets.end(); ++it)
		{
			it->second->Unbind();
		}
	}

	// ------------------------------------------------------------------------
	void VBOMesh::SetupAttributes(
		const std::vector<GLAttributeInfo> requiredAttribs)
	{
		// Clear all attributes
		for (AttributeMap::iterator it = this->customAttribs.begin();
			it != this->customAttribs.end(); ++it)
		{
			it->second->DontUse();
		}
		// Set attributes used by the program
		for (std::vector<GLAttributeInfo>::const_iterator it =
			requiredAttribs.begin(); it != requiredAttribs.end(); ++it)
		{
			if (it->index >= 0)
			{
				AttributeMap::iterator ait = customAttribs.find(it->name);
				if (ait != customAttribs.end())
				{
					ait->second->UseAsVertexAttrib(it->index);
				}
				else
				{
					// Set a default value for the attribute
					// It seems we can ignore the size, as array elements are listed
					// separately in requiredAttribs.
					// Matrices seem to be listed once; rows need to be set separately
					// TODO: type for mat4 is returned as vec4, how to distinguish?
					std::vector<float> zeroes;
					zeroes.resize(4 * 4);
					switch (it->type)
					{
						case GL_FLOAT:
							glVertexAttrib1fv(it->index, &zeroes[0]);
							break;

						case GL_FLOAT_MAT4x2:
							glVertexAttrib2fv(it->index + 3, &zeroes[0]);
						case GL_FLOAT_MAT3x2:
							glVertexAttrib2fv(it->index + 2, &zeroes[0]);
						case GL_FLOAT_MAT2:
							glVertexAttrib2fv(it->index + 1, &zeroes[0]);
						case GL_FLOAT_VEC2:
							glVertexAttrib2fv(it->index, &zeroes[0]);
							break;

						case GL_FLOAT_MAT4x3:
							glVertexAttrib3fv(it->index + 3, &zeroes[0]);
						case GL_FLOAT_MAT3:
							glVertexAttrib3fv(it->index + 2, &zeroes[0]);
						case GL_FLOAT_MAT2x3:
							glVertexAttrib3fv(it->index + 1, &zeroes[0]);
						case GL_FLOAT_VEC3:
							glVertexAttrib3fv(it->index, &zeroes[0]);
							break;

						case GL_FLOAT_MAT4:
							glVertexAttrib4fv(it->index + 3, &zeroes[0]);
						case GL_FLOAT_MAT3x4:
							glVertexAttrib4fv(it->index + 2, &zeroes[0]);
						case GL_FLOAT_MAT2x4:
							glVertexAttrib4fv(it->index + 1, &zeroes[0]);
						case GL_FLOAT_VEC4:
							glVertexAttrib4fv(it->index, &zeroes[0]);
							break;

						default:
							std::cerr << "Error! Attribute " << it->name <<
								" has unsupported type " << it->type << std::endl;
					}
				}
			}
		}
	}

	// ------------------------------------------------------------------------
	void VBOMesh::AddAttributeSet(const std::string &name,
		AttributeSet *attribSet, bool isCustom)
	{
		AttributeSet *oldSet = attributeSets[name];
		if (oldSet) delete oldSet;
		attributeSets[name] = attribSet;

		if (isCustom)
		{
			customAttribs[name] = attribSet;
		}
	}

	// ------------------------------------------------------------------------
	AttributeSet *VBOMesh::GetAttributeSet(const std::string &name)
	{
		AttributeMap::iterator it = attributeSets.find(name);
		if (it != attributeSets.end())
		{
			return it->second;
		}
		return 0;
	}

	// ------------------------------------------------------------------------
	AttributeSet *VBOMesh::ReplaceAttributeSet(const std::string &name,
		AttributeSet *attribSet)
	{
		AttributeMap::iterator it = attributeSets.find(name);
		assert(it != attributeSets.end());
		AttributeSet *oldSet = it->second;
		it->second = attribSet;
		// Check the custom sets
		it = customAttribs.find(name);
		if (it != customAttribs.end())
		{
			it->second = attribSet;
		}
		return oldSet;
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: textdlgs.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 22:15:15 $
 *
 *  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
 *
 ************************************************************************/

#undef SC_DLLIMPLEMENTATION

//      ohne precompiled Headers uebersetzen !!!

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------

#include <svx/svxids.hrc>
#define ITEMID_FONTLIST SID_ATTR_CHAR_FONTLIST
#define ITEMID_TABSTOP  0

//CHINA001 #include <svx/chardlg.hxx>
#include <svx/flstitem.hxx>
//CHINA001 #include <svx/paragrph.hxx>
//CHINA001 #include <svx/tabstpge.hxx>
#include <sfx2/objsh.hxx>
#include <svtools/cjkoptions.hxx>

#include "textdlgs.hxx"
#include "scresid.hxx"
#include "sc.hrc"
#include <svx/svxids.hrc> //add CHINA001
#include <svtools/intitem.hxx> //add CHINA001
#include <svx/flagsdef.hxx> //CHINA001
// -----------------------------------------------------------------------

ScCharDlg::ScCharDlg( Window* pParent, const SfxItemSet* pAttr,
                    const SfxObjectShell* pDocShell ) :
        SfxTabDialog        ( pParent, ScResId( RID_SCDLG_CHAR ), pAttr ),
        rOutAttrs           ( *pAttr ),
        rDocShell           ( *pDocShell )
{
    FreeResource();

    AddTabPage( RID_SVXPAGE_CHAR_NAME ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_NAME, SvxCharNamePage::Create, 0);
    AddTabPage( RID_SVXPAGE_CHAR_EFFECTS ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_EFFECTS, SvxCharEffectsPage::Create, 0);
    AddTabPage( RID_SVXPAGE_CHAR_POSITION ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_POSITION, SvxCharPositionPage::Create, 0);
}

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

void __EXPORT ScCharDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
    SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool())); //CHINA001
    switch( nId )
    {
        case RID_SVXPAGE_CHAR_NAME:
        {
            SvxFontListItem aItem(*( (const SvxFontListItem*)
                ( rDocShell.GetItem( SID_ATTR_CHAR_FONTLIST) ) ) );

            //CHINA001 ( (SvxCharNamePage&) rPage ).SetFontList( aItem );
            aSet.Put (SvxFontListItem( aItem.GetFontList(), SID_ATTR_CHAR_FONTLIST));
            rPage.PageCreated(aSet);
        }
        break;

        case RID_SVXPAGE_CHAR_EFFECTS:
            //CHINA001 ( (SvxCharEffectsPage&) rPage ).DisableControls(
                            //CHINA001 DISABLE_CASEMAP);
            aSet.Put (SfxUInt16Item(SID_DISABLE_CTL,DISABLE_CASEMAP)); //CHINA001
            rPage.PageCreated(aSet);
            break;

        default:
        break;
    }
}

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

ScParagraphDlg::ScParagraphDlg( Window* pParent, const SfxItemSet* pAttr ) :
        SfxTabDialog        ( pParent, ScResId( RID_SCDLG_PARAGRAPH ), pAttr ),
        rOutAttrs           ( *pAttr )
{
    FreeResource();

    SvtCJKOptions aCJKOptions;

    AddTabPage( RID_SVXPAGE_STD_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_STD_PARAGRAPH, SvxStdParagraphTabPage::Create, 0);
    AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH, SvxParaAlignTabPage::Create, 0);
    //AddTabPage( RID_SVXPAGE_EXT_PARAGRAPH, SvxExtParagraphTabPage::Create, 0);
    if ( aCJKOptions.IsAsianTypographyEnabled() )
        AddTabPage( RID_SVXPAGE_PARA_ASIAN);//CHINA001 AddTabPage( RID_SVXPAGE_PARA_ASIAN, SvxAsianTabPage::Create,0);
    else
        RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );
    AddTabPage( RID_SVXPAGE_TABULATOR );//CHINA001 AddTabPage( RID_SVXPAGE_TABULATOR, SvxTabulatorTabPage::Create, 0);
}

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

void __EXPORT ScParagraphDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
    switch( nId )
    {
        case RID_SVXPAGE_TABULATOR:
            {
            //CHINA001 ( (SvxTabulatorTabPage&) rPage ).
            //CHINA001      DisableControls( TABTYPE_ALL &~TABTYPE_LEFT |
            //CHINA001                       TABFILL_ALL &~TABFILL_NONE );
            SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001
            aSet.Put(SfxUInt16Item(SID_SVXTABULATORTABPAGE_CONTROLFLAGS,TABTYPE_ALL &~TABTYPE_LEFT |
                                TABFILL_ALL &~TABFILL_NONE ));
            rPage.PageCreated(aSet);//add CHINA001
            }
        break;
    }
}

<commit_msg>INTEGRATION: CWS pchfix01 (1.7.216); FILE MERGED 2006/07/12 10:02:46 kaib 1.7.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: textdlgs.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 14:11:42 $
 *
 *  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_sc.hxx"

#undef SC_DLLIMPLEMENTATION

//      ohne precompiled Headers uebersetzen !!!

// INCLUDE ---------------------------------------------------------------

#include <svx/svxids.hrc>
#define ITEMID_FONTLIST SID_ATTR_CHAR_FONTLIST
#define ITEMID_TABSTOP  0

//CHINA001 #include <svx/chardlg.hxx>
#include <svx/flstitem.hxx>
//CHINA001 #include <svx/paragrph.hxx>
//CHINA001 #include <svx/tabstpge.hxx>
#include <sfx2/objsh.hxx>
#include <svtools/cjkoptions.hxx>

#include "textdlgs.hxx"
#include "scresid.hxx"
#include "sc.hrc"
#include <svx/svxids.hrc> //add CHINA001
#include <svtools/intitem.hxx> //add CHINA001
#include <svx/flagsdef.hxx> //CHINA001
// -----------------------------------------------------------------------

ScCharDlg::ScCharDlg( Window* pParent, const SfxItemSet* pAttr,
                    const SfxObjectShell* pDocShell ) :
        SfxTabDialog        ( pParent, ScResId( RID_SCDLG_CHAR ), pAttr ),
        rOutAttrs           ( *pAttr ),
        rDocShell           ( *pDocShell )
{
    FreeResource();

    AddTabPage( RID_SVXPAGE_CHAR_NAME ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_NAME, SvxCharNamePage::Create, 0);
    AddTabPage( RID_SVXPAGE_CHAR_EFFECTS ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_EFFECTS, SvxCharEffectsPage::Create, 0);
    AddTabPage( RID_SVXPAGE_CHAR_POSITION ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_POSITION, SvxCharPositionPage::Create, 0);
}

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

void __EXPORT ScCharDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
    SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool())); //CHINA001
    switch( nId )
    {
        case RID_SVXPAGE_CHAR_NAME:
        {
            SvxFontListItem aItem(*( (const SvxFontListItem*)
                ( rDocShell.GetItem( SID_ATTR_CHAR_FONTLIST) ) ) );

            //CHINA001 ( (SvxCharNamePage&) rPage ).SetFontList( aItem );
            aSet.Put (SvxFontListItem( aItem.GetFontList(), SID_ATTR_CHAR_FONTLIST));
            rPage.PageCreated(aSet);
        }
        break;

        case RID_SVXPAGE_CHAR_EFFECTS:
            //CHINA001 ( (SvxCharEffectsPage&) rPage ).DisableControls(
                            //CHINA001 DISABLE_CASEMAP);
            aSet.Put (SfxUInt16Item(SID_DISABLE_CTL,DISABLE_CASEMAP)); //CHINA001
            rPage.PageCreated(aSet);
            break;

        default:
        break;
    }
}

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

ScParagraphDlg::ScParagraphDlg( Window* pParent, const SfxItemSet* pAttr ) :
        SfxTabDialog        ( pParent, ScResId( RID_SCDLG_PARAGRAPH ), pAttr ),
        rOutAttrs           ( *pAttr )
{
    FreeResource();

    SvtCJKOptions aCJKOptions;

    AddTabPage( RID_SVXPAGE_STD_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_STD_PARAGRAPH, SvxStdParagraphTabPage::Create, 0);
    AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH, SvxParaAlignTabPage::Create, 0);
    //AddTabPage( RID_SVXPAGE_EXT_PARAGRAPH, SvxExtParagraphTabPage::Create, 0);
    if ( aCJKOptions.IsAsianTypographyEnabled() )
        AddTabPage( RID_SVXPAGE_PARA_ASIAN);//CHINA001 AddTabPage( RID_SVXPAGE_PARA_ASIAN, SvxAsianTabPage::Create,0);
    else
        RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );
    AddTabPage( RID_SVXPAGE_TABULATOR );//CHINA001 AddTabPage( RID_SVXPAGE_TABULATOR, SvxTabulatorTabPage::Create, 0);
}

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

void __EXPORT ScParagraphDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
    switch( nId )
    {
        case RID_SVXPAGE_TABULATOR:
            {
            //CHINA001 ( (SvxTabulatorTabPage&) rPage ).
            //CHINA001      DisableControls( TABTYPE_ALL &~TABTYPE_LEFT |
            //CHINA001                       TABFILL_ALL &~TABFILL_NONE );
            SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001
            aSet.Put(SfxUInt16Item(SID_SVXTABULATORTABPAGE_CONTROLFLAGS,TABTYPE_ALL &~TABTYPE_LEFT |
                                TABFILL_ALL &~TABFILL_NONE ));
            rPage.PageCreated(aSet);//add CHINA001
            }
        break;
    }
}

<|endoftext|>


<commit_before>// This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

static const char* kMimeTypes[][2] = {
    {"image/jpeg", ".jpg"},
    {"image/jpeg", ".jpeg"},
    {"image/png", ".png"},
};

void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images)
{
	for (size_t i = 0; i < data->materials_count; ++i)
	{
		const cgltf_material& material = data->materials[i];

		if (material.has_pbr_metallic_roughness)
		{
			const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;

			if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image)
				images[pbr.base_color_texture.texture->image - data->images].srgb = true;
		}

		if (material.has_pbr_specular_glossiness)
		{
			const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;

			if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image)
				images[pbr.diffuse_texture.texture->image - data->images].srgb = true;
		}

		if (material.emissive_texture.texture && material.emissive_texture.texture->image)
			images[material.emissive_texture.texture->image - data->images].srgb = true;

		if (material.normal_texture.texture && material.normal_texture.texture->image)
			images[material.normal_texture.texture->image - data->images].normal_map = true;
	}
}

const char* inferMimeType(const char* path)
{
	const char* ext = strrchr(path, '.');
	if (!ext)
		return "";

	std::string extl = ext;
	for (size_t i = 0; i < extl.length(); ++i)
		extl[i] = char(tolower(extl[i]));

	for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
		if (extl == kMimeTypes[i][1])
			return kMimeTypes[i][0];

	return "";
}

static const char* mimeExtension(const char* mime_type)
{
	for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
		if (strcmp(kMimeTypes[i][0], mime_type) == 0)
			return kMimeTypes[i][1];

	return ".raw";
}

#ifdef __EMSCRIPTEN__
EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), {
	var cp = require('child_process');
	var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ];
	var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio });
	return ret.status == null ? 256 : ret.status;
});

EM_JS(const char*, readenv, (const char* name), {
	var val = process.env[UTF8ToString(name)];
	if (!val) return 0;
	var ret = _malloc(lengthBytesUTF8(val) + 1);
	stringToUTF8(val, ret, lengthBytesUTF8(val) + 1);
	return ret;
});
#else
static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr)
{
#ifdef _WIN32
	std::string ignore = "nul";
#else
	std::string ignore = "/dev/null";
#endif

	std::string cmd = cmd_;

	if (ignore_stdout)
		(cmd += " >") += ignore;
	if (ignore_stderr)
		(cmd += " 2>") += ignore;

	return system(cmd.c_str());
}

static const char* readenv(const char* name)
{
	return getenv(name);
}
#endif

bool checkBasis(bool verbose)
{
	const char* basisu_path = readenv("BASISU_PATH");
	std::string cmd = basisu_path ? basisu_path : "basisu";

	cmd += " -version";

	int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
	if (verbose)
		printf("%s => %d\n", cmd.c_str(), rc);

	return rc == 0;
}

bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
	(void)scale;

	TempFile temp_input(mimeExtension(mime_type));
	TempFile temp_output(".basis");

	if (!writeFile(temp_input.path.c_str(), data))
		return false;

	const char* basisu_path = readenv("BASISU_PATH");
	std::string cmd = basisu_path ? basisu_path : "basisu";

	char ql[16];
	sprintf(ql, "%d", (quality * 255 + 50) / 100);

	cmd += " -q ";
	cmd += ql;

	cmd += " -mipmap";

	if (normal_map)
	{
		cmd += " -normal_map";
		// for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness
	}
	else if (!srgb)
	{
		cmd += " -linear";
	}

	if (uastc)
	{
		cmd += " -uastc";
	}

	cmd += " -file ";
	cmd += temp_input.path;
	cmd += " -output_file ";
	cmd += temp_output.path;

	int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false);
	if (verbose)
		printf("%s => %d\n", cmd.c_str(), rc);

	return rc == 0 && readFile(temp_output.path.c_str(), result);
}

bool checkKtx(bool verbose)
{
	const char* toktx_path = readenv("TOKTX_PATH");
	std::string cmd = toktx_path ? toktx_path : "toktx";

	cmd += " --version";

	int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
	if (verbose)
		printf("%s => %d\n", cmd.c_str(), rc);

	return rc == 0;
}

bool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
	TempFile temp_input(mimeExtension(mime_type));
	TempFile temp_output(".ktx2");

	if (!writeFile(temp_input.path.c_str(), data))
		return false;

	const char* toktx_path = readenv("TOKTX_PATH");
	std::string cmd = toktx_path ? toktx_path : "toktx";

	cmd += " --2d";
	cmd += " --t2";

	cmd += " --automipmap";

	if (scale < 1)
	{
		char sl[128];
		sprintf(sl, "%g", scale);

		cmd += " --scale ";
		cmd += sl;
	}

	if (uastc)
	{
		cmd += " --uastc 2";
		cmd += " --zcmp 9";
	}
	else
	{
		char ql[16];
		sprintf(ql, "%d", (quality * 255 + 50) / 100);

		cmd += " --bcmp";
		cmd += " --qlevel ";
		cmd += ql;

		// for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness
		if (normal_map)
			cmd += " --normal_map";
	}

	if (srgb)
		cmd += " --srgb";
	else
		cmd += " --linear";

	cmd += " -- ";
	cmd += temp_output.path;
	cmd += " ";
	cmd += temp_input.path;

	int rc = execute(cmd.c_str(), /* ignore_stdout= */ false, /* ignore_stderr= */ false);
	if (verbose)
		printf("%s => %d\n", cmd.c_str(), rc);

	return rc == 0 && readFile(temp_output.path.c_str(), result);
}
<commit_msg>gltfpack: Add --nowarn to command line options<commit_after>// This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

static const char* kMimeTypes[][2] = {
    {"image/jpeg", ".jpg"},
    {"image/jpeg", ".jpeg"},
    {"image/png", ".png"},
};

void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images)
{
	for (size_t i = 0; i < data->materials_count; ++i)
	{
		const cgltf_material& material = data->materials[i];

		if (material.has_pbr_metallic_roughness)
		{
			const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;

			if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image)
				images[pbr.base_color_texture.texture->image - data->images].srgb = true;
		}

		if (material.has_pbr_specular_glossiness)
		{
			const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;

			if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image)
				images[pbr.diffuse_texture.texture->image - data->images].srgb = true;
		}

		if (material.emissive_texture.texture && material.emissive_texture.texture->image)
			images[material.emissive_texture.texture->image - data->images].srgb = true;

		if (material.normal_texture.texture && material.normal_texture.texture->image)
			images[material.normal_texture.texture->image - data->images].normal_map = true;
	}
}

const char* inferMimeType(const char* path)
{
	const char* ext = strrchr(path, '.');
	if (!ext)
		return "";

	std::string extl = ext;
	for (size_t i = 0; i < extl.length(); ++i)
		extl[i] = char(tolower(extl[i]));

	for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
		if (extl == kMimeTypes[i][1])
			return kMimeTypes[i][0];

	return "";
}

static const char* mimeExtension(const char* mime_type)
{
	for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
		if (strcmp(kMimeTypes[i][0], mime_type) == 0)
			return kMimeTypes[i][1];

	return ".raw";
}

#ifdef __EMSCRIPTEN__
EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), {
	var cp = require('child_process');
	var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ];
	var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio });
	return ret.status == null ? 256 : ret.status;
});

EM_JS(const char*, readenv, (const char* name), {
	var val = process.env[UTF8ToString(name)];
	if (!val) return 0;
	var ret = _malloc(lengthBytesUTF8(val) + 1);
	stringToUTF8(val, ret, lengthBytesUTF8(val) + 1);
	return ret;
});
#else
static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr)
{
#ifdef _WIN32
	std::string ignore = "nul";
#else
	std::string ignore = "/dev/null";
#endif

	std::string cmd = cmd_;

	if (ignore_stdout)
		(cmd += " >") += ignore;
	if (ignore_stderr)
		(cmd += " 2>") += ignore;

	return system(cmd.c_str());
}

static const char* readenv(const char* name)
{
	return getenv(name);
}
#endif

bool checkBasis(bool verbose)
{
	const char* basisu_path = readenv("BASISU_PATH");
	std::string cmd = basisu_path ? basisu_path : "basisu";

	cmd += " -version";

	int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
	if (verbose)
		printf("%s => %d\n", cmd.c_str(), rc);

	return rc == 0;
}

bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
	(void)scale;

	TempFile temp_input(mimeExtension(mime_type));
	TempFile temp_output(".basis");

	if (!writeFile(temp_input.path.c_str(), data))
		return false;

	const char* basisu_path = readenv("BASISU_PATH");
	std::string cmd = basisu_path ? basisu_path : "basisu";

	char ql[16];
	sprintf(ql, "%d", (quality * 255 + 50) / 100);

	cmd += " -q ";
	cmd += ql;

	cmd += " -mipmap";

	if (normal_map)
	{
		cmd += " -normal_map";
		// for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness
	}
	else if (!srgb)
	{
		cmd += " -linear";
	}

	if (uastc)
	{
		cmd += " -uastc";
	}

	cmd += " -file ";
	cmd += temp_input.path;
	cmd += " -output_file ";
	cmd += temp_output.path;

	int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false);
	if (verbose)
		printf("%s => %d\n", cmd.c_str(), rc);

	return rc == 0 && readFile(temp_output.path.c_str(), result);
}

bool checkKtx(bool verbose)
{
	const char* toktx_path = readenv("TOKTX_PATH");
	std::string cmd = toktx_path ? toktx_path : "toktx";

	cmd += " --version";

	int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
	if (verbose)
		printf("%s => %d\n", cmd.c_str(), rc);

	return rc == 0;
}

bool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
	TempFile temp_input(mimeExtension(mime_type));
	TempFile temp_output(".ktx2");

	if (!writeFile(temp_input.path.c_str(), data))
		return false;

	const char* toktx_path = readenv("TOKTX_PATH");
	std::string cmd = toktx_path ? toktx_path : "toktx";

	cmd += " --t2";
	cmd += " --2d";
	cmd += " --automipmap";
	cmd += " --nowarn";

	if (scale < 1)
	{
		char sl[128];
		sprintf(sl, "%g", scale);

		cmd += " --scale ";
		cmd += sl;
	}

	if (uastc)
	{
		cmd += " --uastc 2";
		cmd += " --zcmp 9";
	}
	else
	{
		char ql[16];
		sprintf(ql, "%d", (quality * 255 + 50) / 100);

		cmd += " --bcmp";
		cmd += " --qlevel ";
		cmd += ql;

		// for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness
		if (normal_map)
			cmd += " --normal_map";
	}

	if (srgb)
		cmd += " --srgb";
	else
		cmd += " --linear";

	cmd += " -- ";
	cmd += temp_output.path;
	cmd += " ";
	cmd += temp_input.path;

	int rc = execute(cmd.c_str(), /* ignore_stdout= */ false, /* ignore_stderr= */ false);
	if (verbose)
		printf("%s => %d\n", cmd.c_str(), rc);

	return rc == 0 && readFile(temp_output.path.c_str(), result);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ViewShellBase.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:43:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_VIEW_SHELL_BASE_HXX
#define SD_VIEW_SHELL_BASE_HXX

#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif

#ifndef SD_GLOB_HXX
#include "glob.hxx"
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
#include <memory>
#include <boost/shared_ptr.hpp>

class SdDrawDocument;
class SfxRequest;

namespace sd { namespace tools {
class EventMultiplexer;
} }

namespace sd {

class DrawController;
class DrawDocShell;
class FormShellManager;
class PrintManager;
class ToolBarManager;
class UpdateLockManager;
class ViewShell;
class ViewShellManager;

/** SfxViewShell descendant that the stacked Draw/Impress shells are
    based on.

The "base" part of the name does not mean that this is a base
    class of some class hierarchy.  It rather is the base of the
    stacked shells.

This class starts as a new and relatively small class.  Over
    time as much code as possible should be moved from the stacked
    shells to this class.

*/
class ViewShellBase
    : public SfxViewShell
{
public:
    TYPEINFO();
    SFX_DECL_VIEWFACTORY(ViewShellBase);
    SFX_DECL_INTERFACE(SD_IF_SDVIEWSHELLBASE)

    /** This constructor is used by the view factory of the SFX macros.
        Note that LateInit() has to be called after the constructor
        terminates and before doing anything else.
    */
    ViewShellBase (
        SfxViewFrame *pFrame,
        SfxViewShell* pOldShell);

    virtual ~ViewShellBase (void);

    /** This method is part of the object construction.  It HAS to be called
        after the constructor has created a new object.
    */
    virtual void LateInit (const ::rtl::OUString& rsDefaultView);

    ViewShellManager& GetViewShellManager (void) const;

    /** Return the main view shell stacked on the called ViewShellBase
        object.  This is usually the view shell displayed in the center
        pane.
    */
    ::boost::shared_ptr<ViewShell> GetMainViewShell (void) const;

    /** When given a view frame this static method returns the
        corresponding sd::ViewShellBase object.
        @return
            When the SfxViewShell of the given frame is not a
            ViewShellBase object then NULL is returned.
    */
    static ViewShellBase* GetViewShellBase (SfxViewFrame* pFrame);

    DrawDocShell* GetDocShell (void) const;
    SdDrawDocument* GetDocument (void) const;

    /** Callback function for retrieving item values related to menu entries.
    */
    void GetMenuState (SfxItemSet& rSet);

    /** Callback function for general slot calls.  At the moment these are
        slots for switching the pane docking windows on and off.
    */
    virtual void Execute (SfxRequest& rRequest);

    /** Callback function for retrieving item values related to certain
        slots.  This is the companion of Execute() and handles the slots
        concerned with showing the pane docking windows.
    */
    virtual void GetState (SfxItemSet& rSet);

    SvBorder GetBorder (bool bOuterResize);
    virtual void InnerResizePixel (const Point& rOrigin, const Size& rSize);
    virtual void OuterResizePixel (const Point& rOrigin, const Size& rSize);

    /** This call is forwarded to the main sub-shell.
    */
    virtual ErrCode DoVerb (long nVerb);

    /// Forwarded to the print manager.
    virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE);

    /// Forwarded to the print manager.
    virtual USHORT SetPrinter (
        SfxPrinter* pNewPrinter,
        USHORT nDiffFlags = SFX_PRINTER_ALL);

    /// Forwarded to the print manager.
    virtual PrintDialog* CreatePrintDialog (::Window *pParent);

    /// Forwarded to the print manager.
    virtual SfxTabPage* CreatePrintOptionsPage (
        ::Window *pParent,
        const SfxItemSet &rOptions);

    /// Forwarded to the print manager.
    virtual USHORT Print (SfxProgress& rProgress, BOOL bIsAPI, PrintDialog* pDialog);

    /// Forwarded to the print manager.
    virtual ErrCode DoPrint (
        SfxPrinter *pPrinter,
        PrintDialog *pPrintDialog,
        BOOL bSilent, BOOL bIsAPI );

    /// Forwarded to the print manager.
    USHORT SetPrinterOptDlg (
        SfxPrinter* pNewPrinter,
        USHORT nDiffFlags = SFX_PRINTER_ALL,
        BOOL _bShowDialog = TRUE);

    virtual void PreparePrint (PrintDialog* pPrintDialog);

    /// Forward methods to main sub shell.
    virtual void WriteUserDataSequence (
        ::com::sun::star::uno::Sequence <
        ::com::sun::star::beans::PropertyValue >&,
        sal_Bool bBrowse = sal_False);

    /** Pass the given properties to the main view shell.  After that we
        ensure that the right view shell type is displayed in the center
        pane.
    */
    virtual void ReadUserDataSequence (
        const ::com::sun::star::uno::Sequence <
        ::com::sun::star::beans::PropertyValue >&,
        sal_Bool bBrowse = sal_False);

    virtual void UIActivating( SfxInPlaceClient* );
    virtual void UIDeactivated( SfxInPlaceClient* );
    virtual void Activate (BOOL IsMDIActivate);
    virtual void Deactivate (BOOL IsMDIActivate);
    virtual void SetZoomFactor (
        const Fraction &rZoomX,
        const Fraction &rZoomY);
    virtual USHORT PrepareClose (BOOL bUI = TRUE, BOOL bForBrowsing = FALSE);
    virtual void WriteUserData (String&, BOOL bBrowse = FALSE);
    virtual void ReadUserData (const String&, BOOL bBrowse = FALSE);
    virtual SdrView* GetDrawView (void) const;
    virtual void AdjustPosSizePixel (const Point &rOfs, const Size &rSize);

    /** When <TRUE/> is given, then the mouse shape is set to hour glass (or
        whatever the busy shape looks like on the system.)
    */
    void SetBusyState (bool bBusy);

    /** Call this method when the controls of this view shell or the
        embedded sub shell need to be rearranged.  This is necessary
        e.g. when the border has been modified (UpdateBorder() calls this
        method).

        This method is like ResizePixel() with no arguments.
    */
    void Rearrange (void);

    /** Update the border that is set with SfxViewShell::SetBorderPixel().
        This is done by adding the border used by the ViewShellBase itself
        with the border used by the main view shell.

        @param bForce   if true the borders are also updated if old border
                        and new border are same.
    */
    void UpdateBorder ( bool bForce = false );

    /** With this method the UI controls can be turned on or off.  It is
        used by the FuSlideShow to hide the UI controls while showing a
        non-full-screen or in-window presentation in the center pane.
    */
    void ShowUIControls (bool bVisible);

    /** this method starts the presentation by
        executing the slot SID_PRESENTATION asynchronous */
    void StartPresentation();

    /** this methods ends the presentation by
        executing the slot SID_PRESENTATION_END asynchronous */
    void StopPresentation();

    /** Return an event multiplexer.  It is a single class that forwards
        events from various sources.  This method must not be called before
        LateInit() has terminated.
    */
    tools::EventMultiplexer& GetEventMultiplexer (void);

    /** returns the complete area of the current view relative to the frame
        window
    */
    const Rectangle& getClientRectangle() const;

    ::boost::shared_ptr<UpdateLockManager> GetUpdateLockManager (void) const;

    ::boost::shared_ptr<ToolBarManager> GetToolBarManager (void) const;

    FormShellManager& GetFormShellManager (void) const;

    DrawController& GetDrawController (void) const;

    void SetViewTabBar (const ::rtl::Reference<ViewTabBar>& rViewTabBar);

    /** Return the window that is used by the main view shell to display its
        view and other UI elements, like scroll bars and rulers.  Ownership
        of that window remains with the called ViewShellBase object.
    */
    ::Window* GetViewWindow (void);

protected:
    osl::Mutex maMutex;

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC,
        const TypeId& rBCType,
        const SfxHint& rHint,
        const TypeId& rHintType);

    virtual void InitializeFramework (void);

private:
    class Implementation;
    ::std::auto_ptr<Implementation> mpImpl;
    ::std::auto_ptr<ViewShellManager> mpViewShellManager;
    DrawDocShell* mpDocShell;
    SdDrawDocument* mpDocument;

    /// The print manager is responsible for printing documents.
    ::std::auto_ptr<PrintManager> mpPrintManager;

    ::std::auto_ptr<FormShellManager> mpFormShellManager;

    ::std::auto_ptr<tools::EventMultiplexer> mpEventMultiplexer;

    ::boost::shared_ptr<UpdateLockManager> mpUpdateLockManager;

    /** Determine from the properties of the document shell the initial type
        of the view shell in the center pane.  We use this method to avoid
        starting with the wrong type.  When ReadUserDataSequence() is called
        we check that the right type is active and change again if that is
        not the case because something went wrong.
    */
    ::rtl::OUString GetInitialViewShellType (void);
};

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS pathfinder01 (1.18.62); FILE MERGED 2007/07/03 13:03:16 cl 1.18.62.1: #i41800# implemented support for path animation editing for custom animations<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ViewShellBase.hxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-06 13:13:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_VIEW_SHELL_BASE_HXX
#define SD_VIEW_SHELL_BASE_HXX

#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif

#ifndef SD_GLOB_HXX
#include "glob.hxx"
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
#include <memory>
#include <boost/shared_ptr.hpp>

#include <set>

class SdDrawDocument;
class SfxRequest;

namespace sd { namespace tools {
class EventMultiplexer;
} }

namespace sd {

class DrawController;
class DrawDocShell;
class FormShellManager;
class PrintManager;
class ToolBarManager;
class UpdateLockManager;
class ViewShell;
class ViewShellManager;
class CustomHandleManager;

/** SfxViewShell descendant that the stacked Draw/Impress shells are
    based on.

The "base" part of the name does not mean that this is a base
    class of some class hierarchy.  It rather is the base of the
    stacked shells.

This class starts as a new and relatively small class.  Over
    time as much code as possible should be moved from the stacked
    shells to this class.

*/
class ViewShellBase
    : public SfxViewShell
{
public:
    TYPEINFO();
    SFX_DECL_VIEWFACTORY(ViewShellBase);
    SFX_DECL_INTERFACE(SD_IF_SDVIEWSHELLBASE)

    /** This constructor is used by the view factory of the SFX macros.
        Note that LateInit() has to be called after the constructor
        terminates and before doing anything else.
    */
    ViewShellBase (
        SfxViewFrame *pFrame,
        SfxViewShell* pOldShell);

    virtual ~ViewShellBase (void);

    /** This method is part of the object construction.  It HAS to be called
        after the constructor has created a new object.
    */
    virtual void LateInit (const ::rtl::OUString& rsDefaultView);

    ViewShellManager& GetViewShellManager (void) const;

    /** Return the main view shell stacked on the called ViewShellBase
        object.  This is usually the view shell displayed in the center
        pane.
    */
    ::boost::shared_ptr<ViewShell> GetMainViewShell (void) const;

    /** When given a view frame this static method returns the
        corresponding sd::ViewShellBase object.
        @return
            When the SfxViewShell of the given frame is not a
            ViewShellBase object then NULL is returned.
    */
    static ViewShellBase* GetViewShellBase (SfxViewFrame* pFrame);

    DrawDocShell* GetDocShell (void) const;
    SdDrawDocument* GetDocument (void) const;

    /** Callback function for retrieving item values related to menu entries.
    */
    void GetMenuState (SfxItemSet& rSet);

    /** Callback function for general slot calls.  At the moment these are
        slots for switching the pane docking windows on and off.
    */
    virtual void Execute (SfxRequest& rRequest);

    /** Callback function for retrieving item values related to certain
        slots.  This is the companion of Execute() and handles the slots
        concerned with showing the pane docking windows.
    */
    virtual void GetState (SfxItemSet& rSet);

    SvBorder GetBorder (bool bOuterResize);
    virtual void InnerResizePixel (const Point& rOrigin, const Size& rSize);
    virtual void OuterResizePixel (const Point& rOrigin, const Size& rSize);

    /** This call is forwarded to the main sub-shell.
    */
    virtual ErrCode DoVerb (long nVerb);

    /// Forwarded to the print manager.
    virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE);

    /// Forwarded to the print manager.
    virtual USHORT SetPrinter (
        SfxPrinter* pNewPrinter,
        USHORT nDiffFlags = SFX_PRINTER_ALL);

    /// Forwarded to the print manager.
    virtual PrintDialog* CreatePrintDialog (::Window *pParent);

    /// Forwarded to the print manager.
    virtual SfxTabPage* CreatePrintOptionsPage (
        ::Window *pParent,
        const SfxItemSet &rOptions);

    /// Forwarded to the print manager.
    virtual USHORT Print (SfxProgress& rProgress, BOOL bIsAPI, PrintDialog* pDialog);

    /// Forwarded to the print manager.
    virtual ErrCode DoPrint (
        SfxPrinter *pPrinter,
        PrintDialog *pPrintDialog,
        BOOL bSilent, BOOL bIsAPI );

    /// Forwarded to the print manager.
    USHORT SetPrinterOptDlg (
        SfxPrinter* pNewPrinter,
        USHORT nDiffFlags = SFX_PRINTER_ALL,
        BOOL _bShowDialog = TRUE);

    virtual void PreparePrint (PrintDialog* pPrintDialog);

    /// Forward methods to main sub shell.
    virtual void WriteUserDataSequence (
        ::com::sun::star::uno::Sequence <
        ::com::sun::star::beans::PropertyValue >&,
        sal_Bool bBrowse = sal_False);

    /** Pass the given properties to the main view shell.  After that we
        ensure that the right view shell type is displayed in the center
        pane.
    */
    virtual void ReadUserDataSequence (
        const ::com::sun::star::uno::Sequence <
        ::com::sun::star::beans::PropertyValue >&,
        sal_Bool bBrowse = sal_False);

    virtual void UIActivating( SfxInPlaceClient* );
    virtual void UIDeactivated( SfxInPlaceClient* );
    virtual void Activate (BOOL IsMDIActivate);
    virtual void Deactivate (BOOL IsMDIActivate);
    virtual void SetZoomFactor (
        const Fraction &rZoomX,
        const Fraction &rZoomY);
    virtual USHORT PrepareClose (BOOL bUI = TRUE, BOOL bForBrowsing = FALSE);
    virtual void WriteUserData (String&, BOOL bBrowse = FALSE);
    virtual void ReadUserData (const String&, BOOL bBrowse = FALSE);
    virtual SdrView* GetDrawView (void) const;
    virtual void AdjustPosSizePixel (const Point &rOfs, const Size &rSize);

    /** When <TRUE/> is given, then the mouse shape is set to hour glass (or
        whatever the busy shape looks like on the system.)
    */
    void SetBusyState (bool bBusy);

    /** Call this method when the controls of this view shell or the
        embedded sub shell need to be rearranged.  This is necessary
        e.g. when the border has been modified (UpdateBorder() calls this
        method).

        This method is like ResizePixel() with no arguments.
    */
    void Rearrange (void);

    /** Update the border that is set with SfxViewShell::SetBorderPixel().
        This is done by adding the border used by the ViewShellBase itself
        with the border used by the main view shell.

        @param bForce   if true the borders are also updated if old border
                        and new border are same.
    */
    void UpdateBorder ( bool bForce = false );

    /** With this method the UI controls can be turned on or off.  It is
        used by the FuSlideShow to hide the UI controls while showing a
        non-full-screen or in-window presentation in the center pane.
    */
    void ShowUIControls (bool bVisible);

    /** this method starts the presentation by
        executing the slot SID_PRESENTATION asynchronous */
    void StartPresentation();

    /** this methods ends the presentation by
        executing the slot SID_PRESENTATION_END asynchronous */
    void StopPresentation();

    /** Return an event multiplexer.  It is a single class that forwards
        events from various sources.  This method must not be called before
        LateInit() has terminated.
    */
    tools::EventMultiplexer& GetEventMultiplexer (void);

    /** returns the complete area of the current view relative to the frame
        window
    */
    const Rectangle& getClientRectangle() const;

    ::boost::shared_ptr<UpdateLockManager> GetUpdateLockManager (void) const;

    ::boost::shared_ptr<ToolBarManager> GetToolBarManager (void) const;

    FormShellManager& GetFormShellManager (void) const;

    DrawController& GetDrawController (void) const;

    void SetViewTabBar (const ::rtl::Reference<ViewTabBar>& rViewTabBar);

    /** Return the window that is used by the main view shell to display its
        view and other UI elements, like scroll bars and rulers.  Ownership
        of that window remains with the called ViewShellBase object.
    */
    ::Window* GetViewWindow (void);

    CustomHandleManager& getCustomHandleManager() const;

protected:
    osl::Mutex maMutex;

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC,
        const TypeId& rBCType,
        const SfxHint& rHint,
        const TypeId& rHintType);

    virtual void InitializeFramework (void);

private:
    class Implementation;
    ::std::auto_ptr<Implementation> mpImpl;
    ::std::auto_ptr<ViewShellManager> mpViewShellManager;
    DrawDocShell* mpDocShell;
    SdDrawDocument* mpDocument;

    /// The print manager is responsible for printing documents.
    ::std::auto_ptr<PrintManager> mpPrintManager;

    ::std::auto_ptr<FormShellManager> mpFormShellManager;

    ::std::auto_ptr<tools::EventMultiplexer> mpEventMultiplexer;

    ::boost::shared_ptr<UpdateLockManager> mpUpdateLockManager;

    ::std::auto_ptr<CustomHandleManager> mpCustomHandleManager;

    /** Determine from the properties of the document shell the initial type
        of the view shell in the center pane.  We use this method to avoid
        starting with the wrong type.  When ReadUserDataSequence() is called
        we check that the right type is active and change again if that is
        not the case because something went wrong.
    */
    ::rtl::OUString GetInitialViewShellType (void);
};

class ICustomhandleSupplier
{
public:
    virtual void addCustomHandler( SdrView& rSourceView, ViewShell::ShellType eShellType, SdrHdlList& rHandlerList ) = 0;
};

class CustomHandleManager : public ICustomhandleSupplier
{
public:
    CustomHandleManager( ViewShellBase& rViewShellBase  );
    virtual ~CustomHandleManager();

    void registerSupplier( ICustomhandleSupplier* pSupplier );
    void unRegisterSupplier( ICustomhandleSupplier* pSupplier );

    virtual void addCustomHandler( SdrView& rSourceView, ViewShell::ShellType eShellType, SdrHdlList& rHandlerList );

private:
    ViewShellBase& mrViewShellBase;
    std::set< ICustomhandleSupplier* > maSupplier;
};

} // end of namespace sd

#endif
<|endoftext|>