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

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

#include "SlsHideSlideFunction.hxx"

#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "view/SlideSorterView.hxx"

#include "app.hrc"
#include "drawdoc.hxx"
#include "sdpage.hxx"

#include <sfx2/viewfrm.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/request.hxx>
#include <svx/svxids.hrc>

namespace sd { namespace slidesorter { namespace controller {

TYPEINIT1(HideSlideFunction, SlideFunction);

HideSlideFunction::HideSlideFunction (
    SlideSorterController& rController,
    SfxRequest& rRequest)
    : SlideFunction( rController, rRequest),
      mrController(rController)
{
}

HideSlideFunction::~HideSlideFunction (void)
{
}

FunctionReference HideSlideFunction::Create (
    SlideSorterController& rController,
    SfxRequest& rRequest )
{
    FunctionReference xFunc( new HideSlideFunction( rController, rRequest ) );
    xFunc->DoExecute(rRequest);
    return xFunc;
}

void HideSlideFunction::DoExecute (SfxRequest& rRequest)
{
    SlideFunction::DoExecute(rRequest);

    model::SlideSorterModel::Enumeration aSelectedPages (
        mrController.GetModel().GetSelectedPagesEnumeration());

    ExclusionState eState (UNDEFINED);

    switch (rRequest.GetSlot())
    {
        case SID_HIDE_SLIDE:
            eState = EXCLUDED;
            break;

        case SID_SHOW_SLIDE:
            eState = INCLUDED;
            break;

        default:
            eState = UNDEFINED;
            break;
    }

    if (eState != UNDEFINED)
    {
        // Set status at the selected pages.
        aSelectedPages.Rewind ();
        while (aSelectedPages.HasMoreElements())
        {
            model::SharedPageDescriptor pDescriptor (aSelectedPages.GetNextElement());
            pDescriptor->GetPage()->SetExcluded (eState==EXCLUDED);
            static_cast<view::SlideSorterView*>(pView)->RequestRepaint(pDescriptor);
        }
    }

    SfxBindings& rBindings = pViewShell->GetViewFrame()->GetBindings();
    rBindings.Invalidate (SID_PRESENTATION);
    rBindings.Invalidate (SID_REHEARSE_TIMINGS);
    rBindings.Invalidate (SID_HIDE_SLIDE);
    rBindings.Invalidate (SID_SHOW_SLIDE);
    pDoc->SetChanged();
}

HideSlideFunction::ExclusionState HideSlideFunction::GetExclusionState (
    model::SlideSorterModel::Enumeration& rPageSet)
{
    ExclusionState eState (UNDEFINED);
    BOOL bState;

    // Get toggle state of the selected pages.
    while (rPageSet.HasMoreElements() && eState!=MIXED)
    {
        bState = rPageSet.GetNextElement()->GetPage()->IsExcluded();
        switch (eState)
        {
            case UNDEFINED:
                // Use the first selected page to set the inital value.
                eState = bState ? EXCLUDED : INCLUDED;
                break;

            case EXCLUDED:
                // The pages before where all not part of the show,
                // this one is.
                if ( ! bState)
                    eState = MIXED;
                break;

            case INCLUDED:
                // The pages before where all part of the show,
                // this one is not.
                if (bState)
                    eState = MIXED;
                break;

            case MIXED:
            default:
                // No need to change anything.
                break;
        }
    }

    return eState;
}

} } } // end of namespace ::sd::slidesorter::controller
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.6.38); FILE MERGED 2006/11/22 12:42:11 cl 1.6.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsHideSlideFunction.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-14 10:45:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "SlsHideSlideFunction.hxx"

#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "view/SlideSorterView.hxx"

#include "app.hrc"
#include "drawdoc.hxx"
#include "sdpage.hxx"

#include <sfx2/viewfrm.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/request.hxx>
#include <svx/svxids.hrc>

namespace sd { namespace slidesorter { namespace controller {

TYPEINIT1(HideSlideFunction, SlideFunction);

HideSlideFunction::HideSlideFunction (
    SlideSorterController& rController,
    SfxRequest& rRequest)
    : SlideFunction( rController, rRequest),
      mrController(rController)
{
}

HideSlideFunction::~HideSlideFunction (void)
{
}

FunctionReference HideSlideFunction::Create (
    SlideSorterController& rController,
    SfxRequest& rRequest )
{
    FunctionReference xFunc( new HideSlideFunction( rController, rRequest ) );
    xFunc->DoExecute(rRequest);
    return xFunc;
}

void HideSlideFunction::DoExecute (SfxRequest& rRequest)
{
    SlideFunction::DoExecute(rRequest);

    model::SlideSorterModel::Enumeration aSelectedPages (
        mrController.GetModel().GetSelectedPagesEnumeration());

    ExclusionState eState (UNDEFINED);

    switch (rRequest.GetSlot())
    {
        case SID_HIDE_SLIDE:
            eState = EXCLUDED;
            break;

        case SID_SHOW_SLIDE:
            eState = INCLUDED;
            break;

        default:
            eState = UNDEFINED;
            break;
    }

    if (eState != UNDEFINED)
    {
        // Set status at the selected pages.
        aSelectedPages.Rewind ();
        while (aSelectedPages.HasMoreElements())
        {
            model::SharedPageDescriptor pDescriptor (aSelectedPages.GetNextElement());
            pDescriptor->GetPage()->SetExcluded (eState==EXCLUDED);
            static_cast<view::SlideSorterView*>(mpView)->RequestRepaint(pDescriptor);
        }
    }

    SfxBindings& rBindings = mpViewShell->GetViewFrame()->GetBindings();
    rBindings.Invalidate (SID_PRESENTATION);
    rBindings.Invalidate (SID_REHEARSE_TIMINGS);
    rBindings.Invalidate (SID_HIDE_SLIDE);
    rBindings.Invalidate (SID_SHOW_SLIDE);
    mpDoc->SetChanged();
}

HideSlideFunction::ExclusionState HideSlideFunction::GetExclusionState (
    model::SlideSorterModel::Enumeration& rPageSet)
{
    ExclusionState eState (UNDEFINED);
    BOOL bState;

    // Get toggle state of the selected pages.
    while (rPageSet.HasMoreElements() && eState!=MIXED)
    {
        bState = rPageSet.GetNextElement()->GetPage()->IsExcluded();
        switch (eState)
        {
            case UNDEFINED:
                // Use the first selected page to set the inital value.
                eState = bState ? EXCLUDED : INCLUDED;
                break;

            case EXCLUDED:
                // The pages before where all not part of the show,
                // this one is.
                if ( ! bState)
                    eState = MIXED;
                break;

            case INCLUDED:
                // The pages before where all part of the show,
                // this one is not.
                if (bState)
                    eState = MIXED;
                break;

            case MIXED:
            default:
                // No need to change anything.
                break;
        }
    }

    return eState;
}

} } } // end of namespace ::sd::slidesorter::controller
<|endoftext|>


<commit_before>/**
 * This file is part of TelepathyQt4
 *
 * @copyright Copyright (C) 2009-2010 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2009-2010 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/PendingVariantMap>

#include "TelepathyQt4/_gen/pending-variant-map.moc.hpp"
#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/Global>

#include <QDBusPendingReply>

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT PendingVariantMap::Private
{
    QVariantMap result;
};

/**
 * \class PendingVariantMap
 * \ingroup utils
 * \headerfile TelepathyQt4/pending-variant-map.h <TelepathyQt4/PendingVariantMap>
 *
 * \brief The PendingVariantMap class is a generic subclass of PendingOperation
 * representing a pending D-Bus method call that returns a variant map.
 */

PendingVariantMap::PendingVariantMap(QDBusPendingCall call, const SharedPtr<RefCounted> &object)
    : PendingOperation(object),
      mPriv(new Private)
{
    connect(new QDBusPendingCallWatcher(call),
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            this,
            SLOT(watcherFinished(QDBusPendingCallWatcher*)));
}

/**
 * Class destructor.
 */
PendingVariantMap::~PendingVariantMap()
{
    delete mPriv;
}

QVariantMap PendingVariantMap::result() const
{
    return mPriv->result;
}

void PendingVariantMap::watcherFinished(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QVariantMap> reply = *watcher;

    if (!reply.isError()) {
        debug() << "Got reply to PendingVariantMap call";
        mPriv->result = reply.value();
        setFinished();
    } else {
        debug().nospace() << "PendingVariantMap call failed: " <<
            reply.error().name() << ": " << reply.error().message();
        setFinishedWithError(reply.error());
    }

    watcher->deleteLater();
}

} // Tp
<commit_msg>PendingVariantMap: Update docs.<commit_after>/**
 * This file is part of TelepathyQt4
 *
 * @copyright Copyright (C) 2009-2010 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2009-2010 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/PendingVariantMap>

#include "TelepathyQt4/_gen/pending-variant-map.moc.hpp"
#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/Global>

#include <QDBusPendingReply>

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT PendingVariantMap::Private
{
    QVariantMap result;
};

/**
 * \class PendingVariantMap
 * \ingroup utils
 * \headerfile TelepathyQt4/pending-variant-map.h <TelepathyQt4/PendingVariantMap>
 *
 * \brief The PendingVariantMap class is a generic subclass of PendingOperation
 * representing a pending D-Bus method call that returns a variant map.
 *
 * See \ref async_model
 */

PendingVariantMap::PendingVariantMap(QDBusPendingCall call, const SharedPtr<RefCounted> &object)
    : PendingOperation(object),
      mPriv(new Private)
{
    connect(new QDBusPendingCallWatcher(call),
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            this,
            SLOT(watcherFinished(QDBusPendingCallWatcher*)));
}

/**
 * Class destructor.
 */
PendingVariantMap::~PendingVariantMap()
{
    delete mPriv;
}

QVariantMap PendingVariantMap::result() const
{
    return mPriv->result;
}

void PendingVariantMap::watcherFinished(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QVariantMap> reply = *watcher;

    if (!reply.isError()) {
        debug() << "Got reply to PendingVariantMap call";
        mPriv->result = reply.value();
        setFinished();
    } else {
        debug().nospace() << "PendingVariantMap call failed: " <<
            reply.error().name() << ": " << reply.error().message();
        setFinishedWithError(reply.error());
    }

    watcher->deleteLater();
}

} // Tp
<|endoftext|>


<commit_before>#ifndef _TCUANDROIDINTERNALS_HPP
#define _TCUANDROIDINTERNALS_HPP
/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief Access to Android internals that are not a part of the NDK.
 *//*--------------------------------------------------------------------*/

#include "tcuDefs.hpp"

#include "deDynamicLibrary.hpp"

#include <vector>
#include <errno.h>

struct ANativeWindowBuffer;

namespace android
{
class GraphicBuffer;
class android_native_base_t;
}

namespace tcu
{

namespace Android
{

// These classes and enums reflect internal android definitions
namespace internal
{

// utils/Errors.h
enum
{
	OK					= 0,
	UNKNOWN_ERROR		= (-2147483647-1),
	NO_MEMORY			= -ENOMEM,
	INVALID_OPERATION	= -ENOSYS,
	BAD_VALUE			= -EINVAL,
	BAD_TYPE			= (UNKNOWN_ERROR + 1),
	NAME_NOT_FOUND		= -ENOENT,
	PERMISSION_DENIED	= -EPERM,
	NO_INIT				= -ENODEV,
	ALREADY_EXISTS		= -EEXIST,
	DEAD_OBJECT			= -EPIPE,
	FAILED_TRANSACTION	= (UNKNOWN_ERROR + 2),
	JPARKS_BROKE_IT		= -EPIPE,
	BAD_INDEX			= -E2BIG,
	NOT_ENOUGH_DATA		= (UNKNOWN_ERROR + 3),
	WOULD_BLOCK			= (UNKNOWN_ERROR + 4),
	TIMED_OUT			= (UNKNOWN_ERROR + 5),
	UNKNOWN_TRANSACTION = (UNKNOWN_ERROR + 6),
	FDS_NOT_ALLOWED		= (UNKNOWN_ERROR + 7),
};

typedef deInt32 status_t;

// ui/PixelFormat.h, system/graphics.h
enum
{
	PIXEL_FORMAT_UNKNOWN				= 0,
	PIXEL_FORMAT_NONE					= 0,
	PIXEL_FORMAT_CUSTOM					= -4,
	PIXEL_FORMAT_TRANSLUCENT			= -3,
	PIXEL_FORMAT_TRANSPARENT			= -2,
	PIXEL_FORMAT_OPAQUE					= -1,
	PIXEL_FORMAT_RGBA_8888				= 1,
	PIXEL_FORMAT_RGBX_8888				= 2,
	PIXEL_FORMAT_RGB_888				= 3,
	PIXEL_FORMAT_RGB_565				= 4,
	PIXEL_FORMAT_BGRA_8888				= 5,
	PIXEL_FORMAT_RGBA_5551				= 6,
	PIXEL_FORMAT_RGBA_4444				= 7,
};

typedef deInt32 PixelFormat;

// ui/GraphicBuffer.h
struct GraphicBufferFunctions
{
	typedef void					(*genericFunc)			();
	typedef status_t				(*initCheckFunc)		(android::GraphicBuffer* buffer);
	typedef status_t				(*lockFunc)				(android::GraphicBuffer* buffer, deUint32 usage, void** vaddr);
	typedef status_t				(*unlockFunc)			(android::GraphicBuffer* buffer);
	typedef ANativeWindowBuffer*	(*getNativeBufferFunc)	(const android::GraphicBuffer* buffer);

	genericFunc						constructor;
	genericFunc						destructor;
	lockFunc						lock;
	unlockFunc						unlock;
	getNativeBufferFunc				getNativeBuffer;
	initCheckFunc					initCheck;
};

// system/window.h
struct NativeBaseFunctions
{
	typedef void	(*incRefFunc)			(android::android_native_base_t* base);
	typedef void	(*decRefFunc)			(android::android_native_base_t* base);

	incRefFunc		incRef;
	decRefFunc		decRef;
};

struct LibUIFunctions
{
	GraphicBufferFunctions graphicBuffer;
};

class LibUI
{
public:
	struct Functions
	{
		GraphicBufferFunctions graphicBuffer;
	};

							LibUI			(void);
	const Functions&		getFunctions	(void) const { return m_functions; }

private:
	Functions				m_functions;
	de::DynamicLibrary		m_library;
};

class GraphicBuffer
{
public:
	// ui/GraphicBuffer.h, hardware/gralloc.h
	enum {
		USAGE_SW_READ_NEVER		= 0x00000000,
		USAGE_SW_READ_RARELY	= 0x00000002,
		USAGE_SW_READ_OFTEN		= 0x00000003,
		USAGE_SW_READ_MASK		= 0x0000000f,

		USAGE_SW_WRITE_NEVER	= 0x00000000,
		USAGE_SW_WRITE_RARELY	= 0x00000020,
		USAGE_SW_WRITE_OFTEN	= 0x00000030,
		USAGE_SW_WRITE_MASK		= 0x000000f0,

		USAGE_SOFTWARE_MASK		= USAGE_SW_READ_MASK | USAGE_SW_WRITE_MASK,

		USAGE_PROTECTED			= 0x00004000,

		USAGE_HW_TEXTURE		= 0x00000100,
		USAGE_HW_RENDER			= 0x00000200,
		USAGE_HW_2D				= 0x00000400,
		USAGE_HW_COMPOSER		= 0x00000800,
		USAGE_HW_VIDEO_ENCODER	= 0x00010000,
		USAGE_HW_MASK			= 0x00071F00,
	};

									GraphicBuffer			(const LibUI& lib, deUint32 width, deUint32 height, PixelFormat format, deUint32 usage);
									~GraphicBuffer			();

	status_t						lock					(deUint32 usage, void** vaddr);
	status_t						unlock					(void);
	ANativeWindowBuffer*			getNativeBuffer			(void) const;

private:
	const GraphicBufferFunctions&	m_functions;
	NativeBaseFunctions				m_baseFunctions;
	android::GraphicBuffer*			m_impl;
};

} // internal
} // Android
} // tcu

#endif // _TCUANDROIDINTERNALS_HPP
<commit_msg>Stop being silly.<commit_after>#ifndef _TCUANDROIDINTERNALS_HPP
#define _TCUANDROIDINTERNALS_HPP
/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief Access to Android internals that are not a part of the NDK.
 *//*--------------------------------------------------------------------*/

#include "tcuDefs.hpp"

#include "deDynamicLibrary.hpp"

#include <vector>
#include <errno.h>

struct ANativeWindowBuffer;

namespace android
{
class GraphicBuffer;
class android_native_base_t;
}

namespace tcu
{

namespace Android
{

// These classes and enums reflect internal android definitions
namespace internal
{

// utils/Errors.h
enum
{
	OK					= 0,
	UNKNOWN_ERROR		= (-2147483647-1),
	NO_MEMORY			= -ENOMEM,
	INVALID_OPERATION	= -ENOSYS,
	BAD_VALUE			= -EINVAL,
	BAD_TYPE			= (UNKNOWN_ERROR + 1),
	NAME_NOT_FOUND		= -ENOENT,
	PERMISSION_DENIED	= -EPERM,
	NO_INIT				= -ENODEV,
	ALREADY_EXISTS		= -EEXIST,
	DEAD_OBJECT			= -EPIPE,
	FAILED_TRANSACTION	= (UNKNOWN_ERROR + 2),
	BAD_INDEX			= -E2BIG,
	NOT_ENOUGH_DATA		= (UNKNOWN_ERROR + 3),
	WOULD_BLOCK			= (UNKNOWN_ERROR + 4),
	TIMED_OUT			= (UNKNOWN_ERROR + 5),
	UNKNOWN_TRANSACTION = (UNKNOWN_ERROR + 6),
	FDS_NOT_ALLOWED		= (UNKNOWN_ERROR + 7),
};

typedef deInt32 status_t;

// ui/PixelFormat.h, system/graphics.h
enum
{
	PIXEL_FORMAT_UNKNOWN				= 0,
	PIXEL_FORMAT_NONE					= 0,
	PIXEL_FORMAT_CUSTOM					= -4,
	PIXEL_FORMAT_TRANSLUCENT			= -3,
	PIXEL_FORMAT_TRANSPARENT			= -2,
	PIXEL_FORMAT_OPAQUE					= -1,
	PIXEL_FORMAT_RGBA_8888				= 1,
	PIXEL_FORMAT_RGBX_8888				= 2,
	PIXEL_FORMAT_RGB_888				= 3,
	PIXEL_FORMAT_RGB_565				= 4,
	PIXEL_FORMAT_BGRA_8888				= 5,
	PIXEL_FORMAT_RGBA_5551				= 6,
	PIXEL_FORMAT_RGBA_4444				= 7,
};

typedef deInt32 PixelFormat;

// ui/GraphicBuffer.h
struct GraphicBufferFunctions
{
	typedef void					(*genericFunc)			();
	typedef status_t				(*initCheckFunc)		(android::GraphicBuffer* buffer);
	typedef status_t				(*lockFunc)				(android::GraphicBuffer* buffer, deUint32 usage, void** vaddr);
	typedef status_t				(*unlockFunc)			(android::GraphicBuffer* buffer);
	typedef ANativeWindowBuffer*	(*getNativeBufferFunc)	(const android::GraphicBuffer* buffer);

	genericFunc						constructor;
	genericFunc						destructor;
	lockFunc						lock;
	unlockFunc						unlock;
	getNativeBufferFunc				getNativeBuffer;
	initCheckFunc					initCheck;
};

// system/window.h
struct NativeBaseFunctions
{
	typedef void	(*incRefFunc)			(android::android_native_base_t* base);
	typedef void	(*decRefFunc)			(android::android_native_base_t* base);

	incRefFunc		incRef;
	decRefFunc		decRef;
};

struct LibUIFunctions
{
	GraphicBufferFunctions graphicBuffer;
};

class LibUI
{
public:
	struct Functions
	{
		GraphicBufferFunctions graphicBuffer;
	};

							LibUI			(void);
	const Functions&		getFunctions	(void) const { return m_functions; }

private:
	Functions				m_functions;
	de::DynamicLibrary		m_library;
};

class GraphicBuffer
{
public:
	// ui/GraphicBuffer.h, hardware/gralloc.h
	enum {
		USAGE_SW_READ_NEVER		= 0x00000000,
		USAGE_SW_READ_RARELY	= 0x00000002,
		USAGE_SW_READ_OFTEN		= 0x00000003,
		USAGE_SW_READ_MASK		= 0x0000000f,

		USAGE_SW_WRITE_NEVER	= 0x00000000,
		USAGE_SW_WRITE_RARELY	= 0x00000020,
		USAGE_SW_WRITE_OFTEN	= 0x00000030,
		USAGE_SW_WRITE_MASK		= 0x000000f0,

		USAGE_SOFTWARE_MASK		= USAGE_SW_READ_MASK | USAGE_SW_WRITE_MASK,

		USAGE_PROTECTED			= 0x00004000,

		USAGE_HW_TEXTURE		= 0x00000100,
		USAGE_HW_RENDER			= 0x00000200,
		USAGE_HW_2D				= 0x00000400,
		USAGE_HW_COMPOSER		= 0x00000800,
		USAGE_HW_VIDEO_ENCODER	= 0x00010000,
		USAGE_HW_MASK			= 0x00071F00,
	};

									GraphicBuffer			(const LibUI& lib, deUint32 width, deUint32 height, PixelFormat format, deUint32 usage);
									~GraphicBuffer			();

	status_t						lock					(deUint32 usage, void** vaddr);
	status_t						unlock					(void);
	ANativeWindowBuffer*			getNativeBuffer			(void) const;

private:
	const GraphicBufferFunctions&	m_functions;
	NativeBaseFunctions				m_baseFunctions;
	android::GraphicBuffer*			m_impl;
};

} // internal
} // Android
} // tcu

#endif // _TCUANDROIDINTERNALS_HPP
<|endoftext|>


<commit_before>#include "chuck_dl.h"
#include "chuck_def.h"
#include <stdio.h>
#include <limits.h>

extern "C"{
#include "soundpipe.h"
#include "../tmp.h"
}

CK_DLL_CTOR(sporth_ctor);
CK_DLL_DTOR(sporth_dtor);

CK_DLL_MFUN(sporth_setp);
CK_DLL_MFUN(sporth_getp);

CK_DLL_MFUN(sporth_parseString);

CK_DLL_TICK(sporth_tick);

t_CKINT sporth_data_offset = 0;

struct sporthData {
    float var;
    int parsed;
    sp_data *sp;
    plumber_data pd;
};
CK_DLL_QUERY(Sporth)
{
    QUERY->setname(QUERY, "Sporth");

    QUERY->begin_class(QUERY, "Sporth", "UGen");

    QUERY->add_ctor(QUERY, sporth_ctor);
    QUERY->add_dtor(QUERY, sporth_dtor);

    QUERY->add_ugen_func(QUERY, sporth_tick, NULL, 1, 1);

    QUERY->add_mfun(QUERY, sporth_setp, "float", "pset");
    QUERY->add_arg(QUERY, "int", "index");
    QUERY->add_arg(QUERY, "float", "val");

    QUERY->add_mfun(QUERY, sporth_getp, "float", "pget");
    QUERY->add_arg(QUERY, "int", "index");

    QUERY->add_mfun(QUERY, sporth_parseString, "string", "parse");
    QUERY->add_arg(QUERY, "string", "arg");

    sporth_data_offset = QUERY->add_mvar(QUERY, "int", "@sporth_data", false);

    QUERY->end_class(QUERY);

    return TRUE;
}

CK_DLL_CTOR(sporth_ctor)
{
    OBJ_MEMBER_INT(SELF, sporth_data_offset) = 0;

    sporthData * data = new sporthData;
    data->parsed = 0;
    sp_create(&data->sp);
    sp_srand(data->sp, time(NULL));
    data->sp->sr = API->vm->get_srate();
    plumber_register(&data->pd);
    plumber_init(&data->pd);
    data->pd.sp = data->sp;

    OBJ_MEMBER_INT(SELF, sporth_data_offset) = (t_CKINT) data;
}

CK_DLL_DTOR(sporth_dtor)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    if(data)
    {
        plumber_clean(&data->pd);
        sp_destroy(&data->sp);

        delete data;
        OBJ_MEMBER_INT(SELF, sporth_data_offset) = 0;
        data = NULL;
    }
}

CK_DLL_TICK(sporth_tick)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    plumber_compute(&data->pd, PLUMBER_COMPUTE);
    *out = sporth_stack_pop_float(&data->pd.sporth.stack);
    return TRUE;
}

CK_DLL_MFUN(sporth_setp)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    int i = GET_NEXT_INT(ARGS);
    float val = GET_NEXT_FLOAT(ARGS);
    data->pd.p[i] = val;
    RETURN->v_float = val;
}

CK_DLL_MFUN(sporth_getp)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    int i = GET_NEXT_INT(ARGS);
    RETURN->v_float = data->pd.p[i];
}

CK_DLL_MFUN(sporth_parseString)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    Chuck_String * ckstring = GET_CK_STRING(ARGS);
    const char * cstr = ckstring->str.c_str();
    char *str = (char *)malloc(strlen(cstr) + 1);
    str = strdup(cstr);
    if(!data->parsed) {
        data->parsed = 1;
        plumber_parse_string(&data->pd, str);
        plumber_compute(&data->pd, PLUMBER_INIT);
    }
    free(str);
    RETURN->v_float = data->var;
}

<commit_msg>updated chorth to have randomization<commit_after>#include "chuck_dl.h"
#include "chuck_def.h"
#include <stdio.h>
#include <limits.h>

extern "C"{
#include "soundpipe.h"
#include "../tmp.h"
}

CK_DLL_CTOR(sporth_ctor);
CK_DLL_DTOR(sporth_dtor);

CK_DLL_MFUN(sporth_setp);
CK_DLL_MFUN(sporth_getp);

CK_DLL_MFUN(sporth_parseString);

CK_DLL_TICK(sporth_tick);

t_CKINT sporth_data_offset = 0;

struct sporthData {
    float var;
    int parsed;
    sp_data *sp;
    plumber_data pd;
};
CK_DLL_QUERY(Sporth)
{
    QUERY->setname(QUERY, "Sporth");

    QUERY->begin_class(QUERY, "Sporth", "UGen");

    QUERY->add_ctor(QUERY, sporth_ctor);
    QUERY->add_dtor(QUERY, sporth_dtor);

    QUERY->add_ugen_func(QUERY, sporth_tick, NULL, 1, 1);

    QUERY->add_mfun(QUERY, sporth_setp, "float", "pset");
    QUERY->add_arg(QUERY, "int", "index");
    QUERY->add_arg(QUERY, "float", "val");

    QUERY->add_mfun(QUERY, sporth_getp, "float", "pget");
    QUERY->add_arg(QUERY, "int", "index");

    QUERY->add_mfun(QUERY, sporth_parseString, "string", "parse");
    QUERY->add_arg(QUERY, "string", "arg");

    sporth_data_offset = QUERY->add_mvar(QUERY, "int", "@sporth_data", false);

    QUERY->end_class(QUERY);

    return TRUE;
}

CK_DLL_CTOR(sporth_ctor)
{
    OBJ_MEMBER_INT(SELF, sporth_data_offset) = 0;

    sporthData * data = new sporthData;
    data->parsed = 0;
    sp_create(&data->sp);
    sp_srand(data->sp, rand());
    data->sp->sr = API->vm->get_srate();
    plumber_register(&data->pd);
    plumber_init(&data->pd);
    data->pd.sp = data->sp;

    OBJ_MEMBER_INT(SELF, sporth_data_offset) = (t_CKINT) data;
}

CK_DLL_DTOR(sporth_dtor)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    if(data)
    {
        plumber_clean(&data->pd);
        sp_destroy(&data->sp);

        delete data;
        OBJ_MEMBER_INT(SELF, sporth_data_offset) = 0;
        data = NULL;
    }
}

CK_DLL_TICK(sporth_tick)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    plumber_compute(&data->pd, PLUMBER_COMPUTE);
    *out = sporth_stack_pop_float(&data->pd.sporth.stack);
    return TRUE;
}

CK_DLL_MFUN(sporth_setp)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    int i = GET_NEXT_INT(ARGS);
    float val = GET_NEXT_FLOAT(ARGS);
    data->pd.p[i] = val;
    RETURN->v_float = val;
}

CK_DLL_MFUN(sporth_getp)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    int i = GET_NEXT_INT(ARGS);
    RETURN->v_float = data->pd.p[i];
}

CK_DLL_MFUN(sporth_parseString)
{
    sporthData * data = (sporthData *) OBJ_MEMBER_INT(SELF, sporth_data_offset);
    Chuck_String * ckstring = GET_CK_STRING(ARGS);
    const char * cstr = ckstring->str.c_str();
    char *str = (char *)malloc(strlen(cstr) + 1);
    str = strdup(cstr);
    if(!data->parsed) {
        data->parsed = 1;
        plumber_parse_string(&data->pd, str);
        plumber_compute(&data->pd, PLUMBER_INIT);
    }
    free(str);
    RETURN->v_float = data->var;
}

<|endoftext|>


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

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

#include "ClientRegister.h"
#include "SyncThread.h"
#include "sync/ILoginListener.h"
#include "common/RhoConf.h"
#include "common/RhodesApp.h"
#include "System.h"
#include "Push.h"

rho::String rho_sysimpl_get_phone_id();

namespace rho{
namespace sync{

using namespace rho::common;
using namespace rho::db;

static const int THREAD_WAIT_TIMEOUT = 10;

IMPLEMENT_LOGCLASS(CClientRegister,"ClientRegister");

CClientRegister* CClientRegister::m_pInstance = 0;
bool CClientRegister::s_sslVerifyPeer = true;
VectorPtr<ILoginListener*> CClientRegister::s_loginListeners;

/*static*/ CClientRegister* CClientRegister::Get()
{
    if (!m_pInstance)
    {
        m_pInstance = new CClientRegister();
    }
    return m_pInstance;
}

/*static*/ CClientRegister* CClientRegister::Create()
{
    LOG(TRACE) + "Starting ClientRegister";
    Get()->startUp();
    return m_pInstance;
}

/*static*/ CClientRegister* CClientRegister::Create(const String& devicePin)
{
    Get()->setDevicehPin(devicePin);
    return m_pInstance;
}

/*static*/ void CClientRegister::Stop()
{
    if(m_pInstance)
    {
        m_pInstance->doStop();
    }
}

/*static*/ void CClientRegister::Destroy()
{
    if ( m_pInstance )
        delete m_pInstance;

    m_pInstance = 0;
}

/*static*/ void CClientRegister::SetSslVerifyPeer(boolean b)
{
    s_sslVerifyPeer = b;
    if (m_pInstance)
        m_pInstance->m_NetRequest.setSslVerifyPeer(b);
}

bool CClientRegister::GetSslVerifyPeer()
{
    return s_sslVerifyPeer;
}

/*static*/void CClientRegister::AddLoginListener(ILoginListener* listener)
{
    s_loginListeners.addElement(listener);
}

CClientRegister::CClientRegister() : m_nPollInterval(POLL_INTERVAL_SECONDS), m_state(stRegister)
{
    m_NetRequest.setSslVerifyPeer(s_sslVerifyPeer);
}

CClientRegister::~CClientRegister()
{
    doStop();
    m_pInstance = null;
}
void CClientRegister::setRhoconnectCredentials(const String& user, const String& pass, const String& session)
{
    LOG(INFO) + "New Sync credentials - user: " + user + ", sess: " + session;

    setState(stRegister);

    notifyLoggedIn(user,pass,session);

    startUp();
}

void CClientRegister::dropRhoconnectCredentials(const String& session,const String& clientID)
{
    LOG(INFO) + "Dropping credentials - sess: " + session;

    setState(stUnregister);

    m_unregisterSession = session;
    m_unregisterClientID = clientID;

    notifyLoggedOut(session);

    startUp();
}

void CClientRegister::notifyLoggedIn(const String& user, const String& pass, const String& session)
{
    for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I)
    {
        (*I)->onLogin(user, pass, session);
    }
}

void CClientRegister::notifyLoggedOut(const String& session)
{
    for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I)
    {
        (*I)->onLogout(session);
    }
}

void CClientRegister::setDevicehPin(const String& pin)
{
    m_strDevicePin = pin;

    if (pin.length() > 0)
    {
        startUp();
    } else
    {
        doStop();
    }
}

void CClientRegister::startUp()
{
    if ( RHOCONF().getString("syncserver").length() > 0 )
    {
        LOG(INFO) + "Starting ClientRegister...";

        start(epLow);
        stopWait();
    }
}

void CClientRegister::run()
{
    unsigned i = 0;
    LOG(INFO)+"ClientRegister is started";
	while(!isStopping())
	{
        i++;
        LOG(INFO)+"Try to (un)register: " + i;
        if ( CSyncThread::getInstance() != null )
		{
            EnState state = getState();
			if ( (stRegister==state) && doRegister(CSyncThread::getSyncEngine()) )
			{
			    LOG(INFO)+"Registered: " + i;
				break;
			} else if  ( (stUnregister==state) && doUnregister(CSyncThread::getSyncEngine()) ) {
                LOG(INFO)+"Unregistered: " + i;
				break;
            }
		} else
		    LOG(INFO)+"SyncThread is not ready";

		LOG(INFO)+"Waiting for "+ m_nPollInterval+ " sec to try again to register client";
		wait(m_nPollInterval*1000);
	}
    LOG(INFO)+"ClientRegister thread shutdown";
}

String CClientRegister::getRegisterBody(const String& strClientID)
{
    String strPushType = rho::push::CPushManager::getInstance()->getDefaultID();
    if(strPushType == "rhoconnect")
    {
        strPushType = "rhoconnect_push";
    }

    int port = RHOCONF().getInt("push_port");

    String appId = RHOCONF().getString("rho_app_id");
    String appVer = RHOCONF().getString("app_version");

	String body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin,
		port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho::System::getPhoneId(),
		                strPushType, appId, appVer);

	LOG(INFO)+"getRegisterBody() BODY is: " + body;
	return body;
}

String CClientRegister::getUnregisterBody(const String& strClientID)
{
	String body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, "", 0, "", "", "", "", "" );
	LOG(INFO)+"getUnregisterBody() BODY is: " + body;
	return body;
}

boolean CClientRegister::doRegister(CSyncEngine& oSync)
{
    String session = oSync.loadSession();
    if ( session.length() == 0 )
    {
        m_nPollInterval = POLL_INTERVAL_INFINITE;
        LOG(INFO)+"Session is empty, do register later";
        return false;
    }

    if ( m_strDevicePin.length() == 0 )
    {
        notifyLoggedIn("","",session);
        m_nPollInterval = POLL_INTERVAL_INFINITE;
        LOG(INFO)+"Device PUSH pin is empty, do register later";
        return false;
    }
    m_nPollInterval = POLL_INTERVAL_SECONDS;

	String client_id = oSync.loadClientID();
	if ( client_id.length() == 0 )
	{
        LOG(WARNING)+"Sync client_id is empty, do register later";
		return false;
	}

    IDBResult res = CDBAdapter::getUserDB().executeSQL("SELECT token,token_sent from client_info");
    if ( !res.isEnd() ) {
		String token = res.getStringByIdx(0);
		int token_sent = res.getIntByIdx(1) && !RHOCONF().getBool("register_push_at_startup");

		if ( m_strDevicePin.compare(token) == 0 && token_sent > 0 )
		{
			//token in db same as new one and it was already send to the server
			//so we do nothing

			return true;
		}
    }

	String strBody = getRegisterBody(client_id);
    NetResponse resp = getNet().pushData( oSync.getProtocol().getClientRegisterUrl(client_id), strBody, &oSync );
	if( resp.isOK() )
    {
        CDBAdapter::getUserDB().executeSQL("UPDATE client_info SET token_sent=?, token=?", 1, m_strDevicePin );
		LOG(INFO)+"Registered client sucessfully...";

        return true;

    }

	LOG(WARNING)+"Network error: "+ resp.getRespCode();
	return false;
}

boolean CClientRegister::doUnregister(CSyncEngine& oSync)
{
    String session = m_unregisterSession;
    if ( session.length() == 0 )
    {
        m_unregisterSession = "";
        m_unregisterClientID = "";

        LOG(INFO)+"Session is empty, don't need to unregister";
        return true;
    }

    m_nPollInterval = POLL_INTERVAL_SECONDS;

	String client_id = m_unregisterClientID;
	if ( client_id.length() == 0 )
	{
        m_unregisterSession = "";
        m_unregisterClientID = "";

        LOG(WARNING)+"Sync client_id is empty, don't need to unregister";
		return true;
	}

    String strBody = getUnregisterBody(client_id);
    LOG(INFO)+"Unregistered client with body = " + strBody;

    class UnregisterSession : public net::IRhoSession {
        String m_session;
        String m_contentType;
    public:
        UnregisterSession(const String& session, const String& contentType) : m_session(session), m_contentType(contentType) {}
      	virtual void logout() {}
        virtual const String& getSession() {
            return m_session;
        }
        virtual const String& getContentType() {
            return m_contentType;
        }
    };

    UnregisterSession unregSession(session, oSync.getProtocol().getContentType() );

    NetResponse resp = getNet().pushData( oSync.getProtocol().getClientRegisterUrl(client_id), strBody, &unregSession );
	if( resp.isOK() )
    {
        m_unregisterSession = "";
        m_unregisterClientID = "";

        CDBAdapter::getUserDB().executeSQL("UPDATE client_info SET token_sent=?", 0 );
		LOG(INFO)+"Unregistered client sucessfully...";

        return true;

    }

	LOG(WARNING)+"Network error: "+ resp.getRespCode();
	return false;
}

void CClientRegister::setState( EnState st ) {
    synchronized(m_mxStateAccess)
    {
        m_state = st;
    }
}

CClientRegister::EnState CClientRegister::getState() {
    EnState state = stRegister;
    synchronized(m_mxStateAccess)
    {
        state = m_state;
    }

    return state;
}

void CClientRegister::doStop()
{
    LOG(INFO) + "Stopping ClientRegister...";

    m_NetRequest.cancel();
    stop(WAIT_BEFOREKILL_SECONDS);
}

}
}
<commit_msg>fix deadlcok when sync and push register at same time<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com

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

#include "ClientRegister.h"
#include "SyncThread.h"
#include "sync/ILoginListener.h"
#include "common/RhoConf.h"
#include "common/RhodesApp.h"
#include "System.h"
#include "Push.h"

rho::String rho_sysimpl_get_phone_id();

namespace rho{
namespace sync{

using namespace rho::common;
using namespace rho::db;

static const int THREAD_WAIT_TIMEOUT = 10;

IMPLEMENT_LOGCLASS(CClientRegister,"ClientRegister");

CClientRegister* CClientRegister::m_pInstance = 0;
bool CClientRegister::s_sslVerifyPeer = true;
VectorPtr<ILoginListener*> CClientRegister::s_loginListeners;

/*static*/ CClientRegister* CClientRegister::Get()
{
    if (!m_pInstance)
    {
        m_pInstance = new CClientRegister();
    }
    return m_pInstance;
}

/*static*/ CClientRegister* CClientRegister::Create()
{
    LOG(TRACE) + "Starting ClientRegister";
    Get()->startUp();
    return m_pInstance;
}

/*static*/ CClientRegister* CClientRegister::Create(const String& devicePin)
{
    Get()->setDevicehPin(devicePin);
    return m_pInstance;
}

/*static*/ void CClientRegister::Stop()
{
    if(m_pInstance)
    {
        m_pInstance->doStop();
    }
}

/*static*/ void CClientRegister::Destroy()
{
    if ( m_pInstance )
        delete m_pInstance;

    m_pInstance = 0;
}

/*static*/ void CClientRegister::SetSslVerifyPeer(boolean b)
{
    s_sslVerifyPeer = b;
    if (m_pInstance)
        m_pInstance->m_NetRequest.setSslVerifyPeer(b);
}

bool CClientRegister::GetSslVerifyPeer()
{
    return s_sslVerifyPeer;
}

/*static*/void CClientRegister::AddLoginListener(ILoginListener* listener)
{
    s_loginListeners.addElement(listener);
}

CClientRegister::CClientRegister() : m_nPollInterval(POLL_INTERVAL_SECONDS), m_state(stRegister)
{
    m_NetRequest.setSslVerifyPeer(s_sslVerifyPeer);
}

CClientRegister::~CClientRegister()
{
    doStop();
    m_pInstance = null;
}
void CClientRegister::setRhoconnectCredentials(const String& user, const String& pass, const String& session)
{
    LOG(INFO) + "New Sync credentials - user: " + user + ", sess: " + session;

    setState(stRegister);

    notifyLoggedIn(user,pass,session);

    startUp();
}

void CClientRegister::dropRhoconnectCredentials(const String& session,const String& clientID)
{
    LOG(INFO) + "Dropping credentials - sess: " + session;

    setState(stUnregister);

    m_unregisterSession = session;
    m_unregisterClientID = clientID;

    notifyLoggedOut(session);

    startUp();
}

void CClientRegister::notifyLoggedIn(const String& user, const String& pass, const String& session)
{
    for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I)
    {
        (*I)->onLogin(user, pass, session);
    }
}

void CClientRegister::notifyLoggedOut(const String& session)
{
    for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I)
    {
        (*I)->onLogout(session);
    }
}

void CClientRegister::setDevicehPin(const String& pin)
{
    m_strDevicePin = pin;

    if (pin.length() > 0)
    {
        startUp();
    } else
    {
        doStop();
    }
}

void CClientRegister::startUp()
{
    if ( RHOCONF().getString("syncserver").length() > 0 )
    {
        LOG(INFO) + "Starting ClientRegister...";

        start(epLow);
        stopWait();
    }
}

void CClientRegister::run()
{
    unsigned i = 0;
    LOG(INFO)+"ClientRegister is started";
	while(!isStopping())
	{
        i++;
        LOG(INFO)+"Try to (un)register: " + i;
        if ( CSyncThread::getInstance() != null )
		{
            EnState state = getState();
			if ( (stRegister==state) && doRegister(CSyncThread::getSyncEngine()) )
			{
			    LOG(INFO)+"Registered: " + i;
				break;
			} else if  ( (stUnregister==state) && doUnregister(CSyncThread::getSyncEngine()) ) {
                LOG(INFO)+"Unregistered: " + i;
				break;
            }
		} else
		    LOG(INFO)+"SyncThread is not ready";

		LOG(INFO)+"Waiting for "+ m_nPollInterval+ " sec to try again to register client";
		wait(m_nPollInterval*1000);
	}
    LOG(INFO)+"ClientRegister thread shutdown";
}

String CClientRegister::getRegisterBody(const String& strClientID)
{
    String strPushType = rho::push::CPushManager::getInstance()->getDefaultID();
    if(strPushType == "rhoconnect")
    {
        strPushType = "rhoconnect_push";
    }

    int port = RHOCONF().getInt("push_port");

    String appId = RHOCONF().getString("rho_app_id");
    String appVer = RHOCONF().getString("app_version");

	String body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin,
		port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho::System::getPhoneId(),
		                strPushType, appId, appVer);

	LOG(INFO)+"getRegisterBody() BODY is: " + body;
	return body;
}

String CClientRegister::getUnregisterBody(const String& strClientID)
{
	String body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, "", 0, "", "", "", "", "" );
	LOG(INFO)+"getUnregisterBody() BODY is: " + body;
	return body;
}

boolean CClientRegister::doRegister(CSyncEngine& oSync)
{
    String session = oSync.loadSession();
    if ( session.length() == 0 )
    {
        m_nPollInterval = POLL_INTERVAL_INFINITE;
        LOG(INFO)+"Session is empty, do register later";
        return false;
    }

    if ( m_strDevicePin.length() == 0 )
    {
        notifyLoggedIn("","",session);
        m_nPollInterval = POLL_INTERVAL_INFINITE;
        LOG(INFO)+"Device PUSH pin is empty, do register later";
        return false;
    }
    m_nPollInterval = POLL_INTERVAL_SECONDS;

	String client_id = oSync.loadClientID();
	if ( client_id.length() == 0 )
	{
        LOG(WARNING)+"Sync client_id is empty, do register later";
		return false;
	}
    {
        // IDBResult hold mutex of DB - we should free it ASAP
        IDBResult res = CDBAdapter::getUserDB().executeSQL("SELECT token,token_sent from client_info");
        if ( !res.isEnd() ) {
            String token = res.getStringByIdx(0);
            int token_sent = res.getIntByIdx(1) && !RHOCONF().getBool("register_push_at_startup");

            if ( m_strDevicePin.compare(token) == 0 && token_sent > 0 )
            {
                //token in db same as new one and it was already send to the server
                //so we do nothing

                return true;
            }
        }
    }

	String strBody = getRegisterBody(client_id);
    NetResponse resp = getNet().pushData( oSync.getProtocol().getClientRegisterUrl(client_id), strBody, &oSync );
	if( resp.isOK() )
    {
        CDBAdapter::getUserDB().executeSQL("UPDATE client_info SET token_sent=?, token=?", 1, m_strDevicePin );
		LOG(INFO)+"Registered client sucessfully...";

        return true;

    }

	LOG(WARNING)+"Network error: "+ resp.getRespCode();
	return false;
}

boolean CClientRegister::doUnregister(CSyncEngine& oSync)
{
    String session = m_unregisterSession;
    if ( session.length() == 0 )
    {
        m_unregisterSession = "";
        m_unregisterClientID = "";

        LOG(INFO)+"Session is empty, don't need to unregister";
        return true;
    }

    m_nPollInterval = POLL_INTERVAL_SECONDS;

	String client_id = m_unregisterClientID;
	if ( client_id.length() == 0 )
	{
        m_unregisterSession = "";
        m_unregisterClientID = "";

        LOG(WARNING)+"Sync client_id is empty, don't need to unregister";
		return true;
	}

    String strBody = getUnregisterBody(client_id);
    LOG(INFO)+"Unregistered client with body = " + strBody;

    class UnregisterSession : public net::IRhoSession {
        String m_session;
        String m_contentType;
    public:
        UnregisterSession(const String& session, const String& contentType) : m_session(session), m_contentType(contentType) {}
      	virtual void logout() {}
        virtual const String& getSession() {
            return m_session;
        }
        virtual const String& getContentType() {
            return m_contentType;
        }
    };

    UnregisterSession unregSession(session, oSync.getProtocol().getContentType() );

    NetResponse resp = getNet().pushData( oSync.getProtocol().getClientRegisterUrl(client_id), strBody, &unregSession );
	if( resp.isOK() )
    {
        m_unregisterSession = "";
        m_unregisterClientID = "";

        CDBAdapter::getUserDB().executeSQL("UPDATE client_info SET token_sent=?", 0 );
		LOG(INFO)+"Unregistered client sucessfully...";

        return true;

    }

	LOG(WARNING)+"Network error: "+ resp.getRespCode();
	return false;
}

void CClientRegister::setState( EnState st ) {
    synchronized(m_mxStateAccess)
    {
        m_state = st;
    }
}

CClientRegister::EnState CClientRegister::getState() {
    EnState state = stRegister;
    synchronized(m_mxStateAccess)
    {
        state = m_state;
    }

    return state;
}

void CClientRegister::doStop()
{
    LOG(INFO) + "Stopping ClientRegister...";

    m_NetRequest.cancel();
    stop(WAIT_BEFOREKILL_SECONDS);
}

}
}
<|endoftext|>


<commit_before>#include "interpreter.hpp"
#include "parser.hpp"
#include <sstream>

using namespace peglib;
using namespace std;

struct Eval
{
    static Value eval(const Ast& ast, shared_ptr<Environment> env) {
        switch (ast.tag) {
            case Statements:         return eval_statements(ast, env);
            case While:              return eval_while(ast, env);
            case If:                 return eval_if(ast, env);
            case Function:           return eval_function(ast, env);
            case FunctionCall:       return eval_function_call(ast, env);
            case Array:              return eval_array(ast, env);
            case ArrayReference:     return eval_array_reference(ast, env);
            case Assignment:         return eval_assignment(ast, env);
            case LogicalOr:          return eval_logical_or(ast, env);
            case LogicalAnd:         return eval_logical_and(ast, env);
            case Condition:          return eval_condition(ast, env);
            case UnaryPlus:          return eval_unary_plus(ast, env);
            case UnaryMinus:         return eval_unary_minus(ast, env);
            case UnaryNot:           return eval_unary_not(ast, env);
            case BinExpresion:       return eval_bin_expression(ast, env);
            case Identifier:         return eval_identifier(ast, env);
            case Number:             return eval_number(ast, env);
            case Boolean:            return eval_bool(ast, env);
            case InterpolatedString: return eval_interpolated_string(ast, env);
        }

        if (ast.is_token) {
            return Value(string(ast.token));
        }

        // NOTREACHED
        throw logic_error("invalid Ast type");
    }

private:
    static Value eval_statements(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.is_token) {
            return eval(ast, env);
        } else if (ast.nodes.empty()) {
            return Value();
        }
        auto it = ast.nodes.begin();
        while (it != ast.nodes.end() - 1) {
            eval(**it, env);
            ++it;
        }
        return eval(**it, env);
    }

    static Value eval_while(const Ast& ast, shared_ptr<Environment> env) {
        for (;;) {
            auto cond = eval(*ast.nodes[0], env);
            if (!cond.to_bool()) {
                break;
            }
            eval(*ast.nodes[1], env);
        }
        return Value();
    }

    static Value eval_if(const Ast& ast, shared_ptr<Environment> env) {
        const auto& nodes = ast.nodes;

        for (auto i = 0u; i < nodes.size(); i += 2) {
            if (i + 1 == nodes.size()) {
                return eval(*nodes[i], env);
            } else {
                auto cond = eval(*nodes[i], env);
                if (cond.to_bool()) {
                    return eval(*nodes[i + 1], env);
                }
            }
        }

        return Value();
    }

    static Value eval_function(const Ast& ast, shared_ptr<Environment> env) {
        vector<Value::FunctionValue::Parameter> params;
        for (auto node: ast.nodes[0]->nodes) {
            auto mut = node->nodes[0]->token == "mut";
            const auto& name = node->nodes[1]->token;
            params.push_back({ name, mut });
        }

        auto body = ast.nodes[1];

        return Value(Value::FunctionValue {
            params,
            [=](shared_ptr<Environment> callEnv) {
                callEnv->set_outer(env);
                return eval(*body, callEnv);
            }
        });
    };

    static Value eval_function_call(const Ast& ast, shared_ptr<Environment> env) {
        const auto& f = eval(*ast.nodes[0], env);
        const auto& fv = f.to_function();

        const auto& args = ast.nodes[1]->nodes;

        if (fv.params.size() <= args.size()) {
            auto callEnv = make_shared<Environment>();

            callEnv->initialize("self", f, false);

            for (auto i = 0u; i < fv.params.size(); i++) {
                auto param = fv.params[i];
                auto arg = args[i];
                auto val = eval(*arg, env);
                callEnv->initialize(param.name, val, param.mut);
            }

            return fv.eval(callEnv);
        }

        string msg = "arguments error...";
        throw runtime_error(msg);
    }

    static Value eval_array(const Ast& ast, shared_ptr<Environment> env) {
        vector<Value> values;

        for (auto i = 0u; i < ast.nodes.size(); i++) {
            auto expr = ast.nodes[i];
            auto val = eval(*expr, env);
            values.push_back(val);
        }

        return Value(Value::ArrayValue {
            values
        });
    }

    static Value eval_array_reference(const Ast& ast, shared_ptr<Environment> env) {
        const auto& a = eval(*ast.nodes[0], env).to_array();
        const auto& i = eval(*ast.nodes[1], env).to_long();

        if (0 <= i && i < a.values.size()) {
            return a.values[i];
        }

        return Value();
    }

    static Value eval_logical_or(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            Value ret;
            for (auto node: ast.nodes) {
                ret = eval(*node, env);
                if (ret.to_bool()) {
                    return ret;
                }
            }
            return ret;
        }
    }

    static Value eval_logical_and(const Ast& ast, shared_ptr<Environment> env) {
        Value ret;
        for (auto node: ast.nodes) {
            ret = eval(*node, env);
            if (!ret.to_bool()) {
                return ret;
            }
        }
        return ret;
    }

    static Value eval_condition(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            auto lhs = eval(*ast.nodes[0], env);
            auto ope = eval(*ast.nodes[1], env).to_string();
            auto rhs = eval(*ast.nodes[2], env);

            if (ope == "==") {
                return Value(lhs == rhs);
            } else if (ope == "!=") {
                return Value(lhs != rhs);
            } else if (ope == "<=") {
                return Value(lhs <= rhs);
            } else if (ope == "<") {
                return Value(lhs < rhs);
            } else if (ope == ">=") {
                return Value(lhs >= rhs);
            } else if (ope == ">") {
                return Value(lhs > rhs);
            } else {
                throw std::logic_error("invalid internal condition.");
            }
        }
    }

    static Value eval_unary_plus(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            return eval(*ast.nodes[1], env);
        }
    }

    static Value eval_unary_minus(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            return Value(eval(*ast.nodes[1], env).to_long() * -1);
        }
    }

    static Value eval_unary_not(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            return Value(!eval(*ast.nodes[1], env).to_bool());
        }
    }

    static Value eval_bin_expression(const Ast& ast, shared_ptr<Environment> env) {
        auto ret = eval(*ast.nodes[0], env).to_long();
        for (auto i = 1u; i < ast.nodes.size(); i += 2) {
            auto val = eval(*ast.nodes[i + 1], env).to_long();
            auto ope = eval(*ast.nodes[i], env).to_string()[0];
            switch (ope) {
                case '+': ret += val; break;
                case '-': ret -= val; break;
                case '*': ret *= val; break;
                case '/': ret /= val; break;
                case '%': ret %= val; break;
            }
        }
        return Value(ret);
    }

    static Value eval_assignment(const Ast& ast, shared_ptr<Environment> env) {
        const auto& mut = ast.nodes[0]->token;
        const auto& var = ast.nodes[1]->token;
        auto val = eval(*ast.nodes[2], env);
        if (env->has(var)) {
            env->assign(var, val);
        } else {
            env->initialize(var, val, mut == "mut");
        }
        return val;
    };

    static Value eval_identifier(const Ast& ast, shared_ptr<Environment> env) {
        const auto& var = ast.token;
        return env->get(var);
    };

    static Value eval_number(const Ast& ast, shared_ptr<Environment> env) {
        return Value(stol(ast.token));
    };

    static Value eval_bool(const Ast& ast, shared_ptr<Environment> env) {
        return Value(ast.token == "true");
    };

    static Value eval_interpolated_string(const Ast& ast, shared_ptr<Environment> env) {
        string s;
        for (auto node: ast.nodes) {
            const auto& val = eval(*node, env);
            s += val.str();
        }
        return Value(std::move(s));
    };
};

bool run(
    const string&           path,
    shared_ptr<Environment> env,
    const char*             expr,
    size_t                  len,
    Value&                  val,
    string&                 msg,
    bool                    print_ast)
{
    try {
        shared_ptr<Ast> ast;

        auto& parser = get_parser();

        parser.log = [&](size_t ln, size_t col, const string& err_msg) {
            stringstream ss;
            ss << path << ":" << ln << ":" << col << ": " << err_msg << endl;
            msg = ss.str();
        };

        if (parser.parse_n(expr, len, ast)) {
            if (print_ast) {
                ast->print();
            }

            val = Eval::eval(*ast, env);
            return true;
        }
    } catch (runtime_error& e) {
        msg = e.what();
    }

    return false;
}

// vim: et ts=4 sw=4 cin cino={1s ff=unix
<commit_msg>Fixed warning message with vc++.<commit_after>#include "interpreter.hpp"
#include "parser.hpp"
#include <sstream>

using namespace peglib;
using namespace std;

struct Eval
{
    static Value eval(const Ast& ast, shared_ptr<Environment> env) {
        switch (ast.tag) {
            case Statements:         return eval_statements(ast, env);
            case While:              return eval_while(ast, env);
            case If:                 return eval_if(ast, env);
            case Function:           return eval_function(ast, env);
            case FunctionCall:       return eval_function_call(ast, env);
            case Array:              return eval_array(ast, env);
            case ArrayReference:     return eval_array_reference(ast, env);
            case Assignment:         return eval_assignment(ast, env);
            case LogicalOr:          return eval_logical_or(ast, env);
            case LogicalAnd:         return eval_logical_and(ast, env);
            case Condition:          return eval_condition(ast, env);
            case UnaryPlus:          return eval_unary_plus(ast, env);
            case UnaryMinus:         return eval_unary_minus(ast, env);
            case UnaryNot:           return eval_unary_not(ast, env);
            case BinExpresion:       return eval_bin_expression(ast, env);
            case Identifier:         return eval_identifier(ast, env);
            case Number:             return eval_number(ast, env);
            case Boolean:            return eval_bool(ast, env);
            case InterpolatedString: return eval_interpolated_string(ast, env);
        }

        if (ast.is_token) {
            return Value(string(ast.token));
        }

        // NOTREACHED
        throw logic_error("invalid Ast type");
    }

private:
    static Value eval_statements(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.is_token) {
            return eval(ast, env);
        } else if (ast.nodes.empty()) {
            return Value();
        }
        auto it = ast.nodes.begin();
        while (it != ast.nodes.end() - 1) {
            eval(**it, env);
            ++it;
        }
        return eval(**it, env);
    }

    static Value eval_while(const Ast& ast, shared_ptr<Environment> env) {
        for (;;) {
            auto cond = eval(*ast.nodes[0], env);
            if (!cond.to_bool()) {
                break;
            }
            eval(*ast.nodes[1], env);
        }
        return Value();
    }

    static Value eval_if(const Ast& ast, shared_ptr<Environment> env) {
        const auto& nodes = ast.nodes;

        for (auto i = 0u; i < nodes.size(); i += 2) {
            if (i + 1 == nodes.size()) {
                return eval(*nodes[i], env);
            } else {
                auto cond = eval(*nodes[i], env);
                if (cond.to_bool()) {
                    return eval(*nodes[i + 1], env);
                }
            }
        }

        return Value();
    }

    static Value eval_function(const Ast& ast, shared_ptr<Environment> env) {
        vector<Value::FunctionValue::Parameter> params;
        for (auto node: ast.nodes[0]->nodes) {
            auto mut = node->nodes[0]->token == "mut";
            const auto& name = node->nodes[1]->token;
            params.push_back({ name, mut });
        }

        auto body = ast.nodes[1];

        return Value(Value::FunctionValue {
            params,
            [=](shared_ptr<Environment> callEnv) {
                callEnv->set_outer(env);
                return eval(*body, callEnv);
            }
        });
    };

    static Value eval_function_call(const Ast& ast, shared_ptr<Environment> env) {
        const auto& f = eval(*ast.nodes[0], env);
        const auto& fv = f.to_function();

        const auto& args = ast.nodes[1]->nodes;

        if (fv.params.size() <= args.size()) {
            auto callEnv = make_shared<Environment>();

            callEnv->initialize("self", f, false);

            for (auto i = 0u; i < fv.params.size(); i++) {
                auto param = fv.params[i];
                auto arg = args[i];
                auto val = eval(*arg, env);
                callEnv->initialize(param.name, val, param.mut);
            }

            return fv.eval(callEnv);
        }

        string msg = "arguments error...";
        throw runtime_error(msg);
    }

    static Value eval_array(const Ast& ast, shared_ptr<Environment> env) {
        vector<Value> values;

        for (auto i = 0u; i < ast.nodes.size(); i++) {
            auto expr = ast.nodes[i];
            auto val = eval(*expr, env);
            values.push_back(val);
        }

        return Value(Value::ArrayValue {
            values
        });
    }

    static Value eval_array_reference(const Ast& ast, shared_ptr<Environment> env) {
        const auto& a = eval(*ast.nodes[0], env).to_array();
        const auto& i = eval(*ast.nodes[1], env).to_long();

        if (0 <= i && i < static_cast<long>(a.values.size())) {
            return a.values[i];
        }

        return Value();
    }

    static Value eval_logical_or(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            Value ret;
            for (auto node: ast.nodes) {
                ret = eval(*node, env);
                if (ret.to_bool()) {
                    return ret;
                }
            }
            return ret;
        }
    }

    static Value eval_logical_and(const Ast& ast, shared_ptr<Environment> env) {
        Value ret;
        for (auto node: ast.nodes) {
            ret = eval(*node, env);
            if (!ret.to_bool()) {
                return ret;
            }
        }
        return ret;
    }

    static Value eval_condition(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            auto lhs = eval(*ast.nodes[0], env);
            auto ope = eval(*ast.nodes[1], env).to_string();
            auto rhs = eval(*ast.nodes[2], env);

            if (ope == "==") {
                return Value(lhs == rhs);
            } else if (ope == "!=") {
                return Value(lhs != rhs);
            } else if (ope == "<=") {
                return Value(lhs <= rhs);
            } else if (ope == "<") {
                return Value(lhs < rhs);
            } else if (ope == ">=") {
                return Value(lhs >= rhs);
            } else if (ope == ">") {
                return Value(lhs > rhs);
            } else {
                throw std::logic_error("invalid internal condition.");
            }
        }
    }

    static Value eval_unary_plus(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            return eval(*ast.nodes[1], env);
        }
    }

    static Value eval_unary_minus(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            return Value(eval(*ast.nodes[1], env).to_long() * -1);
        }
    }

    static Value eval_unary_not(const Ast& ast, shared_ptr<Environment> env) {
        if (ast.nodes.size() == 1) {
            return eval(*ast.nodes[0], env);
        } else {
            return Value(!eval(*ast.nodes[1], env).to_bool());
        }
    }

    static Value eval_bin_expression(const Ast& ast, shared_ptr<Environment> env) {
        auto ret = eval(*ast.nodes[0], env).to_long();
        for (auto i = 1u; i < ast.nodes.size(); i += 2) {
            auto val = eval(*ast.nodes[i + 1], env).to_long();
            auto ope = eval(*ast.nodes[i], env).to_string()[0];
            switch (ope) {
                case '+': ret += val; break;
                case '-': ret -= val; break;
                case '*': ret *= val; break;
                case '/': ret /= val; break;
                case '%': ret %= val; break;
            }
        }
        return Value(ret);
    }

    static Value eval_assignment(const Ast& ast, shared_ptr<Environment> env) {
        const auto& mut = ast.nodes[0]->token;
        const auto& var = ast.nodes[1]->token;
        auto val = eval(*ast.nodes[2], env);
        if (env->has(var)) {
            env->assign(var, val);
        } else {
            env->initialize(var, val, mut == "mut");
        }
        return val;
    };

    static Value eval_identifier(const Ast& ast, shared_ptr<Environment> env) {
        const auto& var = ast.token;
        return env->get(var);
    };

    static Value eval_number(const Ast& ast, shared_ptr<Environment> env) {
        return Value(stol(ast.token));
    };

    static Value eval_bool(const Ast& ast, shared_ptr<Environment> env) {
        return Value(ast.token == "true");
    };

    static Value eval_interpolated_string(const Ast& ast, shared_ptr<Environment> env) {
        string s;
        for (auto node: ast.nodes) {
            const auto& val = eval(*node, env);
            s += val.str();
        }
        return Value(std::move(s));
    };
};

bool run(
    const string&           path,
    shared_ptr<Environment> env,
    const char*             expr,
    size_t                  len,
    Value&                  val,
    string&                 msg,
    bool                    print_ast)
{
    try {
        shared_ptr<Ast> ast;

        auto& parser = get_parser();

        parser.log = [&](size_t ln, size_t col, const string& err_msg) {
            stringstream ss;
            ss << path << ":" << ln << ":" << col << ": " << err_msg << endl;
            msg = ss.str();
        };

        if (parser.parse_n(expr, len, ast)) {
            if (print_ast) {
                ast->print();
            }

            val = Eval::eval(*ast, env);
            return true;
        }
    } catch (runtime_error& e) {
        msg = e.what();
    }

    return false;
}

// vim: et ts=4 sw=4 cin cino={1s ff=unix
<|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "InterfaceKernelBase.h"

// MOOSE includes
#include "Assembly.h"
#include "MooseVariableFE.h"
#include "SystemBase.h"

#include "libmesh/quadrature.h"

defineLegacyParams(InterfaceKernelBase);

InputParameters
InterfaceKernelBase::validParams()
{
  InputParameters params = NeighborResidualObject::validParams();
  params += BoundaryRestrictable::validParams();

  params.addParam<bool>("use_displaced_mesh",
                        false,
                        "Whether or not this object should use the "
                        "displaced mesh for computation. Note that in "
                        "the case this is true but no displacements "
                        "are provided in the Mesh block the "
                        "undisplaced mesh will still be used.");
  params.addPrivateParam<bool>("_use_undisplaced_reference_points", false);
  params.addParamNamesToGroup("use_displaced_mesh", "Advanced");

  params.declareControllable("enable");
  params.addRequiredCoupledVar("neighbor_var", "The variable on the other side of the interface.");
  params.set<std::string>("_moose_base") = "InterfaceKernel";
  params.addParam<std::vector<AuxVariableName>>(
      "save_in",
      "The name of auxiliary variables to save this Kernel's residual contributions to. "
      " Everything about that variable must match everything about this variable (the "
      "type, what blocks it's on, etc.)");
  params.addParam<std::vector<AuxVariableName>>(
      "diag_save_in",
      "The name of auxiliary variables to save this Kernel's diagonal Jacobian "
      "contributions to. Everything about that variable must match everything "
      "about this variable (the type, what blocks it's on, etc.)");

  MultiMooseEnum save_in_var_side("m s");
  params.addParam<MultiMooseEnum>(
      "save_in_var_side",
      save_in_var_side,
      "This parameter must exist if save_in variables are specified and must have the same length "
      "as save_in. This vector specifies whether the corresponding aux_var should save-in "
      "residual contributions from the primary ('p') or secondary side ('s').");
  params.addParam<MultiMooseEnum>(
      "diag_save_in_var_side",
      save_in_var_side,
      "This parameter must exist if diag_save_in variables are specified and must have the same "
      "length as diag_save_in. This vector specifies whether the corresponding aux_var should "
      "save-in jacobian contributions from the primary ('p') or secondary side ('s').");

  // InterfaceKernels always need one layer of ghosting.
  params.addRelationshipManager("ElementSideNeighborLayers",
                                Moose::RelationshipManagerType::GEOMETRIC |
                                    Moose::RelationshipManagerType::ALGEBRAIC |
                                    Moose::RelationshipManagerType::COUPLING);
  return params;
}

// Static mutex definitions
Threads::spin_mutex InterfaceKernelBase::_resid_vars_mutex;
Threads::spin_mutex InterfaceKernelBase::_jacoby_vars_mutex;

InterfaceKernelBase::InterfaceKernelBase(const InputParameters & parameters)
  : NeighborResidualObject(parameters),
    BoundaryRestrictable(this, false), // false for _not_ nodal
    NeighborCoupleableMooseVariableDependencyIntermediateInterface(this, false, false),
    TwoMaterialPropertyInterface(this, Moose::EMPTY_BLOCK_IDS, boundaryIDs()),
    ElementIDInterface(this),
    _current_elem(_assembly.elem()),
    _current_elem_volume(_assembly.elemVolume()),
    _neighbor_elem(_assembly.neighbor()),
    _neighbor_elem_volume(_assembly.neighborVolume()),
    _current_side(_assembly.side()),
    _current_side_elem(_assembly.sideElem()),
    _current_side_volume(_assembly.sideElemVolume()),
    _coord_sys(_assembly.coordSystem()),
    _q_point(_assembly.qPointsFace()),
    _qrule(_assembly.qRuleFace()),
    _JxW(_assembly.JxWFace()),
    _coord(_assembly.coordTransformation()),
    _save_in_var_side(parameters.get<MultiMooseEnum>("save_in_var_side")),
    _save_in_strings(parameters.get<std::vector<AuxVariableName>>("save_in")),
    _diag_save_in_var_side(parameters.get<MultiMooseEnum>("diag_save_in_var_side")),
    _diag_save_in_strings(parameters.get<std::vector<AuxVariableName>>("diag_save_in"))

{
}

const Real &
InterfaceKernelBase::getNeighborElemVolume()
{
  return _assembly.neighborVolume();
}

void
InterfaceKernelBase::prepareShapes(const unsigned int var_num)
{
  _subproblem.prepareFaceShapes(var_num, _tid);
}
<commit_msg>Add TwoMaterialPropertyInterface params to InterfaceKernelBase<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "InterfaceKernelBase.h"

// MOOSE includes
#include "Assembly.h"
#include "MooseVariableFE.h"
#include "SystemBase.h"

#include "libmesh/quadrature.h"

defineLegacyParams(InterfaceKernelBase);

InputParameters
InterfaceKernelBase::validParams()
{
  InputParameters params = NeighborResidualObject::validParams();
  params += BoundaryRestrictable::validParams();
  params += TwoMaterialPropertyInterface::validParams();

  params.addParam<bool>("use_displaced_mesh",
                        false,
                        "Whether or not this object should use the "
                        "displaced mesh for computation. Note that in "
                        "the case this is true but no displacements "
                        "are provided in the Mesh block the "
                        "undisplaced mesh will still be used.");
  params.addPrivateParam<bool>("_use_undisplaced_reference_points", false);
  params.addParamNamesToGroup("use_displaced_mesh", "Advanced");

  params.declareControllable("enable");
  params.addRequiredCoupledVar("neighbor_var", "The variable on the other side of the interface.");
  params.set<std::string>("_moose_base") = "InterfaceKernel";
  params.addParam<std::vector<AuxVariableName>>(
      "save_in",
      "The name of auxiliary variables to save this Kernel's residual contributions to. "
      " Everything about that variable must match everything about this variable (the "
      "type, what blocks it's on, etc.)");
  params.addParam<std::vector<AuxVariableName>>(
      "diag_save_in",
      "The name of auxiliary variables to save this Kernel's diagonal Jacobian "
      "contributions to. Everything about that variable must match everything "
      "about this variable (the type, what blocks it's on, etc.)");

  MultiMooseEnum save_in_var_side("m s");
  params.addParam<MultiMooseEnum>(
      "save_in_var_side",
      save_in_var_side,
      "This parameter must exist if save_in variables are specified and must have the same length "
      "as save_in. This vector specifies whether the corresponding aux_var should save-in "
      "residual contributions from the primary ('p') or secondary side ('s').");
  params.addParam<MultiMooseEnum>(
      "diag_save_in_var_side",
      save_in_var_side,
      "This parameter must exist if diag_save_in variables are specified and must have the same "
      "length as diag_save_in. This vector specifies whether the corresponding aux_var should "
      "save-in jacobian contributions from the primary ('p') or secondary side ('s').");

  // InterfaceKernels always need one layer of ghosting.
  params.addRelationshipManager("ElementSideNeighborLayers",
                                Moose::RelationshipManagerType::GEOMETRIC |
                                    Moose::RelationshipManagerType::ALGEBRAIC |
                                    Moose::RelationshipManagerType::COUPLING);
  return params;
}

// Static mutex definitions
Threads::spin_mutex InterfaceKernelBase::_resid_vars_mutex;
Threads::spin_mutex InterfaceKernelBase::_jacoby_vars_mutex;

InterfaceKernelBase::InterfaceKernelBase(const InputParameters & parameters)
  : NeighborResidualObject(parameters),
    BoundaryRestrictable(this, false), // false for _not_ nodal
    NeighborCoupleableMooseVariableDependencyIntermediateInterface(this, false, false),
    TwoMaterialPropertyInterface(this, Moose::EMPTY_BLOCK_IDS, boundaryIDs()),
    ElementIDInterface(this),
    _current_elem(_assembly.elem()),
    _current_elem_volume(_assembly.elemVolume()),
    _neighbor_elem(_assembly.neighbor()),
    _neighbor_elem_volume(_assembly.neighborVolume()),
    _current_side(_assembly.side()),
    _current_side_elem(_assembly.sideElem()),
    _current_side_volume(_assembly.sideElemVolume()),
    _coord_sys(_assembly.coordSystem()),
    _q_point(_assembly.qPointsFace()),
    _qrule(_assembly.qRuleFace()),
    _JxW(_assembly.JxWFace()),
    _coord(_assembly.coordTransformation()),
    _save_in_var_side(parameters.get<MultiMooseEnum>("save_in_var_side")),
    _save_in_strings(parameters.get<std::vector<AuxVariableName>>("save_in")),
    _diag_save_in_var_side(parameters.get<MultiMooseEnum>("diag_save_in_var_side")),
    _diag_save_in_strings(parameters.get<std::vector<AuxVariableName>>("diag_save_in"))

{
}

const Real &
InterfaceKernelBase::getNeighborElemVolume()
{
  return _assembly.neighborVolume();
}

void
InterfaceKernelBase::prepareShapes(const unsigned int var_num)
{
  _subproblem.prepareFaceShapes(var_num, _tid);
}
<|endoftext|>


<commit_before>#include "FillTool.h"

#include <qDebug>
#include <QQueue>

void Painting::FillTool::begin(const QPoint &point, QPainter &painter, const QPixmap &pixmap)
{
    QRgb oldColor = pixmap.toImage().pixel(point);
    QRect pixmapRect = pixmap.rect();

    if (QColor(oldColor) == painter.pen().color())
    {
        return;
    }

    QQueue<QPoint> neighbours;
    neighbours.enqueue(point);

    while(!neighbours.isEmpty())
    {
        QPoint currentPoint = neighbours.dequeue();
        if (pixmapRect.contains(currentPoint))
        {
            QRgb currentColor = pixmap.toImage().pixel(currentPoint);
            if (currentColor == oldColor)
            {
                painter.drawPoint(currentPoint);

                neighbours.enqueue(QPoint(currentPoint.x() - 1, currentPoint.y()));
                neighbours.enqueue(QPoint(currentPoint.x() + 1, currentPoint.y()));
                neighbours.enqueue(QPoint(currentPoint.x(), currentPoint.y() - 1));
                neighbours.enqueue(QPoint(currentPoint.x(), currentPoint.y() + 1));
            }
        }
    }
}

void Painting::FillTool::move(const QPoint &point, QPainter &painter, const QPixmap &pixmap)
{
    this->begin(point, painter, pixmap);
}
<commit_msg>Accelerate FillTool<commit_after>#include "FillTool.h"

#include <qDebug>
#include <QQueue>

void Painting::FillTool::begin(const QPoint &point, QPainter &painter, const QPixmap &pixmap)
{
    QImage image = pixmap.toImage();
    const QRect pixmapRect = pixmap.rect();

    const QRgb oldColor = image.pixel(point);
    const QRgb newColor = painter.pen().color().rgb();

    if (oldColor == newColor)
    {
        return;
    }

    QQueue<QPoint> neighbours;
    neighbours.enqueue(point);

    while(!neighbours.isEmpty())
    {
        const QPoint currentPoint = neighbours.dequeue();
        if (pixmapRect.contains(currentPoint))
        {
            const QRgb currentColor = image.pixel(currentPoint);
            if (currentColor == oldColor)
            {
                image.setPixel(currentPoint, newColor);

                neighbours.enqueue(QPoint(currentPoint.x() - 1, currentPoint.y()));
                neighbours.enqueue(QPoint(currentPoint.x() + 1, currentPoint.y()));
                neighbours.enqueue(QPoint(currentPoint.x(), currentPoint.y() - 1));
                neighbours.enqueue(QPoint(currentPoint.x(), currentPoint.y() + 1));
            }
        }
    }
    painter.drawImage(QPoint(), image);
}

void Painting::FillTool::move(const QPoint &point, QPainter &painter, const QPixmap &pixmap)
{
    this->begin(point, painter, pixmap);
}
<|endoftext|>