<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: slideshow.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 16:09:25 $
 *
 *  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_SLIDESHOW_HXX
#define _SD_SLIDESHOW_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

#include <memory>

namespace com { namespace sun { namespace star {

    namespace drawing {
        class XDrawPage;
    }
    namespace animations {
        class XAnimationNode;
    }
} } }

class SdDrawDocument;
class KeyEvent;
class HelpEvent;
class MouseEvent;
class Size;
class CommandEvent;
class Rectangle;
class Window;
class SfxRequest;

// TODO: Remove
#define PAGE_NO_END         65535
#define PAGE_NO_SOFTEND     (PAGE_NO_END - 1)
#define PAGE_NO_PAUSE       (PAGE_NO_SOFTEND - 1)
#define PAGE_NO_FIRSTDEF    PAGE_NO_PAUSE // immer mit anpassen

/* Definition of Slideshow class */

namespace sd
{

class SlideshowImpl;
class ShowWindow;
class Window;
class View;
class ViewShell;
struct PresentationSettings;
class EffectSequenceHelper;

enum AnimationMode
{
    ANIMATIONMODE_SHOW,
    ANIMATIONMODE_VIEW,
    ANIMATIONMODE_PREVIEW
};

class Slideshow
{
public:
    Slideshow( ViewShell* pViewSh, ::sd::View* pView, SdDrawDocument* pDoc,
        ::Window* pParentWindow );
    ~Slideshow();

    // actions
    bool startShow( PresentationSettings* pPresSettings = 0 );  // a.k.a. FuSlideShow::StartShow()
    bool startPreview(
        const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& xDrawPage,
        const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xAnimationNode,
        ::Window* pParent = 0 );

    void stopShow();                                        // a.k.a. FuSlideShow::Terminate()
    void jumpToPageNumber( sal_Int32 nPage );               // a.k.a. FuSlideShow::JumpToPage()
    void jumpToPageIndex( sal_Int32 nIndex );
    void jumpToBookmark( const String& sBookmark );         // a.k.a. FuSlideShow::JumpToBookmark()
    void dispose();                                         // a.k.a. FuSlideShow::Destroy()

    /** sets or clears the pause state of the running slideshow.
        !!!! This should only be called by the SdShowWindow !!!!*/
    bool pause( bool bPause );

    // settings
    void setRehearseTimings( bool bRehearseTimings );
    bool isFullScreen();                                // a.k.a. FuSlideShow::IsFullScreen()
    bool isTerminated();                                // a.k.a. FuSlideShow::IsTerminated();
    bool isAlwaysOnTop();                               // a.k.a. FuSlideShow::IsAlwaysOnTop();
    ShowWindow* getShowWindow();                        // a.k.a. FuSlideShow::GetShowWindow()
    int getAnimationMode();                             // a.k.a. FuSlideShow::GetAnimationMode()
    sal_Int32 getCurrentPageNumber();                   // a.k.a. FuSlideShow::GetCurrentPage()
    sal_Int32 getCurrentPageIndex();
    sal_Int32 getFirstPageNumber();
    sal_Int32 getLastPageNumber();
    bool isEndless();
    bool isDrawingPossible();

    // methods
    void setWindow( sd::Window* pWindow );              // a.k.a. FuSlideShow::SetWindow();

    // events
    void paint( const Rectangle& rRect );
    void resize( const Size &rSize );                   // a.k.a. FuSlideShow::Resize()
    void activate();                                    // a.k.a. FuSlideShow::Activate();
    void deactivate();                                  // a.k.a. FuSlideShow::Deactivate();

    bool requestHelp(const HelpEvent& rHEvt);           // a.k.a. FuSlideShow::requestHelp();
    bool keyInput(const KeyEvent& rKEvt);               // a.k.a. FuSlideShow::KeyInput();
    void mouseButtonDown(const MouseEvent& rMEvt);      // a.k.a. FuSlideShow::MouseButtonDown();
    void mouseMove(const MouseEvent& rMEvt);            // a.k.a. FuSlideShow::MouseMove();
    void mouseButtonUp(const MouseEvent& rMEvt);        // a.k.a. FuSlideShow::MouseButtonUp();

    void command(const CommandEvent& rCEvt);            // a.k.a. FuSlideShow::Command();

    void receiveRequest(SfxRequest& rReq);

private:
    // default: disabled copy/assignment
    Slideshow(const Slideshow&);
    Slideshow& operator=( const Slideshow& );

    sd::SlideshowImpl* mpImpl;
};

}

#endif /* _SD_SLIDESHOW_HXX */
<commit_msg>INTEGRATION: CWS presenterview (1.4.388); FILE MERGED 2008/01/11 14:19:04 cl 1.4.388.4: #i18486# fullscreen slideshow fix 2008/01/09 18:28:24 cl 1.4.388.3: #i15900# slideshow api consolidation 2007/04/19 15:52:53 af 1.4.388.2: RESYNC: (1.4-1.5); FILE MERGED 2007/02/27 09:08:27 cl 1.4.388.1: #i71351# added api draft for a slideshow controller<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: slideshow.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 14:01:18 $
 *
 *  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_SLIDESHOW_HXX
#define _SD_SLIDESHOW_HXX

#include <com/sun/star/presentation/XPresentation2.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>

#include <rtl/ref.hxx>

#include <tools/link.hxx>

#include <cppuhelper/compbase2.hxx>
#include <cppuhelper/basemutex.hxx>

#include <svx/unoipset.hxx>

#include <memory>
#include <boost/shared_ptr.hpp>

namespace com { namespace sun { namespace star {

    namespace drawing {
        class XDrawPage;
    }
    namespace animations {
        class XAnimationNode;
    }
} } }

class SdDrawDocument;
class KeyEvent;
class HelpEvent;
class MouseEvent;
class Size;
class CommandEvent;
class Rectangle;
class Window;
class SfxRequest;

// TODO: Remove
#define PAGE_NO_END         65535
#define PAGE_NO_SOFTEND     (PAGE_NO_END - 1)
#define PAGE_NO_PAUSE       (PAGE_NO_SOFTEND - 1)
#define PAGE_NO_FIRSTDEF    PAGE_NO_PAUSE // immer mit anpassen

/* Definition of SlideShow class */

namespace sd
{

class SlideshowImpl;
class ShowWindow;
class Window;
class View;
class ViewShell;
struct PresentationSettings;
class EffectSequenceHelper;
class ViewShellBase;
struct PresentationSettingsEx;
class FrameView;

enum AnimationMode
{
    ANIMATIONMODE_SHOW,
    ANIMATIONMODE_VIEW,
    ANIMATIONMODE_PREVIEW
};

typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::presentation::XPresentation2, ::com::sun::star::lang::XServiceInfo > SlideshowBase;

class SlideShow : private ::cppu::BaseMutex, public SlideshowBase
{
public:
    /// used by the model to create a slideshow for it
    static rtl::Reference< SlideShow > Create( SdDrawDocument* pDoc );

    // static helper api
    static rtl::Reference< SlideShow > GetSlideShow( SdDrawDocument* pDocument );
    static rtl::Reference< SlideShow > GetSlideShow( ViewShellBase& rBase );

    static ::com::sun::star::uno::Reference< ::com::sun::star::presentation::XSlideShowController > GetSlideShowController(ViewShellBase& rBase );

    static bool StartPreview( ViewShellBase& rBase,
        const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& xDrawPage,
        const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xAnimationNode,
        ::Window* pParent = 0 );

    static void Stop( ViewShellBase& rBase );

    /// returns true if there is a running presentation for the given ViewShellBase
    static bool IsRunning( ViewShellBase& rBase );

    /// returns true if there is a running presentation inside the given ViewShell
    /// returns false even if there is a running presentation but in another ViewShell
    static bool IsRunning( ViewShell& rViewShell );

    // helper api

    bool startPreview(
        const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& xDrawPage,
        const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xAnimationNode,
        ::Window* pParent = 0 );

    // uno api

        virtual void SAL_CALL disposing (void);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPresentation
    virtual void SAL_CALL start(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL end(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL rehearseTimings(  ) throw (::com::sun::star::uno::RuntimeException);

    // XPresentation2
    virtual void SAL_CALL startWithArguments( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& Arguments ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::sal_Bool SAL_CALL isRunning(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::presentation::XSlideShowController > SAL_CALL getController(  ) throw (::com::sun::star::uno::RuntimeException);

    // legacy api

    // actions
    void jumpToPageNumber( sal_Int32 nPage );               // a.k.a. FuSlideShow::JumpToPage()
    void jumpToPageIndex( sal_Int32 nIndex );
    void jumpToBookmark( const ::rtl::OUString& sBookmark );            // a.k.a. FuSlideShow::JumpToBookmark()

    /** sets or clears the pause state of the running slideshow.
        !!!! This should only be called by the SdShowWindow !!!!*/
    bool pause( bool bPause );

    // settings
    bool isFullScreen();                                // a.k.a. FuSlideShow::IsFullScreen()
    bool isAlwaysOnTop();                               // a.k.a. FuSlideShow::IsAlwaysOnTop();
    ShowWindow* getShowWindow();                        // a.k.a. FuSlideShow::GetShowWindow()
    int getAnimationMode();                             // a.k.a. FuSlideShow::GetAnimationMode()
    sal_Int32 getCurrentPageNumber();                   // a.k.a. FuSlideShow::GetCurrentPage()
    sal_Int32 getCurrentPageIndex();
    sal_Int32 getFirstPageNumber();
    sal_Int32 getLastPageNumber();
    bool isEndless();
    bool isDrawingPossible();

    // events
    void resize( const Size &rSize );
    void activate(ViewShellBase& rBase);
    void deactivate(ViewShellBase& rBase);
    void paint( const Rectangle& rRect );

    bool keyInput(const KeyEvent& rKEvt);

    void receiveRequest(SfxRequest& rReq);

    bool dependsOn( ViewShellBase* pViewShellBase );

    static sal_Int32 GetDisplay();

private:
    SlideShow( SdDrawDocument* pDoc );

    DECL_LINK( StartInPlacePresentationConfigurationHdl, void * );
    void StartInPlacePresentationConfigurationCallback();

    void StartInPlacePresentation();
    void StartFullscreenPresentation();

    void ThrowIfDisposed() throw (::com::sun::star::uno::RuntimeException);

    void CreateController( ViewShell* pViewSh, ::sd::View* pView, ::Window* pParentWindow );

    // default: disabled copy/assignment
    SlideShow(const SlideShow&);
    SlideShow& operator=( const SlideShow& );

    SvxItemPropertySet  maPropSet;

    rtl::Reference< SlideshowImpl > mxController;
    SdDrawDocument* mpDoc;

    boost::shared_ptr< PresentationSettingsEx > mxCurrentSettings;

    ViewShellBase* mpCurrentViewShellBase;
    ViewShellBase* mpFullScreenViewShellBase;
    FrameView* mpFullScreenFrameView;
    sal_Int32   mnInPlaceConfigEvent;
};

}

#endif /* _SD_SLIDESHOW_HXX */
<|endoftext|>


<commit_before>#include "KVProxyServer.h"
#include <QUrl>
#include <QBuffer>
#include <QTcpSocket>
#include <QDebug>

KVProxyServer::KVProxyServer(QObject *parent):
	QTcpServer(parent)
{
	connect(this, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
}

void KVProxyServer::onNewConnection()
{
	qDebug() << "-> New Connection";

	QTcpSocket *socket = this->nextPendingConnection();
	connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));

	socket->setProperty("firstLineRead", false);
	socket->setProperty("headersRead", false);

	socket->setProperty("method", QString());
	socket->setProperty("url", QUrl());
	socket->setProperty("headers", QVariantMap());
	socket->setProperty("body", QByteArray());
}

void KVProxyServer::onReadyRead()
{
	qDebug() << "  -> Ready to Read";
	QTcpSocket *socket = qobject_cast<QTcpSocket*>(QObject::sender());
	if(socket->bytesAvailable() && !socket->property("firstLineRead").toBool())
	{
		qDebug() << "Reading First Line...";
		QString line = socket->readLine();
		int spIndex1 = line.indexOf(" ");
		int spIndex2 = line.indexOf(" ", spIndex1+1);
		socket->setProperty("method", line.left(spIndex1));
		socket->setProperty("url", QUrl(line.mid(spIndex1 + 1, spIndex2 - spIndex1 - 1)));
		qDebug() << socket->property("method");
		qDebug() << socket->property("url");
		socket->setProperty("firstLineRead", true);
	}
	if(socket->bytesAvailable() && !socket->property("headersRead").toBool())
	{
		qDebug() << "Reading Headers...";
		QVariantMap headers = socket->property("headers").toMap();
		while(socket->canReadLine())
		{
			QString line = socket->readLine().trimmed();
			if(!line.isEmpty())
			{
				int sepIndex = line.indexOf(": ");
				QString key = line.left(sepIndex);
				QString value = line.mid(sepIndex + 2);
				//qDebug() << key << ": " << value;
				headers.insert(key, value);
			}
			else
			{
				socket->setProperty("headersRead", true);
				break;
			}
		}

		socket->setProperty("headers", headers);
		qDebug() << socket->property("headers");
	}

	if(socket->property("headersRead").toBool())
	{
		if(socket->bytesAvailable())
		{
			qDebug() << "Reading" << socket->bytesAvailable() << "bytes of body data...";
			QByteArray body = socket->property("body").toByteArray();
			body.append(socket->readAll());
			socket->setProperty("body", body);
		}
		else
		{
			qDebug() << "No Body";
			this->sendProxyRequest(socket);
		}
	}
}

void KVProxyServer::sendProxyRequest(QTcpSocket *requestSocket)
{
	QNetworkRequest request(requestSocket->property("url").toUrl());
	request.setOriginatingObject(requestSocket);

	QVariantMap headers = requestSocket->property("headers").toMap();
	foreach(QString key, headers.keys())
		request.setRawHeader(key.toLatin1(), headers.value(key).toString().toLatin1());

	// Unset default headers
	request.setRawHeader("Connection", QByteArray());
	request.setRawHeader("Accept-Encoding", QByteArray());
	request.setRawHeader("Accept-Language", QByteArray());
	request.setRawHeader("User-Agent", QByteArray());

    //QByteArray body = requestSocket->property("body").toByteArray();
    //QBuffer buffer(&body);
    QNetworkReply *reply = netManager.sendCustomRequest(request, requestSocket->property("method").toString().toLatin1());
    connect(reply, SIGNAL(finished()), this, SLOT(onProxyRequestFinished()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onProxyRequestError(QNetworkReply::NetworkError)));

	qDebug() << "  -> Proxy Request Sent";
}

void KVProxyServer::writeBackResponse(QNetworkReply *reply, QTcpSocket *socket)
{
	socket->write("HTTP/1.1 ");
	socket->write(QString::number(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()).toLatin1());
	socket->write(" ");
	socket->write(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString().toLatin1());
	socket->write("\r\n");

	foreach(QNetworkReply::RawHeaderPair header, reply->rawHeaderPairs())
	{
		if(header.first == "Content-Encoding")
			continue;
		else if(header.first == "Transfer-Encoding")
			continue;
		else if(header.first == "Connection")
			continue;
		else
		{
			socket->write(header.first);
			socket->write(": ");
			socket->write(header.second);
			socket->write("\r\n");
		}
	}
	socket->write("Connection: close\r\n");
	socket->write("\r\n");
	socket->write(reply->readAll());
	socket->disconnectFromHost();

	qDebug() << "  <- Response Written";
}

void KVProxyServer::onProxyRequestFinished()
{
	qDebug() << "    -- Finished";

	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	QTcpSocket *socket = qobject_cast<QTcpSocket*>(reply->request().originatingObject());

	writeBackResponse(reply, socket);
}

void KVProxyServer::onProxyRequestError(QNetworkReply::NetworkError error)
{
	qDebug() << "    -x Error:" << error;

	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	QTcpSocket *socket = qobject_cast<QTcpSocket*>(reply->request().originatingObject());

	writeBackResponse(reply, socket);
}
<commit_msg>Hey, it works<commit_after>#include "KVProxyServer.h"
#include <QUrl>
#include <QBuffer>
#include <QTcpSocket>
#include <QDebug>

KVProxyServer::KVProxyServer(QObject *parent):
	QTcpServer(parent)
{
	connect(this, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
}

void KVProxyServer::onNewConnection()
{
	qDebug() << "-> New Connection";

	QTcpSocket *socket = this->nextPendingConnection();
	connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));

	socket->setProperty("firstLineRead", false);
	socket->setProperty("headersRead", false);

	socket->setProperty("method", QString());
	socket->setProperty("url", QUrl());
	socket->setProperty("headers", QVariantMap());
	socket->setProperty("body", QByteArray());
}

void KVProxyServer::onReadyRead()
{
	//qDebug() << "  -> Ready to Read";
	QTcpSocket *socket = qobject_cast<QTcpSocket*>(QObject::sender());
	if(socket->bytesAvailable() && !socket->property("firstLineRead").toBool())
	{
		qDebug() << "  -- Reading First Line...";
		QString line = socket->readLine();
		int spIndex1 = line.indexOf(" ");
		int spIndex2 = line.indexOf(" ", spIndex1+1);
		socket->setProperty("method", line.left(spIndex1));
		socket->setProperty("url", QUrl(line.mid(spIndex1 + 1, spIndex2 - spIndex1 - 1)));
		qDebug() << socket->property("method");
		qDebug() << socket->property("url");
		socket->setProperty("firstLineRead", true);
	}
	if(socket->bytesAvailable() && !socket->property("headersRead").toBool())
	{
		qDebug() << "  -- Reading Headers...";
		QVariantMap headers = socket->property("headers").toMap();
		while(socket->canReadLine())
		{
			QString line = socket->readLine().trimmed();
			if(!line.isEmpty())
			{
				int sepIndex = line.indexOf(": ");
				QString key = line.left(sepIndex);
				QString value = line.mid(sepIndex + 2);
				//qDebug() << key << ": " << value;
				headers.insert(key, value);
			}
			else
			{
				socket->setProperty("headersRead", true);
				break;
			}
		}

		socket->setProperty("headers", headers);
		qDebug() << socket->property("headers");
	}

	if(socket->property("headersRead").toBool())
	{
		if(socket->bytesAvailable())
		{
			qDebug() << "  -- Reading" << socket->bytesAvailable() << "bytes of body data...";

			QByteArray body = socket->property("body").toByteArray();
			body.append(socket->readAll());
			socket->setProperty("body", body);

			qDebug() << "  -- Complete!";
			int contentLength = socket->property("headers").toMap().value("Content-Length").toInt();
			if(body.size() >= contentLength)
				this->sendProxyRequest(socket);
		}
		else
		{
			qDebug() << "    -- No Body";
			this->sendProxyRequest(socket);
		}
	}
}

void KVProxyServer::sendProxyRequest(QTcpSocket *requestSocket)
{
	QNetworkRequest request(requestSocket->property("url").toUrl());
	request.setOriginatingObject(requestSocket);

	QVariantMap headers = requestSocket->property("headers").toMap();
	foreach(QString key, headers.keys())
		request.setRawHeader(key.toLatin1(), headers.value(key).toString().toLatin1());

	// Unset default headers
	request.setRawHeader("Connection", QByteArray());
	request.setRawHeader("Accept-Encoding", QByteArray());
	request.setRawHeader("Accept-Language", QByteArray());
	request.setRawHeader("User-Agent", QByteArray());

    //QByteArray body = requestSocket->property("body").toByteArray();
    //QBuffer buffer(&body);
    QBuffer *buffer = new QBuffer(this);
    buffer->setData(requestSocket->property("body").toByteArray());

    QNetworkReply *reply = netManager.sendCustomRequest(request, requestSocket->property("method").toString().toLatin1(), buffer);
    connect(reply, SIGNAL(finished()), this, SLOT(onProxyRequestFinished()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onProxyRequestError(QNetworkReply::NetworkError)));

    connect(reply, SIGNAL(finished()), buffer, SLOT(deleteLater()));

	qDebug() << "  -> Proxy Request Sent";
}

void KVProxyServer::writeBackResponse(QNetworkReply *reply, QTcpSocket *socket)
{
	socket->write("HTTP/1.1 ");
	socket->write(QString::number(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()).toLatin1());
	socket->write(" ");
	socket->write(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString().toLatin1());
	socket->write("\r\n");

	foreach(QNetworkReply::RawHeaderPair header, reply->rawHeaderPairs())
	{
		if(header.first == "Content-Encoding")
			continue;
		else if(header.first == "Transfer-Encoding")
			continue;
		else if(header.first == "Connection")
			continue;
		else
		{
			socket->write(header.first);
			socket->write(": ");
			socket->write(header.second);
			socket->write("\r\n");
		}
	}
	socket->write("Connection: close\r\n");
	socket->write("\r\n");
	socket->write(reply->readAll());
	socket->disconnectFromHost();

	qDebug() << "<- Response Written";
}

void KVProxyServer::onProxyRequestFinished()
{
	qDebug() << "    -- Finished";

	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	QTcpSocket *socket = qobject_cast<QTcpSocket*>(reply->request().originatingObject());

	writeBackResponse(reply, socket);
}

void KVProxyServer::onProxyRequestError(QNetworkReply::NetworkError error)
{
	qDebug() << "    -x Error:" << error;

	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	QTcpSocket *socket = qobject_cast<QTcpSocket*>(reply->request().originatingObject());

	writeBackResponse(reply, socket);
}
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOpArgType::OUT WARRANTIES OR CONDITIONS OF ANY KOpArgType::IND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License. */

#include "paddle/framework/grad_op_builder.h"
#include "paddle/framework/op_proto.pb.h"
#include "paddle/framework/op_registry.h"

namespace paddle {
namespace framework {

class OpRegistry;

using VarIndexMap = std::unordered_map<std::string, int>;

enum class OpArgType { IN, OUT };

static std::vector<int>* GetOpFormat(OperatorBase* op, const OpArgType& type) {
  std::string key = type == OpArgType::IN ? "input_format" : "output_format";
  return op->attrs_.count(key)
             ? &boost::get<std::vector<int>>(op->attrs_.at(key))
             : nullptr;
}

static const std::vector<int>* GetOpFormat(const OperatorBase* op,
                                           const OpArgType& type) {
  std::string key = type == OpArgType::IN ? "input_format" : "output_format";
  return op->attrs_.count(key)
             ? &boost::get<std::vector<int>>(op->attrs_.at(key))
             : nullptr;
}

static void TransOpArg(const OperatorBase* src_op, OperatorBase* dst_op,
                       const OpArgType& src_type, const OpArgType& dst_type,
                       int& idx, bool is_grad) {
  const std::vector<std::string>& src_inout =
      src_type == OpArgType::IN ? src_op->inputs_ : src_op->outputs_;
  const std::vector<int>* src_format = GetOpFormat(src_op, src_type);

  std::vector<std::string>& dst_inout =
      dst_type == OpArgType::IN ? dst_op->inputs_ : dst_op->outputs_;
  std::vector<int>* dst_format = GetOpFormat(dst_op, dst_type);
  const OpProto& proto = OpRegistry::protos().at(src_op->type_);
  const auto& src_arg_list =
      src_type == OpArgType::IN ? proto.inputs() : proto.outputs();

  for (const auto& arg : src_arg_list) {
    std::string src_name = arg.name();
    std::string dst_name = is_grad ? src_name + kGradVarSuffix : src_name;
    (*dst_op->in_out_idxs_)[dst_name] = idx++;
    int src_arg_idx = src_op->in_out_idxs_->at(src_name);
    int src_begin =
        src_format == nullptr ? src_arg_idx : src_format->at(src_arg_idx);
    int src_end = src_format == nullptr ? src_arg_idx + 1
                                        : src_format->at(src_arg_idx + 1);
    for (int i = src_begin; i < src_end; ++i) {
      std::string s =
          is_grad ? src_inout[i] + kGradVarSuffix
                  : (arg.ignore_gradient() ? kEmptyVarName : src_inout[i]);
      dst_inout.emplace_back(s);
    }
    if (dst_format != nullptr) {
      dst_format->push_back(dst_inout.size());
    }
  }
}

OperatorBase* BuildGradOp(const OperatorBase* op) {
  std::string grad_op_type = OpRegistry::grad_ops().at(op->type_);
  OperatorBase* grad_op = OpRegistry::op_creators().at(grad_op_type)();
  grad_op->type_ = grad_op_type;
  grad_op->attrs_ = op->attrs_;
  grad_op->attrs_.erase("input_format");
  grad_op->attrs_.erase("output_format");
  if (GetOpFormat(op, OpArgType::IN) != nullptr) {
    grad_op->attrs_["output_format"] = std::vector<int>({0});
  }
  if (GetOpFormat(op, OpArgType::IN) != nullptr ||
      GetOpFormat(op, OpArgType::OUT) != nullptr) {
    grad_op->attrs_["input_format"] = std::vector<int>({0});
  }
  grad_op->in_out_idxs_.reset(new VarIndexMap());
  int in_idx = 0;
  int out_idx = 0;
  TransOpArg(op, grad_op, OpArgType::IN, OpArgType::IN, in_idx, false);   // I
  TransOpArg(op, grad_op, OpArgType::OUT, OpArgType::IN, in_idx, false);  // G
  TransOpArg(op, grad_op, OpArgType::OUT, OpArgType::IN, in_idx, true);   // OG
  TransOpArg(op, grad_op, OpArgType::IN, OpArgType::OUT, out_idx, true);  // IG
  return grad_op;
}

}  // namespace framework
}  // namespace paddle
<commit_msg>Update<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOpArgType::OUT WARRANTIES OR CONDITIONS OF ANY KOpArgType::IND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License. */

#include "paddle/framework/grad_op_builder.h"
#include "paddle/framework/op_proto.pb.h"
#include "paddle/framework/op_registry.h"

namespace paddle {
namespace framework {

class OpRegistry;

using VarIndexMap = std::unordered_map<std::string, int>;

enum class OpArgType { IN, OUT };

static std::vector<int>* GetOpFormat(OperatorBase* op, const OpArgType& type) {
  std::string key = type == OpArgType::IN ? "input_format" : "output_format";
  return op->attrs_.count(key)
             ? &boost::get<std::vector<int>>(op->attrs_.at(key))
             : nullptr;
}

static const std::vector<int>* GetOpFormat(const OperatorBase* op,
                                           const OpArgType& type) {
  std::string key = type == OpArgType::IN ? "input_format" : "output_format";
  return op->attrs_.count(key)
             ? &boost::get<std::vector<int>>(op->attrs_.at(key))
             : nullptr;
}

static void TransOpArg(const OperatorBase* src_op, OperatorBase* dst_op,
                       const OpArgType& src_type, const OpArgType& dst_type,
                       int& idx, bool is_grad) {
  const std::vector<std::string>& src_inout =
      src_type == OpArgType::IN ? src_op->inputs_ : src_op->outputs_;
  const std::vector<int>* src_format = GetOpFormat(src_op, src_type);

  std::vector<std::string>& dst_inout =
      dst_type == OpArgType::IN ? dst_op->inputs_ : dst_op->outputs_;
  std::vector<int>* dst_format = GetOpFormat(dst_op, dst_type);
  const OpProto& proto = OpRegistry::protos().at(src_op->type_);
  const auto& src_arg_list =
      src_type == OpArgType::IN ? proto.inputs() : proto.outputs();

  for (const auto& arg : src_arg_list) {
    std::string src_name = arg.name();
    std::string dst_name = is_grad ? src_name + kGradVarSuffix : src_name;
    (*dst_op->in_out_idxs_)[dst_name] = idx++;
    int src_arg_idx = src_op->in_out_idxs_->at(src_name);
    int src_begin =
        src_format == nullptr ? src_arg_idx : src_format->at(src_arg_idx);
    int src_end = src_format == nullptr ? src_arg_idx + 1
                                        : src_format->at(src_arg_idx + 1);
    for (int i = src_begin; i < src_end; ++i) {
      std::string s =
          is_grad ? src_inout[i] + kGradVarSuffix
                  : (arg.ignore_gradient() ? kEmptyVarName : src_inout[i]);
      dst_inout.emplace_back(s);
    }
    if (dst_format != nullptr) {
      dst_format->push_back(dst_inout.size());
    }
  }
}

OperatorBase* BuildGradOp(const OperatorBase* op) {
  const std::string& grad_op_type = OpRegistry::grad_ops().at(op->Type());
  OperatorBase* grad_op = OpRegistry::op_creators().at(grad_op_type)();
  grad_op->type_ = grad_op_type;
  grad_op->attrs_ = op->attrs_;
  grad_op->attrs_.erase("input_format");
  grad_op->attrs_.erase("output_format");
  if (GetOpFormat(op, OpArgType::IN) != nullptr) {
    grad_op->attrs_["output_format"] = std::vector<int>({0});
  }
  if (GetOpFormat(op, OpArgType::IN) != nullptr ||
      GetOpFormat(op, OpArgType::OUT) != nullptr) {
    grad_op->attrs_["input_format"] = std::vector<int>({0});
  }
  grad_op->in_out_idxs_.reset(new VarIndexMap());
  int in_idx = 0;
  int out_idx = 0;
  TransOpArg(op, grad_op, OpArgType::IN, OpArgType::IN, in_idx, false);   // I
  TransOpArg(op, grad_op, OpArgType::OUT, OpArgType::IN, in_idx, false);  // G
  TransOpArg(op, grad_op, OpArgType::OUT, OpArgType::IN, in_idx, true);   // OG
  TransOpArg(op, grad_op, OpArgType::IN, OpArgType::OUT, out_idx, true);  // IG
  return grad_op;
}

}  // namespace framework
}  // namespace paddle
<|endoftext|>


<commit_before>#pragma once

#include "clonable.hpp"
#include "singleton.hpp"
#include <vector>
#include <map>
#include <stdexcept>

namespace ncv
{
        ///
        /// \brief manager: used to manage different object types associated with ID strings.
        /// hint: use register_object<base, derived> to register objects to the manager.
        ///
        template
        <
                class tobject,
                typename tstring = std::string
        >
        class manager_t : public singleton_t<manager_t<tobject, tstring> >
	{
        public:

                typedef tstring                                                 string_t;
                typedef typename clonable_t<tobject, tstring>::robject_t        robject_t;

                // manage prototypes
                bool add(const tstring& id, const tobject& proto)
                {
                        return _add(id, proto);
                }
                bool has(const tstring& id) const
                {
                        return _has(id);
                }
                robject_t get(const tstring& id) const
                {
                        return _get(id);
                }
                robject_t get(const tstring& id, const tstring& params) const
                {
                        return _get(id, params);
                }

                // access functions
                std::vector<tstring> ids() const { return _ids(); }
                std::vector<tstring> descriptions() const { return _descriptions(); }

        private:

                // object prototypes
                typedef std::map<tstring, robject_t>       	protos_t;
                typedef typename protos_t::const_iterator       protos_const_it;
                typedef typename protos_t::iterator		protos_it;

        private:

                bool _add(const tstring& id, const tobject& proto)
                {
                        return m_protos.insert(typename protos_t::value_type(id, proto.clone())).second;
                }

                bool _has(const tstring& id) const
                {
                        return m_protos.find(id) != m_protos.end();
                }

                robject_t _get(const tstring& id) const
                {
                        const protos_const_it it = m_protos.find(id);
                        if (it == m_protos.end())
                        {
                                throw std::runtime_error("invalid object id <" + id + ">!");
                        }
                        return it->second->clone();
                }

                robject_t _get(const tstring& id, const tstring& params) const
                {
                        const protos_const_it it = m_protos.find(id);
                        if (it == m_protos.end())
                        {
                                throw std::runtime_error("invalid object id <" + id + ">!");
                        }
                        return it->second->make(params);
                }

		template <typename TFunctor>
                std::vector<tstring> _collect(const TFunctor& fun) const
		{
                        std::vector<tstring> result;
                        for (protos_const_it it = m_protos.cbegin(); it != m_protos.cend(); ++ it)
                        {
                                result.push_back(fun(it));
                        }

			return result;
		}

                std::vector<tstring> _ids() const
                {
			return _collect([] (const protos_const_it& it) { return it->first; });
                }

                std::vector<tstring> _descriptions() const
		{
                        return _collect([] (const protos_const_it& it) { return it->second->description(); });
		}

	private:

                // attributes
                protos_t                m_protos;
        };

        ///
        /// \brief register a type tderived to the tbase manager
        ///
        template
        <
                class tbase,
                class tderived
        >
        struct register_object
        {
                register_object(const typename tbase::string_t& id)
                {
                        manager_t<tbase>::instance().add(id, tderived());
                }
        };
}
<commit_msg>cleanup implementation, added documentation<commit_after>#pragma once

#include "clonable.hpp"
#include "singleton.hpp"
#include <vector>
#include <map>
#include <stdexcept>

namespace ncv
{
        ///
        /// \brief manager: used to manage different object types associated with ID strings.
        ///
        /// hint: use register_object<base, derived> to register objects to the manager.
        ///
        template
        <
                class tobject,
                typename tstring = std::string
        >
        class manager_t : public singleton_t<manager_t<tobject, tstring> >
	{
        public:

                typedef tstring                                                 string_t;
                typedef typename clonable_t<tobject, tstring>::robject_t        robject_t;

                ///
                /// \brief add a new object with the given ID
                ///
                bool add(const tstring& id, const tobject& proto)
                {
                        return m_protos.emplace(id, proto.clone()).second;
                }

                ///
                /// \brief check if an objects was registered, given its ID
                ///
                bool has(const tstring& id) const
                {
                        return m_protos.find(id) != m_protos.end();
                }

                ///
                /// \brief retrieve the object associated with the given ID
                ///
                robject_t get(const tstring& id) const
                {
                        const auto it = m_protos.find(id);
                        assert_it(id, it);
                        return it->second->clone();
                }

                ///
                /// \brief retrieve the object associated with the given ID, constructed from the given parameters
                ///
                robject_t get(const tstring& id, const tstring& params) const
                {
                        const auto it = m_protos.find(id);
                        assert_it(id, it);
                        return it->second->make(params);
                }

                ///
                /// \brief get the IDs of all registered objects
                ///
                std::vector<tstring> ids() const
                {
                        return collect([] (const auto& it) { return it.first; });
                }

                ///
                /// \brief get the descriptions of all registered objects
                ///
                std::vector<tstring> descriptions() const
                {
                        return collect([] (const auto& it) { return it.second->description(); });
                }

        private:

                template <typename tfunctor>
                std::vector<tstring> collect(const tfunctor& fun) const
		{
                        std::vector<tstring> result;
                        for (const auto& it : m_protos)
                        {
                                result.push_back(fun(it));
                        }

			return result;
                }

                template <typename titerator>
                void assert_it(const tstring& id, const titerator& it) const
                {
                          if (it == m_protos.end())
                          {
                                  throw std::runtime_error("invalid object id <" + id + ">!");
                          }
                }

	private:

                // attributes
                std::map<tstring, robject_t>    m_protos;       ///< registered objects
        };

        ///
        /// \brief register a type tderived to the tbase manager
        ///
        template
        <
                class tbase,
                class tderived
        >
        struct register_object
        {
                register_object(const typename tbase::string_t& id)
                {
                        manager_t<tbase>::instance().add(id, tderived());
                }
        };
}
<|endoftext|>


<commit_before>#include "FastLED.h"

#ifdef FASTLED_AVR
extern "C" {
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

typedef union { unsigned long _long; uint8_t raw[4]; } tBytesForLong;
// tBytesForLong FastLED_timer0_overflow_count;
volatile unsigned long FastLED_timer0_overflow_count=0;
volatile unsigned long FastLED_timer0_millis = 0;

LIB8STATIC void  __attribute__((always_inline)) fastinc32 (volatile uint32_t & _long) {
  uint8_t b = ++((tBytesForLong&)_long).raw[0];
  if(!b) {
    b = ++((tBytesForLong&)_long).raw[1];
    if(!b) {
      b = ++((tBytesForLong&)_long).raw[2];
      if(!b) {
        ++((tBytesForLong&)_long).raw[3];
      }
    }
  }
}

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
  fastinc32(FastLED_timer0_overflow_count);
  // FastLED_timer0_overflow_count++;
}

// there are 1024 microseconds per overflow counter tick.
unsigned long millis()
{
        unsigned long m;
        uint8_t oldSREG = SREG;

        // disable interrupts while we read FastLED_timer0_millis or we might get an
        // inconsistent value (e.g. in the middle of a write to FastLED_timer0_millis)
        cli();
        m = FastLED_timer0_overflow_count;  //._long;
        SREG = oldSREG;

        return (m*MICROSECONDS_PER_TIMER0_OVERFLOW)/1000;
}

unsigned long micros() {
        unsigned long m;
        uint8_t oldSREG = SREG, t;

        cli();
        m = FastLED_timer0_overflow_count; // ._long;
#if defined(TCNT0)
        t = TCNT0;
#elif defined(TCNT0L)
        t = TCNT0L;
#else
        #error TIMER 0 not defined
#endif

#ifdef TIFR0
        if ((TIFR0 & _BV(TOV0)) && (t < 255))
                m++;
#else
        if ((TIFR & _BV(TOV0)) && (t < 255))
                m++;
#endif

        SREG = oldSREG;

        return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

void delay(unsigned long ms)
{
        uint16_t start = (uint16_t)micros();

        while (ms > 0) {
                if (((uint16_t)micros() - start) >= 1000) {
                        ms--;
                        start += 1000;
                }
        }
}

/* Delay for the given number of microseconds.  Assumes a 8 or 16 MHz clock. */
void delayMicroseconds(unsigned int us)
{
        // calling avrlib's delay_us() function with low values (e.g. 1 or
        // 2 microseconds) gives delays longer than desired.
        //delay_us(us);
#if F_CPU >= 20000000L
        // for the 20 MHz clock on rare Arduino boards

        // for a one-microsecond delay, simply wait 2 cycle and return. The overhead
        // of the function call yields a delay of exactly a one microsecond.
        __asm__ __volatile__ (
                "nop" "\n\t"
                "nop"); //just waiting 2 cycle
        if (--us == 0)
                return;

        // the following loop takes a 1/5 of a microsecond (4 cycles)
        // per iteration, so execute it five times for each microsecond of
        // delay requested.
        us = (us<<2) + us; // x5 us

        // account for the time taken in the preceeding commands.
        us -= 2;

#elif F_CPU >= 16000000L
        // for the 16 MHz clock on most Arduino boards

        // for a one-microsecond delay, simply return.  the overhead
        // of the function call yields a delay of approximately 1 1/8 us.
        if (--us == 0)
                return;

        // the following loop takes a quarter of a microsecond (4 cycles)
        // per iteration, so execute it four times for each microsecond of
        // delay requested.
        us <<= 2;

        // account for the time taken in the preceeding commands.
        us -= 2;
#else
        // for the 8 MHz internal clock on the ATmega168

        // for a one- or two-microsecond delay, simply return.  the overhead of
        // the function calls takes more than two microseconds.  can't just
        // subtract two, since us is unsigned; we'd overflow.
        if (--us == 0)
                return;
        if (--us == 0)
                return;

        // the following loop takes half of a microsecond (4 cycles)
        // per iteration, so execute it twice for each microsecond of
        // delay requested.
        us <<= 1;

        // partially compensate for the time taken by the preceeding commands.
        // we can't subtract any more than this or we'd overflow w/ small delays.
        us--;
#endif

        // busy wait
        __asm__ __volatile__ (
                "1: sbiw %0,1" "\n\t" // 2 cycles
                "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
        );
}
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
void init()
{
  // this needs to be called before setup() or some functions won't
  // work there
  sei();

  // on the ATmega168, timer 0 is also used for fast hardware pwm
  // (using phase-correct PWM would mean that timer 0 overflowed half as often
  // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
  sbi(TCCR0A, WGM01);
  sbi(TCCR0A, WGM00);
#endif

  // set timer 0 prescale factor to 64
#if defined(__AVR_ATmega128__)
  // CPU specific: different values for the ATmega128
  sbi(TCCR0, CS02);
#elif defined(TCCR0) && defined(CS01) && defined(CS00)
  // this combination is for the standard atmega8
  sbi(TCCR0, CS01);
  sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
  // this combination is for the standard 168/328/1280/2560
  sbi(TCCR0B, CS01);
  sbi(TCCR0B, CS00);
#elif defined(TCCR0A) && defined(CS01) && defined(CS00)
  // this combination is for the __AVR_ATmega645__ series
  sbi(TCCR0A, CS01);
  sbi(TCCR0A, CS00);
#else
  #error Timer 0 prescale factor 64 not set correctly
#endif

  // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
  sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
  sbi(TIMSK0, TOIE0);
#else
  #error	Timer 0 overflow interrupt not set correctly
#endif

  // timers 1 and 2 are used for phase-correct hardware pwm
  // this is better for motors as it ensures an even waveform
  // note, however, that fast pwm mode can achieve a frequency of up
  // 8 MHz (with a 16 MHz clock) at 50% duty cycle

#if defined(TCCR1B) && defined(CS11) && defined(CS10)
  TCCR1B = 0;

  // set timer 1 prescale factor to 64
  sbi(TCCR1B, CS11);
#if F_CPU >= 8000000L
  sbi(TCCR1B, CS10);
#endif
#elif defined(TCCR1) && defined(CS11) && defined(CS10)
  sbi(TCCR1, CS11);
#if F_CPU >= 8000000L
  sbi(TCCR1, CS10);
#endif
#endif
  // put timer 1 in 8-bit phase correct pwm mode
#if defined(TCCR1A) && defined(WGM10)
  sbi(TCCR1A, WGM10);
#elif defined(TCCR1)
  #warning this needs to be finished
#endif

  // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
  sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
  sbi(TCCR2B, CS22);
#else
  #warning Timer 2 not finished (may not be present on this CPU)
#endif

  // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
  sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
  sbi(TCCR2A, WGM20);
#else
  #warning Timer 2 not finished (may not be present on this CPU)
#endif

#if defined(TCCR3B) && defined(CS31) && defined(WGM30)
  sbi(TCCR3B, CS31);		// set timer 3 prescale factor to 64
  sbi(TCCR3B, CS30);
  sbi(TCCR3A, WGM30);		// put timer 3 in 8-bit phase correct pwm mode
#endif

#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */
  sbi(TCCR4B, CS42);		// set timer4 prescale factor to 64
  sbi(TCCR4B, CS41);
  sbi(TCCR4B, CS40);
  sbi(TCCR4D, WGM40);		// put timer 4 in phase- and frequency-correct PWM mode
  sbi(TCCR4A, PWM4A);		// enable PWM mode for comparator OCR4A
  sbi(TCCR4C, PWM4D);		// enable PWM mode for comparator OCR4D
#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */
#if defined(TCCR4B) && defined(CS41) && defined(WGM40)
  sbi(TCCR4B, CS41);		// set timer 4 prescale factor to 64
  sbi(TCCR4B, CS40);
  sbi(TCCR4A, WGM40);		// put timer 4 in 8-bit phase correct pwm mode
#endif
#endif /* end timer4 block for ATMEGA1280/2560 and similar */

#if defined(TCCR5B) && defined(CS51) && defined(WGM50)
  sbi(TCCR5B, CS51);		// set timer 5 prescale factor to 64
  sbi(TCCR5B, CS50);
  sbi(TCCR5A, WGM50);		// put timer 5 in 8-bit phase correct pwm mode
#endif

#if defined(ADCSRA)
  // set a2d prescale factor to 128
  // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
  // XXX: this will not work properly for other clock speeds, and
  // this code should use F_CPU to determine the prescale factor.
  sbi(ADCSRA, ADPS2);
  sbi(ADCSRA, ADPS1);
  sbi(ADCSRA, ADPS0);

  // enable a2d conversions
  sbi(ADCSRA, ADEN);
#endif

  // the bootloader connects pins 0 and 1 to the USART; disconnect them
  // here so they can be used as normal digital i/o; they will be
  // reconnected in Serial.begin()
#if defined(UCSRB)
  UCSRB = 0;
#elif defined(UCSR0B)
  UCSR0B = 0;
#endif
}
};
#endif
<commit_msg>Improve the math a bit<commit_after>#include "FastLED.h"

#ifdef FASTLED_AVR
extern "C" {
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

typedef union { unsigned long _long; uint8_t raw[4]; } tBytesForLong;
// tBytesForLong FastLED_timer0_overflow_count;
volatile unsigned long FastLED_timer0_overflow_count=0;
volatile unsigned long FastLED_timer0_millis = 0;

LIB8STATIC void  __attribute__((always_inline)) fastinc32 (volatile uint32_t & _long) {
  uint8_t b = ++((tBytesForLong&)_long).raw[0];
  if(!b) {
    b = ++((tBytesForLong&)_long).raw[1];
    if(!b) {
      b = ++((tBytesForLong&)_long).raw[2];
      if(!b) {
        ++((tBytesForLong&)_long).raw[3];
      }
    }
  }
}

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
  fastinc32(FastLED_timer0_overflow_count);
  // FastLED_timer0_overflow_count++;
}

// there are 1024 microseconds per overflow counter tick.
unsigned long millis()
{
        unsigned long m;
        uint8_t oldSREG = SREG;

        // disable interrupts while we read FastLED_timer0_millis or we might get an
        // inconsistent value (e.g. in the middle of a write to FastLED_timer0_millis)
        cli();
        m = FastLED_timer0_overflow_count;  //._long;
        SREG = oldSREG;

        return (m*(MICROSECONDS_PER_TIMER0_OVERFLOW/8))/(1000/8);
}

unsigned long micros() {
        unsigned long m;
        uint8_t oldSREG = SREG, t;

        cli();
        m = FastLED_timer0_overflow_count; // ._long;
#if defined(TCNT0)
        t = TCNT0;
#elif defined(TCNT0L)
        t = TCNT0L;
#else
        #error TIMER 0 not defined
#endif

#ifdef TIFR0
        if ((TIFR0 & _BV(TOV0)) && (t < 255))
                m++;
#else
        if ((TIFR & _BV(TOV0)) && (t < 255))
                m++;
#endif

        SREG = oldSREG;

        return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

void delay(unsigned long ms)
{
        uint16_t start = (uint16_t)micros();

        while (ms > 0) {
                if (((uint16_t)micros() - start) >= 1000) {
                        ms--;
                        start += 1000;
                }
        }
}

#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
void init()
{
  // this needs to be called before setup() or some functions won't
  // work there
  sei();

  // on the ATmega168, timer 0 is also used for fast hardware pwm
  // (using phase-correct PWM would mean that timer 0 overflowed half as often
  // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
  sbi(TCCR0A, WGM01);
  sbi(TCCR0A, WGM00);
#endif

  // set timer 0 prescale factor to 64
#if defined(__AVR_ATmega128__)
  // CPU specific: different values for the ATmega128
  sbi(TCCR0, CS02);
#elif defined(TCCR0) && defined(CS01) && defined(CS00)
  // this combination is for the standard atmega8
  sbi(TCCR0, CS01);
  sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
  // this combination is for the standard 168/328/1280/2560
  sbi(TCCR0B, CS01);
  sbi(TCCR0B, CS00);
#elif defined(TCCR0A) && defined(CS01) && defined(CS00)
  // this combination is for the __AVR_ATmega645__ series
  sbi(TCCR0A, CS01);
  sbi(TCCR0A, CS00);
#else
  #error Timer 0 prescale factor 64 not set correctly
#endif

  // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
  sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
  sbi(TIMSK0, TOIE0);
#else
  #error	Timer 0 overflow interrupt not set correctly
#endif

  // timers 1 and 2 are used for phase-correct hardware pwm
  // this is better for motors as it ensures an even waveform
  // note, however, that fast pwm mode can achieve a frequency of up
  // 8 MHz (with a 16 MHz clock) at 50% duty cycle

#if defined(TCCR1B) && defined(CS11) && defined(CS10)
  TCCR1B = 0;

  // set timer 1 prescale factor to 64
  sbi(TCCR1B, CS11);
#if F_CPU >= 8000000L
  sbi(TCCR1B, CS10);
#endif
#elif defined(TCCR1) && defined(CS11) && defined(CS10)
  sbi(TCCR1, CS11);
#if F_CPU >= 8000000L
  sbi(TCCR1, CS10);
#endif
#endif
  // put timer 1 in 8-bit phase correct pwm mode
#if defined(TCCR1A) && defined(WGM10)
  sbi(TCCR1A, WGM10);
#elif defined(TCCR1)
  #warning this needs to be finished
#endif

  // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
  sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
  sbi(TCCR2B, CS22);
#else
  #warning Timer 2 not finished (may not be present on this CPU)
#endif

  // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
  sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
  sbi(TCCR2A, WGM20);
#else
  #warning Timer 2 not finished (may not be present on this CPU)
#endif

#if defined(TCCR3B) && defined(CS31) && defined(WGM30)
  sbi(TCCR3B, CS31);		// set timer 3 prescale factor to 64
  sbi(TCCR3B, CS30);
  sbi(TCCR3A, WGM30);		// put timer 3 in 8-bit phase correct pwm mode
#endif

#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */
  sbi(TCCR4B, CS42);		// set timer4 prescale factor to 64
  sbi(TCCR4B, CS41);
  sbi(TCCR4B, CS40);
  sbi(TCCR4D, WGM40);		// put timer 4 in phase- and frequency-correct PWM mode
  sbi(TCCR4A, PWM4A);		// enable PWM mode for comparator OCR4A
  sbi(TCCR4C, PWM4D);		// enable PWM mode for comparator OCR4D
#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */
#if defined(TCCR4B) && defined(CS41) && defined(WGM40)
  sbi(TCCR4B, CS41);		// set timer 4 prescale factor to 64
  sbi(TCCR4B, CS40);
  sbi(TCCR4A, WGM40);		// put timer 4 in 8-bit phase correct pwm mode
#endif
#endif /* end timer4 block for ATMEGA1280/2560 and similar */

#if defined(TCCR5B) && defined(CS51) && defined(WGM50)
  sbi(TCCR5B, CS51);		// set timer 5 prescale factor to 64
  sbi(TCCR5B, CS50);
  sbi(TCCR5A, WGM50);		// put timer 5 in 8-bit phase correct pwm mode
#endif

#if defined(ADCSRA)
  // set a2d prescale factor to 128
  // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
  // XXX: this will not work properly for other clock speeds, and
  // this code should use F_CPU to determine the prescale factor.
  sbi(ADCSRA, ADPS2);
  sbi(ADCSRA, ADPS1);
  sbi(ADCSRA, ADPS0);

  // enable a2d conversions
  sbi(ADCSRA, ADEN);
#endif

  // the bootloader connects pins 0 and 1 to the USART; disconnect them
  // here so they can be used as normal digital i/o; they will be
  // reconnected in Serial.begin()
#if defined(UCSRB)
  UCSRB = 0;
#elif defined(UCSR0B)
  UCSR0B = 0;
#endif
}
};
#endif
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Hunspell, based on MySpell.
 *
 * The Initial Developers of the Original Code are
 * Kevin Hendricks (MySpell) and Németh László (Hunspell).
 * Portions created by the Initial Developers are Copyright (C) 2002-2005
 * the Initial Developers. All Rights Reserved.
 *
 * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
 * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
 * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
 * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
 * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
/*
 * Copyright 2002 Kevin B. Hendricks, Stratford, Ontario, Canada
 * And Contributors.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. All modifications to the source code must be clearly marked as
 *    such.  Binary redistributions based on modified source code
 *    must be clearly marked as modified versions in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * KEVIN B. HENDRICKS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef _SUGGESTMGR_HXX_
#define _SUGGESTMGR_HXX_

#define MAXSWL 100
#define MAXSWUTF8L (MAXSWL * 4)
#define MAX_ROOTS 100
#define MAX_WORDS 100
#define MAX_GUESS 200
#define MAXNGRAMSUGS 4
#define MAXPHONSUGS 2
#define MAXCOMPOUNDSUGS 3

// timelimit: max ~1/4 sec (process time on Linux) for a time consuming function
#define TIMELIMIT (CLOCKS_PER_SEC >> 2)
#define MINTIMER 100
#define MAXPLUSTIMER 100

#define NGRAM_LONGER_WORSE (1 << 0)
#define NGRAM_ANY_MISMATCH (1 << 1)
#define NGRAM_LOWERING (1 << 2)
#define NGRAM_WEIGHTED (1 << 3)

#include "hunvisapi.h"

#include "atypes.hxx"
#include "affixmgr.hxx"
#include "hashmgr.hxx"
#include "langnum.hxx"
#include <time.h>

enum { LCS_UP, LCS_LEFT, LCS_UPLEFT };

class LIBHUNSPELL_DLL_EXPORTED SuggestMgr {
 private:
  SuggestMgr(const SuggestMgr&);
  SuggestMgr& operator=(const SuggestMgr&);

 private:
  char* ckey;
  int ckeyl;
  w_char* ckey_utf;

  char* ctry;
  int ctryl;
  w_char* ctry_utf;

  AffixMgr* pAMgr;
  int maxSug;
  struct cs_info* csconv;
  int utf8;
  int langnum;
  int nosplitsugs;
  int maxngramsugs;
  int maxcpdsugs;
  int complexprefixes;

 public:
  SuggestMgr(const char* tryme, int maxn, AffixMgr* aptr);
  ~SuggestMgr();

  int suggest(char*** slst, const char* word, int nsug, int* onlycmpdsug);
  int ngsuggest(char** wlst, const char* word, int ns, HashMgr** pHMgr, int md);
  int suggest_auto(char*** slst, const char* word, int nsug);
  int suggest_stems(char*** slst, const char* word, int nsug);
  int suggest_pos_stems(char*** slst, const char* word, int nsug);

  char* suggest_morph(const char* word);
  char* suggest_gen(char** pl, int pln, const char* pattern);
  char* suggest_morph_for_spelling_error(const char* word);

 private:
  int testsug(char** wlst,
              const char* candidate,
              int wl,
              int ns,
              int cpdsuggest,
              int* timer,
              clock_t* timelimit);
  int checkword(const char*, int, int, int*, clock_t*);
  int check_forbidden(const char*, int);

  int capchars(char**, const char*, int, int);
  int replchars(char**, const char*, int, int);
  int doubletwochars(char**, const char*, int, int);
  int forgotchar(char**, const char*, int, int);
  int swapchar(char**, const char*, int, int);
  int longswapchar(char**, const char*, int, int);
  int movechar(char**, const char*, int, int);
  int extrachar(char**, const char*, int, int);
  int badcharkey(char**, const char*, int, int);
  int badchar(char**, const char*, int, int);
  int twowords(char**, const char*, int, int);
  int fixstems(char**, const char*, int);

  int capchars_utf(char**, const w_char*, int wl, int, int);
  int doubletwochars_utf(char**, const w_char*, int wl, int, int);
  int forgotchar_utf(char**, const w_char*, int wl, int, int);
  int extrachar_utf(char**, const w_char*, int wl, int, int);
  int badcharkey_utf(char**, const w_char*, int wl, int, int);
  int badchar_utf(char**, const w_char*, int wl, int, int);
  int swapchar_utf(char**, const w_char*, int wl, int, int);
  int longswapchar_utf(char**, const w_char*, int, int, int);
  int movechar_utf(char**, const w_char*, int, int, int);

  int mapchars(char**, const char*, int, int);
  int map_related(const char*,
                  std::string&,
                  int,
                  char** wlst,
                  int,
                  int,
                  const mapentry*,
                  int,
                  int*,
                  clock_t*);
  int ngram(int n, const std::string& s1, const std::string& s2, int opt);
  int mystrlen(const char* word);
  int leftcommonsubstring(const char* s1, const char* s2);
  int commoncharacterpositions(const char* s1, const char* s2, int* is_swap);
  void bubblesort(char** rwd, char** rwd2, int* rsc, int n);
  void lcs(const char* s, const char* s2, int* l1, int* l2, char** result);
  int lcslen(const char* s, const char* s2);
  int lcslen(const std::string& s, const std::string& s2);
  char* suggest_hentry_gen(hentry* rv, const char* pattern);
};

#endif
<commit_msg>drop unused MAXSWUTF8L and MAXSWL<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Hunspell, based on MySpell.
 *
 * The Initial Developers of the Original Code are
 * Kevin Hendricks (MySpell) and Németh László (Hunspell).
 * Portions created by the Initial Developers are Copyright (C) 2002-2005
 * the Initial Developers. All Rights Reserved.
 *
 * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
 * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
 * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
 * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
 * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
/*
 * Copyright 2002 Kevin B. Hendricks, Stratford, Ontario, Canada
 * And Contributors.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. All modifications to the source code must be clearly marked as
 *    such.  Binary redistributions based on modified source code
 *    must be clearly marked as modified versions in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * KEVIN B. HENDRICKS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef _SUGGESTMGR_HXX_
#define _SUGGESTMGR_HXX_

#define MAX_ROOTS 100
#define MAX_WORDS 100
#define MAX_GUESS 200
#define MAXNGRAMSUGS 4
#define MAXPHONSUGS 2
#define MAXCOMPOUNDSUGS 3

// timelimit: max ~1/4 sec (process time on Linux) for a time consuming function
#define TIMELIMIT (CLOCKS_PER_SEC >> 2)
#define MINTIMER 100
#define MAXPLUSTIMER 100

#define NGRAM_LONGER_WORSE (1 << 0)
#define NGRAM_ANY_MISMATCH (1 << 1)
#define NGRAM_LOWERING (1 << 2)
#define NGRAM_WEIGHTED (1 << 3)

#include "hunvisapi.h"

#include "atypes.hxx"
#include "affixmgr.hxx"
#include "hashmgr.hxx"
#include "langnum.hxx"
#include <time.h>

enum { LCS_UP, LCS_LEFT, LCS_UPLEFT };

class LIBHUNSPELL_DLL_EXPORTED SuggestMgr {
 private:
  SuggestMgr(const SuggestMgr&);
  SuggestMgr& operator=(const SuggestMgr&);

 private:
  char* ckey;
  int ckeyl;
  w_char* ckey_utf;

  char* ctry;
  int ctryl;
  w_char* ctry_utf;

  AffixMgr* pAMgr;
  int maxSug;
  struct cs_info* csconv;
  int utf8;
  int langnum;
  int nosplitsugs;
  int maxngramsugs;
  int maxcpdsugs;
  int complexprefixes;

 public:
  SuggestMgr(const char* tryme, int maxn, AffixMgr* aptr);
  ~SuggestMgr();

  int suggest(char*** slst, const char* word, int nsug, int* onlycmpdsug);
  int ngsuggest(char** wlst, const char* word, int ns, HashMgr** pHMgr, int md);
  int suggest_auto(char*** slst, const char* word, int nsug);
  int suggest_stems(char*** slst, const char* word, int nsug);
  int suggest_pos_stems(char*** slst, const char* word, int nsug);

  char* suggest_morph(const char* word);
  char* suggest_gen(char** pl, int pln, const char* pattern);
  char* suggest_morph_for_spelling_error(const char* word);

 private:
  int testsug(char** wlst,
              const char* candidate,
              int wl,
              int ns,
              int cpdsuggest,
              int* timer,
              clock_t* timelimit);
  int checkword(const char*, int, int, int*, clock_t*);
  int check_forbidden(const char*, int);

  int capchars(char**, const char*, int, int);
  int replchars(char**, const char*, int, int);
  int doubletwochars(char**, const char*, int, int);
  int forgotchar(char**, const char*, int, int);
  int swapchar(char**, const char*, int, int);
  int longswapchar(char**, const char*, int, int);
  int movechar(char**, const char*, int, int);
  int extrachar(char**, const char*, int, int);
  int badcharkey(char**, const char*, int, int);
  int badchar(char**, const char*, int, int);
  int twowords(char**, const char*, int, int);
  int fixstems(char**, const char*, int);

  int capchars_utf(char**, const w_char*, int wl, int, int);
  int doubletwochars_utf(char**, const w_char*, int wl, int, int);
  int forgotchar_utf(char**, const w_char*, int wl, int, int);
  int extrachar_utf(char**, const w_char*, int wl, int, int);
  int badcharkey_utf(char**, const w_char*, int wl, int, int);
  int badchar_utf(char**, const w_char*, int wl, int, int);
  int swapchar_utf(char**, const w_char*, int wl, int, int);
  int longswapchar_utf(char**, const w_char*, int, int, int);
  int movechar_utf(char**, const w_char*, int, int, int);

  int mapchars(char**, const char*, int, int);
  int map_related(const char*,
                  std::string&,
                  int,
                  char** wlst,
                  int,
                  int,
                  const mapentry*,
                  int,
                  int*,
                  clock_t*);
  int ngram(int n, const std::string& s1, const std::string& s2, int opt);
  int mystrlen(const char* word);
  int leftcommonsubstring(const char* s1, const char* s2);
  int commoncharacterpositions(const char* s1, const char* s2, int* is_swap);
  void bubblesort(char** rwd, char** rwd2, int* rsc, int n);
  void lcs(const char* s, const char* s2, int* l1, int* l2, char** result);
  int lcslen(const char* s, const char* s2);
  int lcslen(const std::string& s, const std::string& s2);
  char* suggest_hentry_gen(hentry* rv, const char* pattern);
};

#endif
<|endoftext|>


<commit_before><?hh // strict

/**
 * This file is part of hhpack\process package.
 *
 * (c) Noritaka Horio <holy.shared.design@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace hhpack\process\input;

use hhpack\process\Stream;
use hhpack\process\Readable;
use hhpack\process\Writable;

// FIXME Remove getOutput() method
interface ReadableStream<T> extends Stream, Readable
{
    public function getOutput() : Writable<T>;
    public function pipeTo(Writable<T> $output) : void;
}
<commit_msg>Remove getOutput<commit_after><?hh // strict

/**
 * This file is part of hhpack\process package.
 *
 * (c) Noritaka Horio <holy.shared.design@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace hhpack\process\input;

use hhpack\process\Stream;
use hhpack\process\Readable;
use hhpack\process\Writable;

interface ReadableStream<T> extends Stream, Readable
{
    public function pipeTo(Writable<T> $output) : void;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: appbaslib.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2007-01-29 15:07:20 $
 *
 *  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 APPBASLIB_HXX
#include "appbaslib.hxx"
#endif

#include "sfxuno.hxx"
#include "sfxtypes.hxx"
#include "app.hxx"

#include <basic/basmgr.hxx>
#include <basic/namecont.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::script;
using namespace ::com::sun::star::embed;
using ::rtl::OUString;
using ::osl::MutexGuard;
using ::osl::Mutex;

using ::basic::SfxLibraryContainer;

//============================================================================
SfxBasicManagerHolder::SfxBasicManagerHolder()
    :mpBasicManager( NULL )
    ,mpBasicLibContainer( NULL )
    ,mpDialogLibContainer( NULL )
{
}

void SfxBasicManagerHolder::reset( BasicManager* _pBasicManager )
{
    impl_releaseContainers();

    // Note: we do not delete the old BasicManager. BasicManager instances are
    // nowadays obtained from the BasicManagerRepository, and the ownership is with
    // the repository.
    // @see basic::BasicManagerRepository::getApplicationBasicManager
    // @see basic::BasicManagerRepository::getDocumentBasicManager
    mpBasicManager = _pBasicManager;

    if ( mpBasicManager )
    {
        const LibraryContainerInfo& rContainerInfo( mpBasicManager->GetLibraryContainerInfo() );
        mpBasicLibContainer = dynamic_cast< SfxLibraryContainer* >( rContainerInfo.mxScriptCont.get() );
        mpDialogLibContainer = dynamic_cast< SfxLibraryContainer* >( rContainerInfo.mxDialogCont.get() );
        DBG_ASSERT( mpBasicLibContainer && mpDialogLibContainer,
            "SfxBasicManagerHolder::reset: invalid library container implementations!" );

        if ( mpBasicLibContainer )
            mpBasicLibContainer->acquire();
        if ( mpDialogLibContainer )
            mpDialogLibContainer->acquire();
    }
}

bool SfxBasicManagerHolder::isAnyContainerModified() const
{
    if ( mpBasicLibContainer && mpBasicLibContainer->isContainerModified() )
        return true;
    if ( mpDialogLibContainer && mpDialogLibContainer->isContainerModified() )
        return true;
    return false;
}

void SfxBasicManagerHolder::storeLibraries( ContainerType _eType, bool _bComplete )
{
    SfxLibraryContainer* pContainer = impl_getContainer( _eType );
    if ( pContainer )
        pContainer->storeLibraries( _bComplete );
}

void SfxBasicManagerHolder::setStorage( const Reference< XStorage >& _rxStorage )
{
    SfxLibraryContainer* pContainer = impl_getContainer( SCRIPTS );
    if ( pContainer )
        pContainer->setStorage( _rxStorage );

    pContainer = impl_getContainer( DIALOGS );
    if ( pContainer )
        pContainer->setStorage( _rxStorage );
}

void SfxBasicManagerHolder::storeLibrariesToStorage( const Reference< XStorage >& _rxStorage )
{
    SfxLibraryContainer* pContainer = impl_getContainer( SCRIPTS );
    if ( pContainer )
        pContainer->storeLibrariesToStorage( _rxStorage );

    pContainer = impl_getContainer( DIALOGS );
    if ( pContainer )
        pContainer->storeLibrariesToStorage( _rxStorage );
}

Reference< XLibraryContainer > SfxBasicManagerHolder::getLibraryContainer( ContainerType _eType )
{
    return impl_getContainer( _eType );
}

void SfxBasicManagerHolder::impl_releaseContainers()
{
    if ( mpBasicLibContainer )
        mpBasicLibContainer->release();
    mpBasicLibContainer = NULL;
    if ( mpDialogLibContainer )
        mpDialogLibContainer->release();
    mpDialogLibContainer = NULL;
}

SfxLibraryContainer* SfxBasicManagerHolder::impl_getContainer( ContainerType _eType )
{
    switch ( _eType )
    {
    case SCRIPTS:   return mpBasicLibContainer;
    case DIALOGS:   return mpDialogLibContainer;
    }
    DBG_ERROR( "SfxBasicManagerHolder::impl_getContainer: illegal container type!" );
    return NULL;
}

// could have moved this to basic/BasicManager class, however probably best
// to keep the nasty use of the uno implementation SfxLibraryContainer class in
// one place
sal_Bool
SfxBasicManagerHolder::LegacyPsswdBinaryLimitExceeded( Sequence< rtl::OUString >& sModules )
{
    if ( mpBasicLibContainer )
        return mpBasicLibContainer->LegacyPsswdBinaryLimitExceeded( sModules );
    return sal_True;
}

//============================================================================
// Service for application library container
SFX_IMPL_ONEINSTANCEFACTORY( SfxApplicationDialogLibraryContainer )

Sequence< OUString > SfxApplicationDialogLibraryContainer::impl_getStaticSupportedServiceNames()
{
    static Sequence< OUString > seqServiceNames( 1 );
    static sal_Bool bNeedsInit = sal_True;

    MutexGuard aGuard( Mutex::getGlobalMutex() );
    if( bNeedsInit )
    {
        OUString* pSeq = seqServiceNames.getArray();
        pSeq[0] = OUString::createFromAscii( "com.sun.star.script.ApplicationDialogLibraryContainer" );
        bNeedsInit = sal_False;
    }
    return seqServiceNames;
}

OUString SfxApplicationDialogLibraryContainer::impl_getStaticImplementationName()
{
    static OUString aImplName;
    static sal_Bool bNeedsInit = sal_True;

    MutexGuard aGuard( Mutex::getGlobalMutex() );
    if( bNeedsInit )
    {
        aImplName = OUString::createFromAscii( "com.sun.star.comp.sfx2.ApplicationDialogLibraryContainer" );
        bNeedsInit = sal_False;
    }
    return aImplName;
}

Reference< XInterface > SAL_CALL SfxApplicationDialogLibraryContainer::impl_createInstance
    ( const Reference< XMultiServiceFactory >& )
        throw( Exception )
{
    SFX_APP()->GetBasicManager();
    Reference< XInterface > xRet =
        Reference< XInterface >( SFX_APP()->GetDialogContainer(), UNO_QUERY );
    return xRet;
}

//============================================================================
// Service for application library container
SFX_IMPL_ONEINSTANCEFACTORY( SfxApplicationScriptLibraryContainer )

Sequence< OUString > SfxApplicationScriptLibraryContainer::impl_getStaticSupportedServiceNames()
{
    static Sequence< OUString > seqServiceNames( 1 );
    static sal_Bool bNeedsInit = sal_True;

    MutexGuard aGuard( Mutex::getGlobalMutex() );
    if( bNeedsInit )
    {
        OUString* pSeq = seqServiceNames.getArray();
        pSeq[0] = OUString::createFromAscii( "com.sun.star.script.ApplicationScriptLibraryContainer" );
        bNeedsInit = sal_False;
    }
    return seqServiceNames;
}

OUString SfxApplicationScriptLibraryContainer::impl_getStaticImplementationName()
{
    static OUString aImplName;
    static sal_Bool bNeedsInit = sal_True;

    MutexGuard aGuard( Mutex::getGlobalMutex() );
    if( bNeedsInit )
    {
        aImplName = OUString::createFromAscii( "com.sun.star.comp.sfx2.ApplicationScriptLibraryContainer" );
        bNeedsInit = sal_False;
    }
    return aImplName;
}

Reference< XInterface > SAL_CALL SfxApplicationScriptLibraryContainer::impl_createInstance
    ( const Reference< XMultiServiceFactory >& )
        throw( Exception )
{
    SFX_APP()->GetBasicManager();
    Reference< XInterface > xRet =
        Reference< XInterface >( SFX_APP()->GetBasicContainer(), UNO_QUERY );
    return xRet;
}

<commit_msg>INTEGRATION: CWS basmgr02 (1.2.68); FILE MERGED 2007/02/28 12:14:59 fs 1.2.68.6: setStorage: removed unnecessary assertion 2007/02/13 08:26:47 fs 1.2.68.5: #i100000# manual RESYNC: LegacyPasswdBinaryLimitExceeded moved to BasicManager 2007/02/12 09:37:31 fs 1.2.68.4: RESYNC: (1.2-1.3); FILE MERGED 2007/01/17 11:35:26 fs 1.2.68.3: #i73329# document's library containers are created as service, not obtained from the BasicManager 2007/01/11 10:54:05 fs 1.2.68.2: corrected assertion 2007/01/10 14:06:18 fs 1.2.68.1: #i73329# library containers expose a pure UNO API now, in particular XPersistentLibraryContainer<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: appbaslib.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2007-03-15 17:02:10 $
 *
 *  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 APPBASLIB_HXX
#include "appbaslib.hxx"
#endif

#include "sfxuno.hxx"
#include "sfxtypes.hxx"
#include "app.hxx"

#include <basic/basmgr.hxx>
#include <tools/diagnose_ex.h>
#include <comphelper/processfactory.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::script;
using namespace ::com::sun::star::embed;
using ::rtl::OUString;
using ::osl::MutexGuard;
using ::osl::Mutex;

//============================================================================
SfxBasicManagerHolder::SfxBasicManagerHolder()
    :mpBasicManager( NULL )
{
}

void SfxBasicManagerHolder::reset( BasicManager* _pBasicManager )
{
    impl_releaseContainers();

    // Note: we do not delete the old BasicManager. BasicManager instances are
    // nowadays obtained from the BasicManagerRepository, and the ownership is with
    // the repository.
    // @see basic::BasicManagerRepository::getApplicationBasicManager
    // @see basic::BasicManagerRepository::getDocumentBasicManager
    mpBasicManager = _pBasicManager;

    if ( mpBasicManager )
    {
        try
        {
            mxBasicContainer.set( mpBasicManager->GetScriptLibraryContainer(), UNO_QUERY_THROW );
            mxDialogContainer.set( mpBasicManager->GetDialogLibraryContainer(), UNO_QUERY_THROW  );
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION();
        }
    }
}

bool SfxBasicManagerHolder::isAnyContainerModified() const
{
    OSL_PRECOND( isValid(), "SfxBasicManagerHolder::isAnyContainerModified: not initialized!" );

    if ( mxBasicContainer.is() && mxBasicContainer->isModified() )
        return true;
    if ( mxDialogContainer.is() && mxDialogContainer->isModified() )
        return true;

    return false;
}

void SfxBasicManagerHolder::storeAllLibraries()
{
    OSL_PRECOND( isValid(), "SfxBasicManagerHolder::storeAllLibraries: not initialized!" );
    try
    {
        if ( mxBasicContainer.is() )
            mxBasicContainer->storeLibraries();
        if ( mxDialogContainer.is() )
            mxDialogContainer->storeLibraries();
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION();
    }
}

void SfxBasicManagerHolder::setStorage( const Reference< XStorage >& _rxStorage )
{
    try
    {
        if ( mxBasicContainer.is() )
            mxBasicContainer->setRootStorage( _rxStorage );
        if ( mxDialogContainer.is() )
            mxDialogContainer->setRootStorage( _rxStorage );
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION();
    }
}

void SfxBasicManagerHolder::storeLibrariesToStorage( const Reference< XStorage >& _rxStorage )
{
    OSL_PRECOND( isValid(), "SfxBasicManagerHolder::storeLibrariesToStorage: not initialized!" );

    try
    {
        if ( mxBasicContainer.is() )
            mxBasicContainer->storeLibrariesToStorage( _rxStorage );
        if ( mxDialogContainer.is() )
            mxDialogContainer->storeLibrariesToStorage( _rxStorage );
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION();
    }
}

Reference< XLibraryContainer > SfxBasicManagerHolder::getLibraryContainer( ContainerType _eType )
{
    OSL_PRECOND( isValid(), "SfxBasicManagerHolder::getLibraryContainer: not initialized!" );

    switch ( _eType )
    {
    case SCRIPTS:   return mxBasicContainer.get();
    case DIALOGS:   return mxDialogContainer.get();
    }
    DBG_ERROR( "SfxBasicManagerHolder::getLibraryContainer: illegal container type!" );
    return NULL;
}

void SfxBasicManagerHolder::impl_releaseContainers()
{
    mxBasicContainer.clear();
    mxDialogContainer.clear();
}

sal_Bool
SfxBasicManagerHolder::LegacyPsswdBinaryLimitExceeded( Sequence< rtl::OUString >& sModules )
{
    if ( mpBasicManager )
        return mpBasicManager->LegacyPsswdBinaryLimitExceeded( sModules );
    return sal_True;
}

//============================================================================
// Service for application library container
SFX_IMPL_ONEINSTANCEFACTORY( SfxApplicationDialogLibraryContainer )

Sequence< OUString > SfxApplicationDialogLibraryContainer::impl_getStaticSupportedServiceNames()
{
    static Sequence< OUString > seqServiceNames( 1 );
    static sal_Bool bNeedsInit = sal_True;

    MutexGuard aGuard( Mutex::getGlobalMutex() );
    if( bNeedsInit )
    {
        OUString* pSeq = seqServiceNames.getArray();
        pSeq[0] = OUString::createFromAscii( "com.sun.star.script.ApplicationDialogLibraryContainer" );
        bNeedsInit = sal_False;
    }
    return seqServiceNames;
}

OUString SfxApplicationDialogLibraryContainer::impl_getStaticImplementationName()
{
    static OUString aImplName;
    static sal_Bool bNeedsInit = sal_True;

    MutexGuard aGuard( Mutex::getGlobalMutex() );
    if( bNeedsInit )
    {
        aImplName = OUString::createFromAscii( "com.sun.star.comp.sfx2.ApplicationDialogLibraryContainer" );
        bNeedsInit = sal_False;
    }
    return aImplName;
}

Reference< XInterface > SAL_CALL SfxApplicationDialogLibraryContainer::impl_createInstance
    ( const Reference< XMultiServiceFactory >& )
        throw( Exception )
{
    SFX_APP()->GetBasicManager();
    Reference< XInterface > xRet =
        Reference< XInterface >( SFX_APP()->GetDialogContainer(), UNO_QUERY );
    return xRet;
}

//============================================================================
// Service for application library container
SFX_IMPL_ONEINSTANCEFACTORY( SfxApplicationScriptLibraryContainer )

Sequence< OUString > SfxApplicationScriptLibraryContainer::impl_getStaticSupportedServiceNames()
{
    static Sequence< OUString > seqServiceNames( 1 );
    static sal_Bool bNeedsInit = sal_True;

    MutexGuard aGuard( Mutex::getGlobalMutex() );
    if( bNeedsInit )
    {
        OUString* pSeq = seqServiceNames.getArray();
        pSeq[0] = OUString::createFromAscii( "com.sun.star.script.ApplicationScriptLibraryContainer" );
        bNeedsInit = sal_False;
    }
    return seqServiceNames;
}

OUString SfxApplicationScriptLibraryContainer::impl_getStaticImplementationName()
{
    static OUString aImplName;
    static sal_Bool bNeedsInit = sal_True;

    MutexGuard aGuard( Mutex::getGlobalMutex() );
    if( bNeedsInit )
    {
        aImplName = OUString::createFromAscii( "com.sun.star.comp.sfx2.ApplicationScriptLibraryContainer" );
        bNeedsInit = sal_False;
    }
    return aImplName;
}

Reference< XInterface > SAL_CALL SfxApplicationScriptLibraryContainer::impl_createInstance
    ( const Reference< XMultiServiceFactory >& )
        throw( Exception )
{
    SFX_APP()->GetBasicManager();
    Reference< XInterface > xRet =
        Reference< XInterface >( SFX_APP()->GetBasicContainer(), UNO_QUERY );
    return xRet;
}

<|endoftext|>


<commit_before><commit_msg>infobar: combine anon. namespace, light/dark color to constant<commit_after><|endoftext|>