<commit_before>
#include "Internal.h"
#include <Lumino/UI/UIViewport.h>
#include <Lumino/UI/UILayoutView.h>
#include <Lumino/UI/UIContext.h>
#include <Lumino/Rendering/DrawingContext.h>
#include "UIManager.h"

LN_NAMESPACE_BEGIN

//==============================================================================
// UIViewport
//==============================================================================
LN_TR_REFLECTION_TYPEINFO_IMPLEMENT(UIViewport, UIElement);

//------------------------------------------------------------------------------
UIViewport::UIViewport()
	: UIElement()
	, m_backbufferSize(0, 0)
	, m_placement(ViewportPlacement::Stretch)
	, m_backgroundColor(Color::White)
{
}

//------------------------------------------------------------------------------
UIViewport::~UIViewport()
{
}

//------------------------------------------------------------------------------
void UIViewport::initialize()
{
	UIElement::initialize();
}

//------------------------------------------------------------------------------
void UIViewport::setViewBackgroundColor(const Color& color)
{
	m_backgroundColor = color;
}

//------------------------------------------------------------------------------
void UIViewport::setPlacement(ViewportPlacement placement)
{
	m_placement = placement;
}

//------------------------------------------------------------------------------
void UIViewport::setBackbufferSize(int width, int height)
{
	m_backbufferSize.set(width, height);
}

//------------------------------------------------------------------------------
void UIViewport::addViewportLayer(UIViewportLayer* layer)
{
	m_viewportLayerList.add(layer);
	layer->m_owner = this;
}

//------------------------------------------------------------------------------
//void UIViewport::RemoveViewportLayer(ViewportLayer* layer)
//{
//	if (m_viewportLayerList->Remove(RefPtr<ViewportLayer>(layer)))
//	{
//		layer->SetOwner(nullptr);
//	}
//}

//------------------------------------------------------------------------------
void UIViewport::onRoutedEvent(UIEventArgs* e)
{
	// UI 要素は通常 UIViewport の上に張り付けられる。
	// デフォルトの MainWindow などは全体に UILayoutPanel が乗るので、
	// 通常のイベントではなく RoutedEvent でなければハンドリングできない。

	for (auto& layer : m_viewportLayerList)
	{
		layer->onRoutedEvent(e);
		if (e->handled) return;
	}

	return UIElement::onRoutedEvent(e);
}

//------------------------------------------------------------------------------
Size UIViewport::arrangeOverride(const Size& finalSize)
{
	Size renderSize = UIElement::arrangeOverride(finalSize);

	for (auto& layer : m_viewportLayerList)
	{
		layer->updateLayout(finalSize);
	}

	return renderSize;
}

//------------------------------------------------------------------------------
UIElement* UIViewport::checkMouseHoverElement(const PointF& globalPt)
{
	for (auto& layer : m_viewportLayerList)
	{
		auto* element = layer->hitTestUIElement(globalPt);
		if (element != nullptr) return element;
	}

	return UIElement::checkMouseHoverElement(globalPt);
}

//------------------------------------------------------------------------------
void UIViewport::onRender(DrawingContext* g)
{
	// バックバッファサイズの調整
	{
		SizeI bakcbufferSize;
		if (m_placement == ViewportPlacement::AutoResize)
			bakcbufferSize = SizeI::fromFloatSize(getRenderSize());
		else
			bakcbufferSize = m_backbufferSize;

		updateFramebufferSizeIfNeeded(bakcbufferSize);
	}

	//TODO: state push/pop

	RefPtr<RenderTargetTexture> oldRT = g->getRenderTarget(0);
	RefPtr<DepthBuffer> oldDB = g->getDepthBuffer();

	g->setRenderTarget(0, m_primaryLayerTarget);
	g->setDepthBuffer(m_depthBuffer);
	g->clear(ClearFlags::All, m_backgroundColor, 1.0f, 0);

	for (auto& layer : m_viewportLayerList)
	{
		layer->render();
	}

	g->setBuiltinEffectData(detail::BuiltinEffectData::DefaultData);

	// 全てのレイヤーの描画リストを実行し m_primaryLayerTarget へ書き込む
	for (auto& layer : m_viewportLayerList)
	{
		layer->executeDrawListRendering(g, m_primaryLayerTarget, m_depthBuffer);

		// Posteffect
		layer->postRender(g, &m_primaryLayerTarget, &m_secondaryLayerTarget);
	}

	g->setRenderTarget(0, oldRT);
	g->setDepthBuffer(oldDB);
	g->blit(m_primaryLayerTarget);	// TODO: 転送先指定

	// TODO: 暫定。blit の中で深度書き込みしないようにしてほしいかも。
	g->clear(ClearFlags::Depth, Color());

	UIElement::onRender(g);
}

//------------------------------------------------------------------------------
void UIViewport::updateFramebufferSizeIfNeeded(const SizeI& viewSize)
{
	bool create = false;
	SizeI newSize(0, 0);

	// 初回、まだ作成されていなければ作りたい
	if (m_primaryLayerTarget == nullptr)
	{
		create = true;
		newSize = viewSize;
	}

	// 自動リサイズONで、描画先とサイズが異なるなら再作成
	if (m_placement == ViewportPlacement::AutoResize)
	{
		if (m_primaryLayerTarget != nullptr && viewSize != m_primaryLayerTarget->getSize())
		{
			create = true;
		}
		newSize = viewSize;
	}

	if (create)
	{
		// RenderTargetTexture
		// TODO: できればこういうのは Resize 関数を作りたい。作り直したくない
		// TODO: というか UE4 みたいにキャッシュしたい
		m_primaryLayerTarget = RefPtr<RenderTargetTexture>::makeRef();
		m_primaryLayerTarget->createImpl(getManager()->getGraphicsManager(), newSize, 1, TextureFormat::R8G8B8X8);
		m_secondaryLayerTarget = RefPtr<RenderTargetTexture>::makeRef();
		m_secondaryLayerTarget->createImpl(getManager()->getGraphicsManager(), newSize, 1, TextureFormat::R8G8B8X8);

		// DepthBuffer
		m_depthBuffer = RefPtr<DepthBuffer>::makeRef();
		m_depthBuffer->createImpl(getManager()->getGraphicsManager(), newSize, TextureFormat::D24S8);

		m_viewSize = newSize.toFloatSize();
	}
}

//------------------------------------------------------------------------------
void UIViewport::makeViewBoxTransform(const SizeI& dstSize, const SizeI& srcSize, Matrix* mat)
{
	float sw = static_cast<float>(srcSize.width);   // 転送元
	float sh = static_cast<float>(srcSize.height);
	float dw = static_cast<float>(dstSize.width);	// 転送先
	float dh = static_cast<float>(dstSize.height);

	float new_x, new_y;
	float new_w, new_h;

	float ratio_w;
	float ratio_h;

	// バックバッファサイズとスクリーンサイズが同じ場合
	if (sw == dw && sh == dh)
	{
		// そのまま設定
		new_x = 0;
		new_y = 0;
		new_w = sw;
		new_h = sh;
		ratio_w = 1.0f;
		ratio_h = 1.0f;
	}
	else
	{
		// 現在のスクリーンサイズ(デフォルトビューポートのサイズ)と画面サイズの比率計算
		ratio_w = dw / sw;
		ratio_h = dh / sh;

		// 縦方向に合わせる ( 左右が余る )
		if (ratio_w > ratio_h)
		{
			new_w = static_cast< float >(sw * ratio_h);
			new_h = static_cast< float >(dh);
			new_x = static_cast< float >((dw / 2) - (new_w / 2));
			new_y = 0;
		}
		//横方向にあわせる
		else
		{
			new_w = static_cast< float >(dw);
			new_h = static_cast< float >(sh * ratio_w);
			new_x = 0;
			new_y = static_cast< float >((dh / 2) - (new_h / 2));
		}
	}

#if 1	// pxel based
	* mat = Matrix::Identity;
	mat->scale(new_w / sw, new_h / sh, 1.0f);
	mat->translate(new_x, new_y, 0.0f);
#else	// screen coord based
	*mat = Matrix::Identity;
	mat->Scale(new_w / dw, new_h / dh, 1.0f);
#endif
}

//==============================================================================
// UIViewportLayer
//==============================================================================
//LN_TR_REFLECTION_TYPEINFO_IMPLEMENT(UIViewportLayer, Object);

//------------------------------------------------------------------------------
UIViewportLayer::UIViewportLayer()
	: Object()
	, m_owner(nullptr)
{
}

//------------------------------------------------------------------------------
UIViewportLayer::~UIViewportLayer()
{
}

//------------------------------------------------------------------------------
void UIViewportLayer::addPostEffect(PostEffect* postEffect)
{
	m_postEffects.add(postEffect);
	postEffect->m_ownerLayer = this;
}

//------------------------------------------------------------------------------
UIElement* UIViewportLayer::hitTestUIElement(const PointF& globalPt)
{
	return nullptr;
}

//------------------------------------------------------------------------------
void UIViewportLayer::onRoutedEvent(UIEventArgs* e)
{
}

//------------------------------------------------------------------------------
void UIViewportLayer::updateLayout(const Size& viewSize)
{
}

//------------------------------------------------------------------------------
void UIViewportLayer::postRender(DrawList* context, RefPtr<RenderTargetTexture>* primaryLayerTarget, RefPtr<RenderTargetTexture>* secondaryLayerTarget)
{
	for (auto& e : m_postEffects)
	{
		e->onRender(context, *primaryLayerTarget, *secondaryLayerTarget);
		std::swap(*primaryLayerTarget, *secondaryLayerTarget);
	}
}

//==============================================================================
// UILayoutLayer
//==============================================================================
//------------------------------------------------------------------------------
UILayoutLayer::UILayoutLayer()
{
}

//------------------------------------------------------------------------------
UILayoutLayer::~UILayoutLayer()
{
}

//------------------------------------------------------------------------------
void UILayoutLayer::initialize()
{
	UIViewportLayer::initialize();
	m_root = newObject<UILayoutView>(UIContext::getMainContext(), nullptr);	// TODO: コンテキスト変更とか

	m_drawingContext = newObject<DrawingContext>();

	// lighting disabled.
	// TODO: newObject
	auto internalRenderer = RefPtr<detail::NonShadingRenderer>::makeRef();
	internalRenderer->initialize(detail::EngineDomain::getGraphicsManager());
	m_internalRenderer = internalRenderer;

	m_drawElementListSet = RefPtr<RenderView>::makeRef();
	m_drawElementListSet->m_lists.add(m_drawingContext->getDrawElementList());

}

//------------------------------------------------------------------------------
UILayoutView* UILayoutLayer::GetLayoutView() const
{
	return m_root;
}

//------------------------------------------------------------------------------
UIElement* UILayoutLayer::hitTestUIElement(const PointF& globalPt)
{
	auto* element = m_root->checkMouseHoverElement(globalPt);
	if (element != nullptr) return element;
	return UIViewportLayer::hitTestUIElement(globalPt);
}

//------------------------------------------------------------------------------
void UILayoutLayer::onRoutedEvent(UIEventArgs* e)
{
	//m_root->raiseEvent(e->GetType(), e->sender, e);
}

//------------------------------------------------------------------------------
void UILayoutLayer::updateLayout(const Size& viewSize)
{
	m_root->updateLayout(viewSize);
}

//------------------------------------------------------------------------------
void UILayoutLayer::render()
{
	m_drawingContext->beginMakeElements();
	m_drawingContext->setBlendMode(BlendMode::Alpha);
	//m_drawingContext->Clear(ClearFlags::All, Color::Black);;	// TODO
	m_root->render(m_drawingContext);
}

//------------------------------------------------------------------------------
void UILayoutLayer::executeDrawListRendering(DrawList* parentDrawList, RenderTargetTexture* renderTarget, DepthBuffer* depthBuffer)
{
	// TODO: float
	Size viewPixelSize((float)renderTarget->getWidth(), (float)renderTarget->getHeight());

	m_drawElementListSet->m_cameraInfo.dataSourceId = reinterpret_cast<intptr_t>(this);
	m_drawElementListSet->m_cameraInfo.viewPixelSize = viewPixelSize;
	m_drawElementListSet->m_cameraInfo.viewPosition = Vector3::Zero;
	m_drawElementListSet->m_cameraInfo.viewMatrix = Matrix::Identity;
	m_drawElementListSet->m_cameraInfo.projMatrix = Matrix::makePerspective2DLH(m_drawElementListSet->m_cameraInfo.viewPixelSize.width, m_drawElementListSet->m_cameraInfo.viewPixelSize.height, 0, 1);
	m_drawElementListSet->m_cameraInfo.viewProjMatrix = m_drawElementListSet->m_cameraInfo.viewMatrix * m_drawElementListSet->m_cameraInfo.projMatrix;
	m_drawElementListSet->m_cameraInfo.viewFrustum = ViewFrustum(m_drawElementListSet->m_cameraInfo.projMatrix);
	m_drawElementListSet->m_cameraInfo.zSortDistanceBase = ZSortDistanceBase::NodeZ;
	parentDrawList->renderSubView(
		m_drawElementListSet,
		m_internalRenderer,
		renderTarget,
		depthBuffer);
}

//==============================================================================
// PostEffect
//==============================================================================
LN_TR_REFLECTION_TYPEINFO_IMPLEMENT(PostEffect, Object);

//------------------------------------------------------------------------------
PostEffect::PostEffect()
	: Object()
{
}

//------------------------------------------------------------------------------
PostEffect::~PostEffect()
{
}

//------------------------------------------------------------------------------
void PostEffect::initialize()
{
}

LN_NAMESPACE_END
<commit_msg>fix event bug<commit_after>
#include "Internal.h"
#include <Lumino/UI/UIViewport.h>
#include <Lumino/UI/UILayoutView.h>
#include <Lumino/UI/UIContext.h>
#include <Lumino/Rendering/DrawingContext.h>
#include "UIManager.h"

LN_NAMESPACE_BEGIN

//==============================================================================
// UIViewport
//==============================================================================
LN_TR_REFLECTION_TYPEINFO_IMPLEMENT(UIViewport, UIElement);

//------------------------------------------------------------------------------
UIViewport::UIViewport()
	: UIElement()
	, m_backbufferSize(0, 0)
	, m_placement(ViewportPlacement::Stretch)
	, m_backgroundColor(Color::White)
{
}

//------------------------------------------------------------------------------
UIViewport::~UIViewport()
{
}

//------------------------------------------------------------------------------
void UIViewport::initialize()
{
	UIElement::initialize();
	setHitTestVisible(true);
}

//------------------------------------------------------------------------------
void UIViewport::setViewBackgroundColor(const Color& color)
{
	m_backgroundColor = color;
}

//------------------------------------------------------------------------------
void UIViewport::setPlacement(ViewportPlacement placement)
{
	m_placement = placement;
}

//------------------------------------------------------------------------------
void UIViewport::setBackbufferSize(int width, int height)
{
	m_backbufferSize.set(width, height);
}

//------------------------------------------------------------------------------
void UIViewport::addViewportLayer(UIViewportLayer* layer)
{
	m_viewportLayerList.add(layer);
	layer->m_owner = this;
}

//------------------------------------------------------------------------------
//void UIViewport::RemoveViewportLayer(ViewportLayer* layer)
//{
//	if (m_viewportLayerList->Remove(RefPtr<ViewportLayer>(layer)))
//	{
//		layer->SetOwner(nullptr);
//	}
//}

//------------------------------------------------------------------------------
void UIViewport::onRoutedEvent(UIEventArgs* e)
{
	// UI 要素は通常 UIViewport の上に張り付けられる。
	// デフォルトの MainWindow などは全体に UILayoutPanel が乗るので、
	// 通常のイベントではなく RoutedEvent でなければハンドリングできない。

	for (auto& layer : m_viewportLayerList)
	{
		layer->onRoutedEvent(e);
		if (e->handled) return;
	}

	return UIElement::onRoutedEvent(e);
}

//------------------------------------------------------------------------------
Size UIViewport::arrangeOverride(const Size& finalSize)
{
	Size renderSize = UIElement::arrangeOverride(finalSize);

	for (auto& layer : m_viewportLayerList)
	{
		layer->updateLayout(finalSize);
	}

	return renderSize;
}

//------------------------------------------------------------------------------
UIElement* UIViewport::checkMouseHoverElement(const PointF& globalPt)
{
	for (auto& layer : m_viewportLayerList)
	{
		auto* element = layer->hitTestUIElement(globalPt);
		if (element != nullptr) return element;
	}

	return UIElement::checkMouseHoverElement(globalPt);
}

//------------------------------------------------------------------------------
void UIViewport::onRender(DrawingContext* g)
{
	// バックバッファサイズの調整
	{
		SizeI bakcbufferSize;
		if (m_placement == ViewportPlacement::AutoResize)
			bakcbufferSize = SizeI::fromFloatSize(getRenderSize());
		else
			bakcbufferSize = m_backbufferSize;

		updateFramebufferSizeIfNeeded(bakcbufferSize);
	}

	//TODO: state push/pop

	RefPtr<RenderTargetTexture> oldRT = g->getRenderTarget(0);
	RefPtr<DepthBuffer> oldDB = g->getDepthBuffer();

	g->setRenderTarget(0, m_primaryLayerTarget);
	g->setDepthBuffer(m_depthBuffer);
	g->clear(ClearFlags::All, m_backgroundColor, 1.0f, 0);

	for (auto& layer : m_viewportLayerList)
	{
		layer->render();
	}

	g->setBuiltinEffectData(detail::BuiltinEffectData::DefaultData);

	// 全てのレイヤーの描画リストを実行し m_primaryLayerTarget へ書き込む
	for (auto& layer : m_viewportLayerList)
	{
		layer->executeDrawListRendering(g, m_primaryLayerTarget, m_depthBuffer);

		// Posteffect
		layer->postRender(g, &m_primaryLayerTarget, &m_secondaryLayerTarget);
	}

	g->setRenderTarget(0, oldRT);
	g->setDepthBuffer(oldDB);
	g->blit(m_primaryLayerTarget);	// TODO: 転送先指定

	// TODO: 暫定。blit の中で深度書き込みしないようにしてほしいかも。
	g->clear(ClearFlags::Depth, Color());

	UIElement::onRender(g);
}

//------------------------------------------------------------------------------
void UIViewport::updateFramebufferSizeIfNeeded(const SizeI& viewSize)
{
	bool create = false;
	SizeI newSize(0, 0);

	// 初回、まだ作成されていなければ作りたい
	if (m_primaryLayerTarget == nullptr)
	{
		create = true;
		newSize = viewSize;
	}

	// 自動リサイズONで、描画先とサイズが異なるなら再作成
	if (m_placement == ViewportPlacement::AutoResize)
	{
		if (m_primaryLayerTarget != nullptr && viewSize != m_primaryLayerTarget->getSize())
		{
			create = true;
		}
		newSize = viewSize;
	}

	if (create)
	{
		// RenderTargetTexture
		// TODO: できればこういうのは Resize 関数を作りたい。作り直したくない
		// TODO: というか UE4 みたいにキャッシュしたい
		m_primaryLayerTarget = RefPtr<RenderTargetTexture>::makeRef();
		m_primaryLayerTarget->createImpl(getManager()->getGraphicsManager(), newSize, 1, TextureFormat::R8G8B8X8);
		m_secondaryLayerTarget = RefPtr<RenderTargetTexture>::makeRef();
		m_secondaryLayerTarget->createImpl(getManager()->getGraphicsManager(), newSize, 1, TextureFormat::R8G8B8X8);

		// DepthBuffer
		m_depthBuffer = RefPtr<DepthBuffer>::makeRef();
		m_depthBuffer->createImpl(getManager()->getGraphicsManager(), newSize, TextureFormat::D24S8);

		m_viewSize = newSize.toFloatSize();
	}
}

//------------------------------------------------------------------------------
void UIViewport::makeViewBoxTransform(const SizeI& dstSize, const SizeI& srcSize, Matrix* mat)
{
	float sw = static_cast<float>(srcSize.width);   // 転送元
	float sh = static_cast<float>(srcSize.height);
	float dw = static_cast<float>(dstSize.width);	// 転送先
	float dh = static_cast<float>(dstSize.height);

	float new_x, new_y;
	float new_w, new_h;

	float ratio_w;
	float ratio_h;

	// バックバッファサイズとスクリーンサイズが同じ場合
	if (sw == dw && sh == dh)
	{
		// そのまま設定
		new_x = 0;
		new_y = 0;
		new_w = sw;
		new_h = sh;
		ratio_w = 1.0f;
		ratio_h = 1.0f;
	}
	else
	{
		// 現在のスクリーンサイズ(デフォルトビューポートのサイズ)と画面サイズの比率計算
		ratio_w = dw / sw;
		ratio_h = dh / sh;

		// 縦方向に合わせる ( 左右が余る )
		if (ratio_w > ratio_h)
		{
			new_w = static_cast< float >(sw * ratio_h);
			new_h = static_cast< float >(dh);
			new_x = static_cast< float >((dw / 2) - (new_w / 2));
			new_y = 0;
		}
		//横方向にあわせる
		else
		{
			new_w = static_cast< float >(dw);
			new_h = static_cast< float >(sh * ratio_w);
			new_x = 0;
			new_y = static_cast< float >((dh / 2) - (new_h / 2));
		}
	}

#if 1	// pxel based
	* mat = Matrix::Identity;
	mat->scale(new_w / sw, new_h / sh, 1.0f);
	mat->translate(new_x, new_y, 0.0f);
#else	// screen coord based
	*mat = Matrix::Identity;
	mat->Scale(new_w / dw, new_h / dh, 1.0f);
#endif
}

//==============================================================================
// UIViewportLayer
//==============================================================================
//LN_TR_REFLECTION_TYPEINFO_IMPLEMENT(UIViewportLayer, Object);

//------------------------------------------------------------------------------
UIViewportLayer::UIViewportLayer()
	: Object()
	, m_owner(nullptr)
{
}

//------------------------------------------------------------------------------
UIViewportLayer::~UIViewportLayer()
{
}

//------------------------------------------------------------------------------
void UIViewportLayer::addPostEffect(PostEffect* postEffect)
{
	m_postEffects.add(postEffect);
	postEffect->m_ownerLayer = this;
}

//------------------------------------------------------------------------------
UIElement* UIViewportLayer::hitTestUIElement(const PointF& globalPt)
{
	return nullptr;
}

//------------------------------------------------------------------------------
void UIViewportLayer::onRoutedEvent(UIEventArgs* e)
{
}

//------------------------------------------------------------------------------
void UIViewportLayer::updateLayout(const Size& viewSize)
{
}

//------------------------------------------------------------------------------
void UIViewportLayer::postRender(DrawList* context, RefPtr<RenderTargetTexture>* primaryLayerTarget, RefPtr<RenderTargetTexture>* secondaryLayerTarget)
{
	for (auto& e : m_postEffects)
	{
		e->onRender(context, *primaryLayerTarget, *secondaryLayerTarget);
		std::swap(*primaryLayerTarget, *secondaryLayerTarget);
	}
}

//==============================================================================
// UILayoutLayer
//==============================================================================
//------------------------------------------------------------------------------
UILayoutLayer::UILayoutLayer()
{
}

//------------------------------------------------------------------------------
UILayoutLayer::~UILayoutLayer()
{
}

//------------------------------------------------------------------------------
void UILayoutLayer::initialize()
{
	UIViewportLayer::initialize();
	m_root = newObject<UILayoutView>(UIContext::getMainContext(), nullptr);	// TODO: コンテキスト変更とか

	// このルート要素はビュー全体に広がるが、ヒットテストは行わない。
	// 行ってしまうと、その後ろにあるシーンのビューにイベントが流れなくなる。
	m_root->setHitTestVisible(false);

	m_drawingContext = newObject<DrawingContext>();

	// lighting disabled.
	// TODO: newObject
	auto internalRenderer = RefPtr<detail::NonShadingRenderer>::makeRef();
	internalRenderer->initialize(detail::EngineDomain::getGraphicsManager());
	m_internalRenderer = internalRenderer;

	m_drawElementListSet = RefPtr<RenderView>::makeRef();
	m_drawElementListSet->m_lists.add(m_drawingContext->getDrawElementList());

}

//------------------------------------------------------------------------------
UILayoutView* UILayoutLayer::GetLayoutView() const
{
	return m_root;
}

//------------------------------------------------------------------------------
UIElement* UILayoutLayer::hitTestUIElement(const PointF& globalPt)
{
	auto* element = m_root->checkMouseHoverElement(globalPt);
	if (element != nullptr) return element;
	return UIViewportLayer::hitTestUIElement(globalPt);
}

//------------------------------------------------------------------------------
void UILayoutLayer::onRoutedEvent(UIEventArgs* e)
{
	//m_root->raiseEvent(e->GetType(), e->sender, e);
}

//------------------------------------------------------------------------------
void UILayoutLayer::updateLayout(const Size& viewSize)
{
	m_root->updateLayout(viewSize);
}

//------------------------------------------------------------------------------
void UILayoutLayer::render()
{
	m_drawingContext->beginMakeElements();
	m_drawingContext->setBlendMode(BlendMode::Alpha);
	//m_drawingContext->Clear(ClearFlags::All, Color::Black);;	// TODO
	m_root->render(m_drawingContext);
}

//------------------------------------------------------------------------------
void UILayoutLayer::executeDrawListRendering(DrawList* parentDrawList, RenderTargetTexture* renderTarget, DepthBuffer* depthBuffer)
{
	// TODO: float
	Size viewPixelSize((float)renderTarget->getWidth(), (float)renderTarget->getHeight());

	m_drawElementListSet->m_cameraInfo.dataSourceId = reinterpret_cast<intptr_t>(this);
	m_drawElementListSet->m_cameraInfo.viewPixelSize = viewPixelSize;
	m_drawElementListSet->m_cameraInfo.viewPosition = Vector3::Zero;
	m_drawElementListSet->m_cameraInfo.viewMatrix = Matrix::Identity;
	m_drawElementListSet->m_cameraInfo.projMatrix = Matrix::makePerspective2DLH(m_drawElementListSet->m_cameraInfo.viewPixelSize.width, m_drawElementListSet->m_cameraInfo.viewPixelSize.height, 0, 1);
	m_drawElementListSet->m_cameraInfo.viewProjMatrix = m_drawElementListSet->m_cameraInfo.viewMatrix * m_drawElementListSet->m_cameraInfo.projMatrix;
	m_drawElementListSet->m_cameraInfo.viewFrustum = ViewFrustum(m_drawElementListSet->m_cameraInfo.projMatrix);
	m_drawElementListSet->m_cameraInfo.zSortDistanceBase = ZSortDistanceBase::NodeZ;
	parentDrawList->renderSubView(
		m_drawElementListSet,
		m_internalRenderer,
		renderTarget,
		depthBuffer);
}

//==============================================================================
// PostEffect
//==============================================================================
LN_TR_REFLECTION_TYPEINFO_IMPLEMENT(PostEffect, Object);

//------------------------------------------------------------------------------
PostEffect::PostEffect()
	: Object()
{
}

//------------------------------------------------------------------------------
PostEffect::~PostEffect()
{
}

//------------------------------------------------------------------------------
void PostEffect::initialize()
{
}

LN_NAMESPACE_END
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NeonUri.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-18 07:49:06 $
 *
 *  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_ucb.hxx"

#include <string.h>

#ifndef _RTL_URI_HXX_
#include <rtl/uri.hxx>
#endif
#ifndef _RTL_OUSTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _NEONURI_HXX_
#include "NeonUri.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif

#include "../inc/urihelper.hxx"

using namespace webdav_ucp;

    char *scheme;
    char *host, *userinfo;
    unsigned int port;
    char *path, *query, *fragment;

# if defined __SUNPRO_CC
// FIXME: not sure whether initializing a ne_uri statically is supposed to work
// the string fields of ne_uri are char*, not const char*
# pragma disable_warn
# endif

namespace {

const ne_uri g_sUriDefaultsHTTP  = { "http",
                                     NULL,
                                     NULL,
                                     DEFAULT_HTTP_PORT,
                                     NULL,
                                     NULL,
                                     NULL };
const ne_uri g_sUriDefaultsHTTPS = { "https",
                                     NULL,
                                     NULL,
                                     DEFAULT_HTTPS_PORT,
                                     NULL,
                                     NULL,
                                     NULL };
const ne_uri g_sUriDefaultsFTP   = { "ftp",
                                     NULL,
                                     NULL,
                                     DEFAULT_FTP_PORT,
                                     NULL,
                                     NULL,
                                     NULL };
} // namespace

# if defined __SUNPRO_CC
# pragma enable_warn
#endif

// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------

namespace {

//TODO! rtl::OString::matchIgnoreAsciiCaseAsciiL() missing
inline bool matchIgnoreAsciiCase(rtl::OString const & rStr1,
                                 sal_Char const * pStr2,
                                 sal_Int32 nStr2Len) SAL_THROW(())
{
    return
        rtl_str_shortenedCompareIgnoreAsciiCase_WithLength(
                rStr1.getStr(), rStr1.getLength(), pStr2, nStr2Len, nStr2Len)
            == 0;
}

}

NeonUri::NeonUri( const ne_uri * inUri )
    throw ( DAVException )
{
    if ( inUri == 0 )
        throw DAVException( DAVException::DAV_INVALID_ARG );

    char * uri = ne_uri_unparse( inUri );

    if ( uri == 0 )
        throw DAVException( DAVException::DAV_INVALID_ARG );

    init( rtl::OString( uri ), inUri );
    free( uri );

    calculateURI();
}

NeonUri::NeonUri( const rtl::OUString & inUri )
    throw ( DAVException )
{
    if ( inUri.getLength() <= 0 )
        throw DAVException( DAVException::DAV_INVALID_ARG );

    // #i77023#
    rtl::OUString aEscapedUri( ucb_impl::urihelper::encodeURI( inUri ) );

    rtl::OString theInputUri(
        aEscapedUri.getStr(), aEscapedUri.getLength(), RTL_TEXTENCODING_UTF8 );

    ne_uri theUri;
    if ( ne_uri_parse( theInputUri.getStr(), &theUri ) != 0 )
    {
        ne_uri_free( &theUri );
        throw DAVException( DAVException::DAV_INVALID_ARG );
    }

    init( theInputUri, &theUri );
    ne_uri_free( &theUri );

    calculateURI();
}

void NeonUri::init( const rtl::OString & rUri, const ne_uri * pUri )
{
    // Complete URI.
    const ne_uri * pUriDefs
        = matchIgnoreAsciiCase( rUri,
                                RTL_CONSTASCII_STRINGPARAM( "ftp:" ) ) ?
              &g_sUriDefaultsFTP :
          matchIgnoreAsciiCase( rUri,
                                RTL_CONSTASCII_STRINGPARAM( "https:" ) ) ?
              &g_sUriDefaultsHTTPS :
              &g_sUriDefaultsHTTP;

    mScheme   = rtl::OStringToOUString(
                    pUri->scheme ? pUri->scheme : pUriDefs->scheme,
                    RTL_TEXTENCODING_UTF8 );
    mUserInfo = rtl::OStringToOUString(
                    pUri->userinfo ? pUri->userinfo : pUriDefs->userinfo,
                    RTL_TEXTENCODING_UTF8 );
    mHostName = rtl::OStringToOUString(
                    pUri->host ? pUri->host : pUriDefs->host,
                    RTL_TEXTENCODING_UTF8 );
    mPort     = pUri->port > 0 ? pUri->port : pUriDefs->port;
    mPath     = rtl::OStringToOUString(
                    pUri->path ? pUri->path : pUriDefs->path,
                    RTL_TEXTENCODING_UTF8 );

    if ( pUri->query )
    {
        mPath += rtl::OUString::createFromAscii( "?" );
        mPath += rtl::OStringToOUString(
            pUri->query,  RTL_TEXTENCODING_UTF8 );
    }

    if ( pUri->fragment )
    {
        mPath += rtl::OUString::createFromAscii( "#" );
        mPath += rtl::OStringToOUString(
            pUri->fragment,  RTL_TEXTENCODING_UTF8 );
    }
}

// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonUri::~NeonUri( )
{
}

void NeonUri::calculateURI ()
{
    rtl::OUStringBuffer aBuf( mScheme );
    aBuf.appendAscii( "://" );
    if ( mUserInfo.getLength() > 0 )
    {
        //TODO! differentiate between empty and missing userinfo
        aBuf.append( mUserInfo );
        aBuf.appendAscii( "@" );
    }
    // Is host a numeric IPv6 address?
    if ( ( mHostName.indexOf( ':' ) != -1 ) &&
         ( mHostName[ 0 ] != sal_Unicode( '[' ) ) )
    {
        aBuf.appendAscii( "[" );
        aBuf.append( mHostName );
        aBuf.appendAscii( "]" );
    }
    else
    {
        aBuf.append( mHostName );
    }
    aBuf.appendAscii( ":" );
    aBuf.append( rtl::OUString::valueOf( mPort ) );
    aBuf.append( mPath );

    mURI = aBuf.makeStringAndClear();
}

::rtl::OUString NeonUri::GetPathBaseName () const
{
    sal_Int32 nPos = mPath.lastIndexOf ('/');
    sal_Int32 nTrail = 0;
    if (nPos == mPath.getLength () - 1)
    {
        // Trailing slash found. Skip.
        nTrail = 1;
        nPos = mPath.lastIndexOf ('/', nPos);
    }
    if (nPos != -1)
        return mPath.copy (nPos + 1, mPath.getLength () - nPos - 1 - nTrail);
    else
        return rtl::OUString::createFromAscii ("/");
}

bool NeonUri::operator== ( const NeonUri & rOther ) const
{
    return ( mURI == rOther.mURI );
}

::rtl::OUString NeonUri::GetPathBaseNameUnescaped () const
{
    return unescape( GetPathBaseName() );
}

::rtl::OUString NeonUri::GetPathDirName () const
{
    sal_Int32 nPos = mPath.lastIndexOf ('/');
    if (nPos == mPath.getLength () - 1)
    {
        // Trailing slash found. Skip.
        nPos = mPath.lastIndexOf ('/', nPos);
    }
    if (nPos != -1)
        return mPath.copy (0, nPos + 1);
    else
        return rtl::OUString::createFromAscii ("/");
}

void NeonUri::AppendPath (const rtl::OUString& rPath)
{
    if (mPath.lastIndexOf ('/') != mPath.getLength () - 1)
        mPath += rtl::OUString::createFromAscii ("/");

    mPath += rPath;
    calculateURI ();
};

// static
rtl::OUString NeonUri::escapeSegment( const rtl::OUString& segment )
{
    return rtl::Uri::encode( segment,
                             rtl_UriCharClassPchar,
                             rtl_UriEncodeIgnoreEscapes,
                             RTL_TEXTENCODING_UTF8 );
}

// static
rtl::OUString NeonUri::unescape( const rtl::OUString& segment )
{
    return rtl::Uri::decode( segment,
                             rtl_UriDecodeWithCharset,
                             RTL_TEXTENCODING_UTF8 );
}

// static
rtl::OUString NeonUri::makeConnectionEndPointString(
                                const rtl::OUString & rHostName, int nPort )
{
    rtl::OUStringBuffer aBuf;

    // Is host a numeric IPv6 address?
    if ( ( rHostName.indexOf( ':' ) != -1 ) &&
         ( rHostName[ 0 ] != sal_Unicode( '[' ) ) )
    {
        aBuf.appendAscii( "[" );
        aBuf.append( rHostName );
        aBuf.appendAscii( "]" );
    }
    else
    {
        aBuf.append( rHostName );
    }

    if ( ( nPort != DEFAULT_HTTP_PORT ) && ( nPort != DEFAULT_HTTPS_PORT ) )
    {
        aBuf.appendAscii( ":" );
        aBuf.append( rtl::OUString::valueOf( sal_Int32( nPort ) ) );
    }
    return aBuf.makeStringAndClear();
}

<commit_msg>INTEGRATION: CWS jl83 (1.19.24); FILE MERGED 2007/11/29 13:07:46 kso 1.19.24.1: #i83870# - Fixed NeonUri::GetPathBaseName().<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NeonUri.cxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: vg $ $Date: 2007-12-07 10:22:24 $
 *
 *  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_ucb.hxx"

#include <string.h>

#ifndef _RTL_URI_HXX_
#include <rtl/uri.hxx>
#endif
#ifndef _RTL_OUSTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _NEONURI_HXX_
#include "NeonUri.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif

#include "../inc/urihelper.hxx"

using namespace webdav_ucp;

    char *scheme;
    char *host, *userinfo;
    unsigned int port;
    char *path, *query, *fragment;

# if defined __SUNPRO_CC
// FIXME: not sure whether initializing a ne_uri statically is supposed to work
// the string fields of ne_uri are char*, not const char*
# pragma disable_warn
# endif

namespace {

const ne_uri g_sUriDefaultsHTTP  = { "http",
                                     NULL,
                                     NULL,
                                     DEFAULT_HTTP_PORT,
                                     NULL,
                                     NULL,
                                     NULL };
const ne_uri g_sUriDefaultsHTTPS = { "https",
                                     NULL,
                                     NULL,
                                     DEFAULT_HTTPS_PORT,
                                     NULL,
                                     NULL,
                                     NULL };
const ne_uri g_sUriDefaultsFTP   = { "ftp",
                                     NULL,
                                     NULL,
                                     DEFAULT_FTP_PORT,
                                     NULL,
                                     NULL,
                                     NULL };
} // namespace

# if defined __SUNPRO_CC
# pragma enable_warn
#endif

// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------

namespace {

//TODO! rtl::OString::matchIgnoreAsciiCaseAsciiL() missing
inline bool matchIgnoreAsciiCase(rtl::OString const & rStr1,
                                 sal_Char const * pStr2,
                                 sal_Int32 nStr2Len) SAL_THROW(())
{
    return
        rtl_str_shortenedCompareIgnoreAsciiCase_WithLength(
                rStr1.getStr(), rStr1.getLength(), pStr2, nStr2Len, nStr2Len)
            == 0;
}

}

NeonUri::NeonUri( const ne_uri * inUri )
    throw ( DAVException )
{
    if ( inUri == 0 )
        throw DAVException( DAVException::DAV_INVALID_ARG );

    char * uri = ne_uri_unparse( inUri );

    if ( uri == 0 )
        throw DAVException( DAVException::DAV_INVALID_ARG );

    init( rtl::OString( uri ), inUri );
    free( uri );

    calculateURI();
}

NeonUri::NeonUri( const rtl::OUString & inUri )
    throw ( DAVException )
{
    if ( inUri.getLength() <= 0 )
        throw DAVException( DAVException::DAV_INVALID_ARG );

    // #i77023#
    rtl::OUString aEscapedUri( ucb_impl::urihelper::encodeURI( inUri ) );

    rtl::OString theInputUri(
        aEscapedUri.getStr(), aEscapedUri.getLength(), RTL_TEXTENCODING_UTF8 );

    ne_uri theUri;
    if ( ne_uri_parse( theInputUri.getStr(), &theUri ) != 0 )
    {
        ne_uri_free( &theUri );
        throw DAVException( DAVException::DAV_INVALID_ARG );
    }

    init( theInputUri, &theUri );
    ne_uri_free( &theUri );

    calculateURI();
}

void NeonUri::init( const rtl::OString & rUri, const ne_uri * pUri )
{
    // Complete URI.
    const ne_uri * pUriDefs
        = matchIgnoreAsciiCase( rUri,
                                RTL_CONSTASCII_STRINGPARAM( "ftp:" ) ) ?
              &g_sUriDefaultsFTP :
          matchIgnoreAsciiCase( rUri,
                                RTL_CONSTASCII_STRINGPARAM( "https:" ) ) ?
              &g_sUriDefaultsHTTPS :
              &g_sUriDefaultsHTTP;

    mScheme   = rtl::OStringToOUString(
                    pUri->scheme ? pUri->scheme : pUriDefs->scheme,
                    RTL_TEXTENCODING_UTF8 );
    mUserInfo = rtl::OStringToOUString(
                    pUri->userinfo ? pUri->userinfo : pUriDefs->userinfo,
                    RTL_TEXTENCODING_UTF8 );
    mHostName = rtl::OStringToOUString(
                    pUri->host ? pUri->host : pUriDefs->host,
                    RTL_TEXTENCODING_UTF8 );
    mPort     = pUri->port > 0 ? pUri->port : pUriDefs->port;
    mPath     = rtl::OStringToOUString(
                    pUri->path ? pUri->path : pUriDefs->path,
                    RTL_TEXTENCODING_UTF8 );

    if ( pUri->query )
    {
        mPath += rtl::OUString::createFromAscii( "?" );
        mPath += rtl::OStringToOUString(
            pUri->query,  RTL_TEXTENCODING_UTF8 );
    }

    if ( pUri->fragment )
    {
        mPath += rtl::OUString::createFromAscii( "#" );
        mPath += rtl::OStringToOUString(
            pUri->fragment,  RTL_TEXTENCODING_UTF8 );
    }
}

// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonUri::~NeonUri( )
{
}

void NeonUri::calculateURI ()
{
    rtl::OUStringBuffer aBuf( mScheme );
    aBuf.appendAscii( "://" );
    if ( mUserInfo.getLength() > 0 )
    {
        //TODO! differentiate between empty and missing userinfo
        aBuf.append( mUserInfo );
        aBuf.appendAscii( "@" );
    }
    // Is host a numeric IPv6 address?
    if ( ( mHostName.indexOf( ':' ) != -1 ) &&
         ( mHostName[ 0 ] != sal_Unicode( '[' ) ) )
    {
        aBuf.appendAscii( "[" );
        aBuf.append( mHostName );
        aBuf.appendAscii( "]" );
    }
    else
    {
        aBuf.append( mHostName );
    }
    aBuf.appendAscii( ":" );
    aBuf.append( rtl::OUString::valueOf( mPort ) );
    aBuf.append( mPath );

    mURI = aBuf.makeStringAndClear();
}

::rtl::OUString NeonUri::GetPathBaseName () const
{
    sal_Int32 nPos = mPath.lastIndexOf ('/');
    sal_Int32 nTrail = 0;
    if (nPos == mPath.getLength () - 1)
    {
        // Trailing slash found. Skip.
        nTrail = 1;
        nPos = mPath.lastIndexOf ('/', nPos);
    }
    if (nPos != -1)
    {
        rtl::OUString aTemp(
            mPath.copy (nPos + 1, mPath.getLength () - nPos - 1 - nTrail) );

        // query, fragment present?
        nPos = aTemp.indexOf( '?' );
        if ( nPos == -1 )
            nPos = aTemp.indexOf( '#' );

        if ( nPos != -1 )
            aTemp = aTemp.copy( 0, nPos );

        return aTemp;
    }
    else
        return rtl::OUString::createFromAscii ("/");
}

bool NeonUri::operator== ( const NeonUri & rOther ) const
{
    return ( mURI == rOther.mURI );
}

::rtl::OUString NeonUri::GetPathBaseNameUnescaped () const
{
    return unescape( GetPathBaseName() );
}

::rtl::OUString NeonUri::GetPathDirName () const
{
    sal_Int32 nPos = mPath.lastIndexOf ('/');
    if (nPos == mPath.getLength () - 1)
    {
        // Trailing slash found. Skip.
        nPos = mPath.lastIndexOf ('/', nPos);
    }
    if (nPos != -1)
        return mPath.copy (0, nPos + 1);
    else
        return rtl::OUString::createFromAscii ("/");
}

void NeonUri::AppendPath (const rtl::OUString& rPath)
{
    if (mPath.lastIndexOf ('/') != mPath.getLength () - 1)
        mPath += rtl::OUString::createFromAscii ("/");

    mPath += rPath;
    calculateURI ();
};

// static
rtl::OUString NeonUri::escapeSegment( const rtl::OUString& segment )
{
    return rtl::Uri::encode( segment,
                             rtl_UriCharClassPchar,
                             rtl_UriEncodeIgnoreEscapes,
                             RTL_TEXTENCODING_UTF8 );
}

// static
rtl::OUString NeonUri::unescape( const rtl::OUString& segment )
{
    return rtl::Uri::decode( segment,
                             rtl_UriDecodeWithCharset,
                             RTL_TEXTENCODING_UTF8 );
}

// static
rtl::OUString NeonUri::makeConnectionEndPointString(
                                const rtl::OUString & rHostName, int nPort )
{
    rtl::OUStringBuffer aBuf;

    // Is host a numeric IPv6 address?
    if ( ( rHostName.indexOf( ':' ) != -1 ) &&
         ( rHostName[ 0 ] != sal_Unicode( '[' ) ) )
    {
        aBuf.appendAscii( "[" );
        aBuf.append( rHostName );
        aBuf.appendAscii( "]" );
    }
    else
    {
        aBuf.append( rHostName );
    }

    if ( ( nPort != DEFAULT_HTTP_PORT ) && ( nPort != DEFAULT_HTTPS_PORT ) )
    {
        aBuf.appendAscii( ":" );
        aBuf.append( rtl::OUString::valueOf( sal_Int32( nPort ) ) );
    }
    return aBuf.makeStringAndClear();
}

<|endoftext|>


<commit_before>/**
 * Created by ionagamed on 28.10.16
 */

int main(int argc, char** argv) {

}
<commit_msg>add frontend<commit_after>#include <initializer_list>
#include <cstdio>
#include <string>
#include <stdarg.h>

int test_deflate(FILE* input, FILE* output) {
	printf("deflate\n");
	return 0;
}
int test_inflate(FILE* input, FILE* output) {
	printf("inflate\n");
	return 0;
}

#define BACKEND_DEFLATE test_deflate
#define BACKEND_INFLATE test_inflate

bool verbose = false;
size_t eprintf(const char* fmt, ...) {
	if (verbose) {
		va_list vp;
		va_start(vp, fmt);
		vprintf(fmt, vp);
	}
}

void usage(char* name) {
	printf("Usage:\n"
		"%s <x|p> [-v|--verbose] [input file] [-o <output file>]\n"
		"First argument without a leading dash must be x (extract) or p (pack)",
		name);
	exit(0);
}

int main(int argc, char** argv) {
	char* name = argv[0];
	if (argc < 2 || argc > 5) {
		usage(name);
	}

	char action = 'n';
	std::string inputFilename;
	std::string outputFilename;

	argc--; argv++;
	while (argc) {
		std::string arg = argv[0];
		eprintf("Got commandline arg '%s'\n", argv[0]);
		if (arg == "-v" || arg == "--verbose") {
			verbose = true;
		} else if (arg == "-o") {
			outputFilename = argv[1];
			argc--; argv++;
		} else {
			if (action == 'n' && arg != "x" && arg != "e") {
				usage(name);
			} else if (action == 'n' && (arg == "x" || arg == "e")) {
				action = arg[0];
			} else if (action != 'n') {
				if (inputFilename.empty()) {
					inputFilename = arg;
				}
			}
		}
		argc--; argv++;
	}

	eprintf("Input from: ");
	FILE* input;
	if (inputFilename.empty()) {
		eprintf("stdin\n");
		input = stdin;
	} else {
		eprintf("file '%s'\n", inputFilename.c_str());
		input = fopen(inputFilename.c_str(), "rb");
	}

	eprintf("Output to: ");
	FILE* output;
	if (outputFilename.empty()) {
		eprintf("stdout\n");
		output = stdout;
	} else {
		eprintf("file '%s'\n", outputFilename.c_str());
		output = fopen(outputFilename.c_str(), "wb");
	}

	if (action == 'p') {
		eprintf("Beginning deflate\n");
		return BACKEND_DEFLATE(input, output);
	} else if (action == 'x') {
		eprintf("Beginning inflate\n");
		return BACKEND_INFLATE(input, output);
	}
}
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <cstdint>
#include <cstdlib>

#include "tensorflow/core/platform/status.h"

// This is a fuzzer for `tensorflow::Status`. Since `Status` is used almost
// everywhere, we need to ensure that the common functionality is safe. We don't
// expect many crashes from this fuzzer since we only create a status and then
// look at the error message from it but this is a good test of the fuzzing
// infrastructure, with minimal dependencies (thus, it is a good test to weed
// out linker bloat and other linker issues).

namespace {

tensorflow::error::Code BuildRandomErrorCode(uint8_t a, uint8_t b, uint8_t c,
                                             uint8_t d) {
  int code = (a << 24) | (b << 16) | (c << 8) | d;

  // We cannot build a `Status` with error_code of 0 and a message, so force
  // error code to be non-zero.
  if (code == 0) {
    return tensorflow::error::UNKNOWN;
  }

  return static_cast<tensorflow::error::Code>(code);
}

std::string GetRandomErrorString(const uint8_t *data, size_t size) {
  const char *p = reinterpret_cast<const char *>(data);
  return std::string(p, size);
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  // TODO(mihaimaruseac): Use `FuzzedDataProvider` and then make these `const`
  tensorflow::error::Code error_code;
  std::string error_message;
  if (size < 4) {
    error_code = BuildRandomErrorCode(0, 0, 0, 0);
    error_message = GetRandomErrorString(data, size);
  } else {
    error_code = BuildRandomErrorCode(data[0], data[1], data[2], data[3]);
    error_message = GetRandomErrorString(data + 4, size - 4);
  }

  tensorflow::Status s = tensorflow::Status(error_code, error_message);
  const std::string actual_message = s.ToString();
  const std::size_t pos = actual_message.rfind(error_message);
  assert(pos != std::string::npos);  // Suffix is error message
  assert(pos > 0);                   // Prefix is error code

  // In some build configurations `assert` is a no-op. This causes `pos` to be
  // unused and then produces an error if also compiling with `-Werror`.
  (void)pos;

  return 0;
}

}  // namespace
<commit_msg>Added FuzzedDataProvider to split fuzzer data<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <cstdint>
#include <cstdlib>

#include "tensorflow/core/platform/status.h"

#include <fuzzer/FuzzedDataProvider.h>

// This is a fuzzer for `tensorflow::Status`. Since `Status` is used almost
// everywhere, we need to ensure that the common functionality is safe. We don't
// expect many crashes from this fuzzer since we only create a status and then
// look at the error message from it but this is a good test of the fuzzing
// infrastructure, with minimal dependencies (thus, it is a good test to weed
// out linker bloat and other linker issues).

namespace {

tensorflow::error::Code BuildRandomErrorCode(uint32_t code){

  // We cannot build a `Status` with error_code of 0 and a message, so force
  // error code to be non-zero.
  if (code == 0) {
    return tensorflow::error::UNKNOWN;
  }

  return static_cast<tensorflow::error::Code>(code);
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  tensorflow::error::Code error_code;
  std::string error_message;

  FuzzedDataProvider fuzzed_data(data, size);

  uint32_t code = fuzzed_data.ConsumeIntegral<uint32_t>();
  error_code = BuildRandomErrorCode(code);

  error_message = fuzzed_data.ConsumeRemainingBytesAsString();

  tensorflow::Status s = tensorflow::Status(error_code, error_message);
  const std::string actual_message = s.ToString();
  const std::size_t pos = actual_message.rfind(error_message);
  assert(pos != std::string::npos);  // Suffix is error message
  assert(pos > 0);                   // Prefix is error code

  // In some build configurations `assert` is a no-op. This causes `pos` to be
  // unused and then produces an error if also compiling with `-Werror`.
  (void)pos;

  return 0;
}

}  // namespace
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * 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 text-field-example.cpp
 * @brief Basic usage of TextField control
 */

// EXTERNAL INCLUDES
#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/devel-api/controls/popup/popup.h>
#include <iostream>
#include <dali/public-api/events/touch-point.h>

// INTERNAL INCLUDES
#include "shared/multi-language-strings.h"
#include "shared/view.h"

using namespace Dali;
using namespace Dali::Toolkit;
using namespace MultiLanguageStrings;

namespace
{

  const char* const FOLDER_ICON_IMAGE = DALI_IMAGE_DIR "folder_appicon_empty_bg.png";

  const float BORDER_WIDTH = 4.0f;

  const Vector3 POPUP_SIZE_FACTOR_TO_PARENT = Vector3( 0.0, 0.25, 0.0 );

} // unnamed namespace

/**
 * @brief The main class of the demo.
 */
class TextFieldExample : public ConnectionTracker
{
public:

  TextFieldExample( Application& application )
  : mApplication( application )
  {
    // Connect to the Application's Init signal
    mApplication.InitSignal().Connect( this, &TextFieldExample::Create );
  }

  ~TextFieldExample()
  {
    // Nothing to do here.
  }

  /**
   * One-time setup in response to Application InitSignal.
   */
  void Create( Application& application )
  {
    Stage stage = Stage::GetCurrent();

    stage.SetBackgroundColor( Vector4( 0.04f, 0.345f, 0.392f, 1.0f ) );
    stage.KeyEventSignal().Connect(this, &TextFieldExample::OnKeyEvent);

    mButton = CreateFolderButton();
    mButton.ClickedSignal().Connect( this, &TextFieldExample::OnButtonClicked );
    stage.Add( mButton );
  }

  PushButton CreateFolderButton()
  {
    PushButton button = PushButton::New();
    ResourceImage image = ResourceImage::New( FOLDER_ICON_IMAGE );
    ImageActor folderButton = ImageActor::New( image );
    folderButton.SetColor( Color::WHITE );
    button.SetButtonImage( folderButton );
    button.SetSelectedImage( Actor() );
    button.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    button.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS );
    button.SetSize( image.GetWidth(), image.GetHeight() );

    return button;
  }

  bool OnButtonClicked( Toolkit::Button button )
  {
    Stage stage = Stage::GetCurrent();
    Vector2 stageSize = stage.GetSize();

    // Launch a pop-up containing TextField
    mField = CreateTextField( stageSize, mButtonLabel );
    mPopup = CreatePopup( stageSize.width * 0.8f );
    mPopup.Add( mField );
    mPopup.OutsideTouchedSignal().Connect( this, &TextFieldExample::OnPopupOutsideTouched );
    mPopup.Show();

    return true;
  }

  TextField CreateTextField( const Vector2& stageSize, const std::string& text )
  {
    TextField field = TextField::New();
    field.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    field.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
    field.SetResizePolicy( ResizePolicy::DIMENSION_DEPENDENCY, Dimension::HEIGHT );
    field.SetProperty( TextField::Property::TEXT, text );
    field.SetProperty( TextField::Property::TEXT_COLOR, Vector4( 0.0f, 1.0f, 1.0f, 1.0f ) ); // CYAN
    field.SetProperty( TextField::Property::PLACEHOLDER_TEXT, "Unnamed folder" );
    field.SetProperty( TextField::Property::PLACEHOLDER_TEXT_FOCUSED, "Enter folder name." );
    field.SetProperty( TextField::Property::DECORATION_BOUNDING_BOX, Rect<int>( BORDER_WIDTH, BORDER_WIDTH, stageSize.width - BORDER_WIDTH*2, stageSize.height - BORDER_WIDTH*2 ) );

    return field;
  }

  Popup CreatePopup( float width )
  {
    Popup popup = Popup::New();
    popup.SetParentOrigin( ParentOrigin::CENTER );
    popup.SetAnchorPoint( AnchorPoint::CENTER );
    popup.SetSize( width, 0.0f );
    popup.HideTail();
    popup.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::HEIGHT );
    popup.SetSizeModeFactor( POPUP_SIZE_FACTOR_TO_PARENT );
    popup.TouchedSignal().Connect( this, &TextFieldExample::OnPopupTouched );

    return popup;
  }

  void OnPopupOutsideTouched()
  {
    // Update the folder text
    if( mButton && mField )
    {
      Property::Value text = mField.GetProperty( TextField::Property::TEXT );
      mButtonLabel = text.Get< std::string >();
      mButton.SetLabel( mButtonLabel );
    }

    // Hide & discard the pop-up
    if( mPopup )
    {
      mPopup.Hide();
    }
    mField.Reset();
    mPopup.Reset();
  }

  bool OnPopupTouched( Actor actor, const TouchEvent& event )
  {
    // End edit mode for TextField if parent Popup touched.
    if(event.GetPointCount() > 0)
    {
      const TouchPoint& point = event.GetPoint(0);
      switch(point.state)
      {
        case TouchPoint::Down:
        {
          // Update the folder text and lose focus for Key events
          if( mButton && mField )
          {
            Property::Value text = mField.GetProperty( TextField::Property::TEXT );
            mButtonLabel = text.Get< std::string >();
            mButton.SetLabel( mButtonLabel );
            mField.ClearKeyInputFocus();
          }
          break;
        }
        default:
        {
          break;
        }
      } // end switch
    }

    return true;
  }

  /**
   * Main key event handler
   */
  void OnKeyEvent(const KeyEvent& event)
  {
    if(event.state == KeyEvent::Down)
    {
      if( IsKey( event, DALI_KEY_ESCAPE) || IsKey( event, DALI_KEY_BACK ) )
      {
        mApplication.Quit();
      }
    }
  }

private:

  Application& mApplication;

  // This button launches a pop-up containing TextField
  PushButton mButton;
  std::string mButtonLabel;

  // Pop-up contents
  TextField mField;
  Popup mPopup;
};

void RunTest( Application& application )
{
  TextFieldExample test( application );

  application.MainLoop();
}

/** Entry point for Linux & Tizen applications */
int main( int argc, char **argv )
{
  Application application = Application::New( &argc, &argv, DALI_DEMO_THEME_PATH );

  RunTest( application );

  return 0;
}
<commit_msg>Fixed memory leak in text-field demo<commit_after>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * 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 text-field-example.cpp
 * @brief Basic usage of TextField control
 */

// EXTERNAL INCLUDES
#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/devel-api/controls/popup/popup.h>
#include <iostream>
#include <dali/public-api/events/touch-point.h>

// INTERNAL INCLUDES
#include "shared/multi-language-strings.h"
#include "shared/view.h"

using namespace Dali;
using namespace Dali::Toolkit;
using namespace MultiLanguageStrings;

namespace
{

  const char* const FOLDER_ICON_IMAGE = DALI_IMAGE_DIR "folder_appicon_empty_bg.png";

  const float BORDER_WIDTH = 4.0f;

  const Vector3 POPUP_SIZE_FACTOR_TO_PARENT = Vector3( 0.0, 0.25, 0.0 );

} // unnamed namespace

/**
 * @brief The main class of the demo.
 */
class TextFieldExample : public ConnectionTracker
{
public:

  TextFieldExample( Application& application )
  : mApplication( application )
  {
    // Connect to the Application's Init signal
    mApplication.InitSignal().Connect( this, &TextFieldExample::Create );
  }

  ~TextFieldExample()
  {
    // Nothing to do here.
  }

  /**
   * One-time setup in response to Application InitSignal.
   */
  void Create( Application& application )
  {
    Stage stage = Stage::GetCurrent();

    stage.SetBackgroundColor( Vector4( 0.04f, 0.345f, 0.392f, 1.0f ) );
    stage.KeyEventSignal().Connect(this, &TextFieldExample::OnKeyEvent);

    mButton = CreateFolderButton();
    mButton.ClickedSignal().Connect( this, &TextFieldExample::OnButtonClicked );
    stage.Add( mButton );
  }

  PushButton CreateFolderButton()
  {
    PushButton button = PushButton::New();
    ResourceImage image = ResourceImage::New( FOLDER_ICON_IMAGE );
    ImageActor folderButton = ImageActor::New( image );
    folderButton.SetColor( Color::WHITE );
    button.SetButtonImage( folderButton );
    button.SetSelectedImage( Actor() );
    button.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    button.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS );
    button.SetSize( image.GetWidth(), image.GetHeight() );

    return button;
  }

  bool OnButtonClicked( Toolkit::Button button )
  {
    Stage stage = Stage::GetCurrent();
    Vector2 stageSize = stage.GetSize();

    // Remove previously hidden pop-up
    UnparentAndReset(mPopup);

    // Launch a pop-up containing TextField
    mField = CreateTextField( stageSize, mButtonLabel );
    mPopup = CreatePopup( stageSize.width * 0.8f );
    mPopup.Add( mField );
    mPopup.OutsideTouchedSignal().Connect( this, &TextFieldExample::OnPopupOutsideTouched );
    mPopup.Show();

    return true;
  }

  TextField CreateTextField( const Vector2& stageSize, const std::string& text )
  {
    TextField field = TextField::New();
    field.SetAnchorPoint( AnchorPoint::TOP_LEFT );
    field.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
    field.SetResizePolicy( ResizePolicy::DIMENSION_DEPENDENCY, Dimension::HEIGHT );
    field.SetProperty( TextField::Property::TEXT, text );
    field.SetProperty( TextField::Property::TEXT_COLOR, Vector4( 0.0f, 1.0f, 1.0f, 1.0f ) ); // CYAN
    field.SetProperty( TextField::Property::PRIMARY_CURSOR_COLOR, Color::WHITE );
    field.SetProperty( TextField::Property::PLACEHOLDER_TEXT, "Unnamed folder" );
    field.SetProperty( TextField::Property::PLACEHOLDER_TEXT_FOCUSED, "Enter folder name." );
    field.SetProperty( TextField::Property::DECORATION_BOUNDING_BOX, Rect<int>( BORDER_WIDTH, BORDER_WIDTH, stageSize.width - BORDER_WIDTH*2, stageSize.height - BORDER_WIDTH*2 ) );

    return field;
  }

  Popup CreatePopup( float width )
  {
    Popup popup = Popup::New();
    popup.SetParentOrigin( ParentOrigin::CENTER );
    popup.SetAnchorPoint( AnchorPoint::CENTER );
    popup.SetSize( width, 0.0f );
    popup.HideTail();
    popup.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::HEIGHT );
    popup.SetSizeModeFactor( POPUP_SIZE_FACTOR_TO_PARENT );
    popup.TouchedSignal().Connect( this, &TextFieldExample::OnPopupTouched );

    return popup;
  }

  void OnPopupOutsideTouched()
  {
    // Update the folder text
    if( mButton && mField )
    {
      Property::Value text = mField.GetProperty( TextField::Property::TEXT );
      mButtonLabel = text.Get< std::string >();
      mButton.SetLabel( mButtonLabel );
    }

    // Hide & discard the pop-up
    if( mPopup )
    {
      mPopup.Hide();
    }
    mField.Reset();
  }

  bool OnPopupTouched( Actor actor, const TouchEvent& event )
  {
    // End edit mode for TextField if parent Popup touched.
    if(event.GetPointCount() > 0)
    {
      const TouchPoint& point = event.GetPoint(0);
      switch(point.state)
      {
        case TouchPoint::Down:
        {
          // Update the folder text and lose focus for Key events
          if( mButton && mField )
          {
            Property::Value text = mField.GetProperty( TextField::Property::TEXT );
            mButtonLabel = text.Get< std::string >();
            mButton.SetLabel( mButtonLabel );
            mField.ClearKeyInputFocus();
          }
          break;
        }
        default:
        {
          break;
        }
      } // end switch
    }

    return true;
  }

  /**
   * Main key event handler
   */
  void OnKeyEvent(const KeyEvent& event)
  {
    if(event.state == KeyEvent::Down)
    {
      if( IsKey( event, DALI_KEY_ESCAPE) || IsKey( event, DALI_KEY_BACK ) )
      {
        mApplication.Quit();
      }
    }
  }

private:

  Application& mApplication;

  // This button launches a pop-up containing TextField
  PushButton mButton;
  std::string mButtonLabel;

  // Pop-up contents
  TextField mField;
  Popup mPopup;
};

void RunTest( Application& application )
{
  TextFieldExample test( application );

  application.MainLoop();
}

/** Entry point for Linux & Tizen applications */
int main( int argc, char **argv )
{
  Application application = Application::New( &argc, &argv, DALI_DEMO_THEME_PATH );

  RunTest( application );

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>Removed unnecessary `#include` line.<commit_after><|endoftext|>


<commit_before>/* mbed Microcontroller Library
 * Copyright (c) 2018 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "mbed.h"
#include "mbed_error.h"
#include "mbed_crash_data_offsets.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"

#if !MBED_CONF_PLATFORM_CRASH_CAPTURE_ENABLED
#error [NOT_SUPPORTED] crash_reporting test not supported
#endif

#define MSG_VALUE_DUMMY "0"
#define MSG_VALUE_LEN 32
#define MSG_KEY_LEN 64

#define MSG_KEY_DEVICE_READY "crash_reporting_ready"
#define MSG_KEY_DEVICE_ERROR "crash_reporting_inject_error"

static mbed_error_ctx saved_error_ctx = {0};

void mbed_error_reboot_callback(mbed_error_ctx *error_context)
{

    TEST_ASSERT_EQUAL_UINT((uint32_t)error_context, ERROR_CONTEXT_LOCATION);
    memcpy(&saved_error_ctx, error_context, sizeof(mbed_error_ctx));
    mbed_reset_reboot_error_info();

    TEST_ASSERT_EQUAL_UINT(MBED_ERROR_OUT_OF_MEMORY, saved_error_ctx.error_status);
    TEST_ASSERT_EQUAL_UINT(1, saved_error_ctx.error_reboot_count);

    //Send the ready msg to host to indicate test pass
    greentea_send_kv(MSG_KEY_DEVICE_READY, MSG_VALUE_DUMMY);
}

void test_crash_reporting()
{
    //Clear any previous status
    mbed_reset_reboot_error_info();

    // Report readiness
    greentea_send_kv(MSG_KEY_DEVICE_READY, MSG_VALUE_DUMMY);

    static char _key[MSG_KEY_LEN + 1] = { };
    static char _value[MSG_VALUE_LEN + 1] = { };

    greentea_parse_kv(_key, _value, MSG_KEY_LEN, MSG_VALUE_LEN);
    if (strcmp(_key, MSG_KEY_DEVICE_ERROR) == 0) {
        MBED_ERROR1(MBED_ERROR_OUT_OF_MEMORY, "Executing crash reporting test.", 0xDEADBAD);
        TEST_ASSERT_MESSAGE(0, "crash_reporting() error call failed.");
    }
    TEST_ASSERT_MESSAGE(0, "Unexpected message received.");
}

int main(void)
{
    GREENTEA_SETUP(40, "crash_reporting");
    test_crash_reporting();
    GREENTEA_TESTSUITE_RESULT(0);

    return 0;
}
<commit_msg>Add debug prints to triage the test timeouts<commit_after>/* mbed Microcontroller Library
 * Copyright (c) 2018 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "mbed.h"
#include "mbed_error.h"
#include "mbed_crash_data_offsets.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"

#if !MBED_CONF_PLATFORM_CRASH_CAPTURE_ENABLED
#error [NOT_SUPPORTED] crash_reporting test not supported
#endif

#define MSG_VALUE_DUMMY "0"
#define MSG_VALUE_LEN 32
#define MSG_KEY_LEN 64

#define MSG_KEY_DEVICE_READY "crash_reporting_ready"
#define MSG_KEY_DEVICE_ERROR "crash_reporting_inject_error"

static mbed_error_ctx saved_error_ctx = {0};

void mbed_error_reboot_callback(mbed_error_ctx *error_context)
{

    TEST_ASSERT_EQUAL_UINT((uint32_t)error_context, ERROR_CONTEXT_LOCATION);
    memcpy(&saved_error_ctx, error_context, sizeof(mbed_error_ctx));
    mbed_reset_reboot_error_info();

    TEST_ASSERT_EQUAL_UINT(MBED_ERROR_OUT_OF_MEMORY, saved_error_ctx.error_status);
    TEST_ASSERT_EQUAL_UINT(1, saved_error_ctx.error_reboot_count);

    //Send the ready msg to host to indicate test pass
    greentea_send_kv(MSG_KEY_DEVICE_READY, MSG_VALUE_DUMMY);
}

void test_crash_reporting()
{
    //Clear any previous status
    mbed_reset_reboot_error_info();

    // Report readiness
    greentea_send_kv(MSG_KEY_DEVICE_READY, MSG_VALUE_DUMMY);
    printf("\nMessage sent: %s\n", MSG_KEY_DEVICE_READY);

    static char _key[MSG_KEY_LEN + 1] = { };
    static char _value[MSG_VALUE_LEN + 1] = { };

    printf("\nWaiting for crash inject error message: %s\n", MSG_KEY_DEVICE_ERROR);
    greentea_parse_kv(_key, _value, MSG_KEY_LEN, MSG_VALUE_LEN);
    printf("\nCrash inject error message received\n");

    if (strcmp(_key, MSG_KEY_DEVICE_ERROR) == 0) {
        printf("\nForcing error\n");
        MBED_ERROR1(MBED_ERROR_OUT_OF_MEMORY, "Executing crash reporting test.", 0xDEADBAD);
        TEST_ASSERT_MESSAGE(0, "crash_reporting() error call failed.");
    }
    TEST_ASSERT_MESSAGE(0, "Unexpected message received.");
}

int main(void)
{
    GREENTEA_SETUP(40, "crash_reporting");
    test_crash_reporting();
    GREENTEA_TESTSUITE_RESULT(0);

    return 0;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling | FileCheck %s
"simple"
//CHECK: (const char [7])
"It's me"
//CHECK: (const char [8]) "It's me"
"Luke, I'm your (father({}{["
//CHECK: const char [28]) "Luke, I'm your (father({}{["
("http://foo/bar/whatever")
//CHECK: (const char [24]) "http://foo/bar/whatever"
("http://foo.bar/whatever")
//CHECK: (const char [24]) "http://foo.bar/whatever"
.q
<commit_msg>Add the expected string also.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling | FileCheck %s
"simple"
//CHECK: (const char [7]) "simple"
"It's me"
//CHECK: (const char [8]) "It's me"
"Luke, I'm your (father({}{["
//CHECK: const char [28]) "Luke, I'm your (father({}{["
("http://foo/bar/whatever")
//CHECK: (const char [24]) "http://foo/bar/whatever"
("http://foo.bar/whatever")
//CHECK: (const char [24]) "http://foo.bar/whatever"
.q
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/renderer_host/clipboard_message_filter.h"

#include "chrome/browser/browser_process.h"
#include "chrome/browser/clipboard_dispatcher.h"
#include "chrome/common/clipboard_messages.h"
#include "googleurl/src/gurl.h"
#include "ipc/ipc_message_macros.h"

namespace {

// Completes a clipboard write initiated by the renderer. The write must be
// performed on the UI thread because the clipboard service from the IO thread
// cannot create windows so it cannot be the "owner" of the clipboard's
// contents.
class WriteClipboardTask : public Task {
 public:
  explicit WriteClipboardTask(ui::Clipboard::ObjectMap* objects)
      : objects_(objects) {}
  ~WriteClipboardTask() {}

  void Run() {
    g_browser_process->clipboard()->WriteObjects(*objects_.get());
  }

 private:
  scoped_ptr<ui::Clipboard::ObjectMap> objects_;
};

}  // namespace

ClipboardMessageFilter::ClipboardMessageFilter() {
}

void ClipboardMessageFilter::OverrideThreadForMessage(
    const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(USE_X11)
  if (message.type() == ViewHostMsg_ClipboardHostMsg_ReadImage::ID)
    *thread = BrowserThread::BACKGROUND_X11;
  else if (IPC_MESSAGE_CLASS(message) == ClipboardMsgStart)
    *thread = BrowserThread::UI;
#endif
}

bool ClipboardMessageFilter::OnMessageReceived(const IPC::Message& message,
                                               bool* message_was_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(ClipboardMessageFilter, message, *message_was_ok)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsAsync, OnWriteObjectsAsync)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsSync, OnWriteObjectsSync)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_IsFormatAvailable, OnIsFormatAvailable)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadText, OnReadText)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAsciiText, OnReadAsciiText)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadHTML, OnReadHTML)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadImage, OnReadImage)
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_FindPboardWriteStringAsync,
                        OnFindPboardWriteString)
#endif
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAvailableTypes,
                        OnReadAvailableTypes)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadData, OnReadData)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadFilenames, OnReadFilenames)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

ClipboardMessageFilter::~ClipboardMessageFilter() {
}

void ClipboardMessageFilter::OnWriteObjectsSync(
    const ui::Clipboard::ObjectMap& objects,
    base::SharedMemoryHandle bitmap_handle) {
  DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle))
      << "Bad bitmap handle";
  // We cannot write directly from the IO thread, and cannot service the IPC
  // on the UI thread. We'll copy the relevant data and get a handle to any
  // shared memory so it doesn't go away when we resume the renderer, and post
  // a task to perform the write on the UI thread.
  ui::Clipboard::ObjectMap* long_living_objects =
      new ui::Clipboard::ObjectMap(objects);

  // Splice the shared memory handle into the clipboard data.
  ui::Clipboard::ReplaceSharedMemHandle(long_living_objects, bitmap_handle,
                                        peer_handle());

  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      new WriteClipboardTask(long_living_objects));
}

void ClipboardMessageFilter::OnWriteObjectsAsync(
    const ui::Clipboard::ObjectMap& objects) {
  // We cannot write directly from the IO thread, and cannot service the IPC
  // on the UI thread. We'll copy the relevant data and post a task to preform
  // the write on the UI thread.
  ui::Clipboard::ObjectMap* long_living_objects =
      new ui::Clipboard::ObjectMap(objects);

  // This async message doesn't support shared-memory based bitmaps; they must
  // be removed otherwise we might dereference a rubbish pointer.
  long_living_objects->erase(ui::Clipboard::CBF_SMBITMAP);

  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      new WriteClipboardTask(long_living_objects));
}

void ClipboardMessageFilter::OnIsFormatAvailable(
    ui::Clipboard::FormatType format, ui::Clipboard::Buffer buffer,
    bool* result) {
  *result = GetClipboard()->IsFormatAvailable(format, buffer);
}

void ClipboardMessageFilter::OnReadText(
    ui::Clipboard::Buffer buffer, string16* result) {
  GetClipboard()->ReadText(buffer, result);
}

void ClipboardMessageFilter::OnReadAsciiText(
    ui::Clipboard::Buffer buffer, std::string* result) {
  GetClipboard()->ReadAsciiText(buffer, result);
}

void ClipboardMessageFilter::OnReadHTML(
    ui::Clipboard::Buffer buffer, string16* markup, GURL* url) {
  std::string src_url_str;
  GetClipboard()->ReadHTML(buffer, markup, &src_url_str);
  *url = GURL(src_url_str);
}

void ClipboardMessageFilter::OnReadImage(
    ui::Clipboard::Buffer buffer, std::string* data) {
  GetClipboard()->ReadImage(buffer, data);
}

void ClipboardMessageFilter::OnReadAvailableTypes(
    ui::Clipboard::Buffer buffer, bool* succeeded, std::vector<string16>* types,
    bool* contains_filenames) {
  *contains_filenames = false;
  *succeeded = ClipboardDispatcher::ReadAvailableTypes(
      buffer, types, contains_filenames);
}

void ClipboardMessageFilter::OnReadData(
    ui::Clipboard::Buffer buffer, const string16& type, bool* succeeded,
    string16* data, string16* metadata) {
  *succeeded = ClipboardDispatcher::ReadData(buffer, type, data, metadata);
}

void ClipboardMessageFilter::OnReadFilenames(
    ui::Clipboard::Buffer buffer, bool* succeeded,
    std::vector<string16>* filenames) {
  *succeeded = ClipboardDispatcher::ReadFilenames(buffer, filenames);
}

// static
ui::Clipboard* ClipboardMessageFilter::GetClipboard() {
  // We have a static instance of the clipboard service for use by all message
  // filters.  This instance lives for the life of the browser processes.
  static ui::Clipboard* clipboard = new ui::Clipboard;

  return clipboard;
}
<commit_msg>Fix build break after r78134.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/renderer_host/clipboard_message_filter.h"

#include "chrome/browser/browser_process.h"
#include "chrome/browser/clipboard_dispatcher.h"
#include "chrome/common/clipboard_messages.h"
#include "googleurl/src/gurl.h"
#include "ipc/ipc_message_macros.h"

namespace {

// Completes a clipboard write initiated by the renderer. The write must be
// performed on the UI thread because the clipboard service from the IO thread
// cannot create windows so it cannot be the "owner" of the clipboard's
// contents.
class WriteClipboardTask : public Task {
 public:
  explicit WriteClipboardTask(ui::Clipboard::ObjectMap* objects)
      : objects_(objects) {}
  ~WriteClipboardTask() {}

  void Run() {
    g_browser_process->clipboard()->WriteObjects(*objects_.get());
  }

 private:
  scoped_ptr<ui::Clipboard::ObjectMap> objects_;
};

}  // namespace

ClipboardMessageFilter::ClipboardMessageFilter() {
}

void ClipboardMessageFilter::OverrideThreadForMessage(
    const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(USE_X11)
  if (message.type() == ClipboardHostMsg_ReadImage::ID)
    *thread = BrowserThread::BACKGROUND_X11;
  else if (IPC_MESSAGE_CLASS(message) == ClipboardMsgStart)
    *thread = BrowserThread::UI;
#endif
}

bool ClipboardMessageFilter::OnMessageReceived(const IPC::Message& message,
                                               bool* message_was_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(ClipboardMessageFilter, message, *message_was_ok)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsAsync, OnWriteObjectsAsync)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsSync, OnWriteObjectsSync)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_IsFormatAvailable, OnIsFormatAvailable)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadText, OnReadText)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAsciiText, OnReadAsciiText)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadHTML, OnReadHTML)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadImage, OnReadImage)
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_FindPboardWriteStringAsync,
                        OnFindPboardWriteString)
#endif
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAvailableTypes,
                        OnReadAvailableTypes)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadData, OnReadData)
    IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadFilenames, OnReadFilenames)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

ClipboardMessageFilter::~ClipboardMessageFilter() {
}

void ClipboardMessageFilter::OnWriteObjectsSync(
    const ui::Clipboard::ObjectMap& objects,
    base::SharedMemoryHandle bitmap_handle) {
  DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle))
      << "Bad bitmap handle";
  // We cannot write directly from the IO thread, and cannot service the IPC
  // on the UI thread. We'll copy the relevant data and get a handle to any
  // shared memory so it doesn't go away when we resume the renderer, and post
  // a task to perform the write on the UI thread.
  ui::Clipboard::ObjectMap* long_living_objects =
      new ui::Clipboard::ObjectMap(objects);

  // Splice the shared memory handle into the clipboard data.
  ui::Clipboard::ReplaceSharedMemHandle(long_living_objects, bitmap_handle,
                                        peer_handle());

  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      new WriteClipboardTask(long_living_objects));
}

void ClipboardMessageFilter::OnWriteObjectsAsync(
    const ui::Clipboard::ObjectMap& objects) {
  // We cannot write directly from the IO thread, and cannot service the IPC
  // on the UI thread. We'll copy the relevant data and post a task to preform
  // the write on the UI thread.
  ui::Clipboard::ObjectMap* long_living_objects =
      new ui::Clipboard::ObjectMap(objects);

  // This async message doesn't support shared-memory based bitmaps; they must
  // be removed otherwise we might dereference a rubbish pointer.
  long_living_objects->erase(ui::Clipboard::CBF_SMBITMAP);

  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      new WriteClipboardTask(long_living_objects));
}

void ClipboardMessageFilter::OnIsFormatAvailable(
    ui::Clipboard::FormatType format, ui::Clipboard::Buffer buffer,
    bool* result) {
  *result = GetClipboard()->IsFormatAvailable(format, buffer);
}

void ClipboardMessageFilter::OnReadText(
    ui::Clipboard::Buffer buffer, string16* result) {
  GetClipboard()->ReadText(buffer, result);
}

void ClipboardMessageFilter::OnReadAsciiText(
    ui::Clipboard::Buffer buffer, std::string* result) {
  GetClipboard()->ReadAsciiText(buffer, result);
}

void ClipboardMessageFilter::OnReadHTML(
    ui::Clipboard::Buffer buffer, string16* markup, GURL* url) {
  std::string src_url_str;
  GetClipboard()->ReadHTML(buffer, markup, &src_url_str);
  *url = GURL(src_url_str);
}

void ClipboardMessageFilter::OnReadImage(
    ui::Clipboard::Buffer buffer, std::string* data) {
  GetClipboard()->ReadImage(buffer, data);
}

void ClipboardMessageFilter::OnReadAvailableTypes(
    ui::Clipboard::Buffer buffer, bool* succeeded, std::vector<string16>* types,
    bool* contains_filenames) {
  *contains_filenames = false;
  *succeeded = ClipboardDispatcher::ReadAvailableTypes(
      buffer, types, contains_filenames);
}

void ClipboardMessageFilter::OnReadData(
    ui::Clipboard::Buffer buffer, const string16& type, bool* succeeded,
    string16* data, string16* metadata) {
  *succeeded = ClipboardDispatcher::ReadData(buffer, type, data, metadata);
}

void ClipboardMessageFilter::OnReadFilenames(
    ui::Clipboard::Buffer buffer, bool* succeeded,
    std::vector<string16>* filenames) {
  *succeeded = ClipboardDispatcher::ReadFilenames(buffer, filenames);
}

// static
ui::Clipboard* ClipboardMessageFilter::GetClipboard() {
  // We have a static instance of the clipboard service for use by all message
  // filters.  This instance lives for the life of the browser processes.
  static ui::Clipboard* clipboard = new ui::Clipboard;

  return clipboard;
}
<|endoftext|>


<commit_before>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/util/StringBuffer.h"

#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>
#include "base/globalsdef.h"

USE_NAMESPACE

/**
 * Test case for the class StringBuffer.
 */
class StringBufferTest : public CppUnit::TestFixture {
    CPPUNIT_TEST_SUITE(StringBufferTest);
    CPPUNIT_TEST(testConstruct);
    CPPUNIT_TEST(testCompare);
    CPPUNIT_TEST(testAssign);
    CPPUNIT_TEST(testConvert);
    CPPUNIT_TEST(testSprintf);
    CPPUNIT_TEST(testReset);
    CPPUNIT_TEST(testLength);
    CPPUNIT_TEST(testEndsWith);
    CPPUNIT_TEST_SUITE_END();

private:

    ///////////////////////////////////////////////////////// Test /////
    // test the different constructor and the c_str() method.
    void testConstruct() {
        StringBuffer s1;
        CPPUNIT_ASSERT(s1.c_str() == NULL);

        StringBuffer s2("");
        CPPUNIT_ASSERT(strcmp(s2.c_str(), "") == 0);

        StringBuffer s3("test");
        CPPUNIT_ASSERT(strcmp(s3.c_str(), "test") == 0);

        StringBuffer s4("0123456789", 4);
        CPPUNIT_ASSERT(strcmp(s4.c_str(), "0123") == 0);

        StringBuffer copy(s3);
        CPPUNIT_ASSERT(strcmp(copy, s3) == 0);
    }

    //////////////////////////////////////////////////////// Test /////
    // test the comparison operators and methods
    void testCompare() {
        StringBuffer s("Test");

        CPPUNIT_ASSERT(s == "Test");
        CPPUNIT_ASSERT(s != "tEST");
        CPPUNIT_ASSERT(s.icmp("tEST"));
    }

    //////////////////////////////////////////////////////// Test /////
    // test assignment operators and methods
    void testAssign() {
        StringBuffer s;

        s.assign("First test string");
        CPPUNIT_ASSERT(s == "First test string");

        s = "Second test string";
        CPPUNIT_ASSERT(s == "Second test string");
    }

    //////////////////////////////////////////////////////// Test /////
    // test WCHAR converison

#define TEST_STRING  "Quant' bella giovinezza.."

    void testConvert() {

        StringBuffer str(TEST_STRING);

        StringBuffer cnv;
        cnv.convert(TEXT(TEST_STRING));

        fprintf(stderr, "Converted string: %s\n", cnv.c_str());

        CPPUNIT_ASSERT(str == cnv);
    }

    //////////////////////////////////////////////////////// Test /////
    void testSprintf() {
        StringBuffer buf;

        buf.sprintf("foo %s %d", "bar", 42);
        CPPUNIT_ASSERT(buf == "foo bar 42");

        buf = doSprintf("foo %s %d", "bar", 42);
        CPPUNIT_ASSERT(buf == "foo bar 42");

        for (unsigned long size = 1; size < (1<<10); size *= 2) {
            buf.sprintf("%*s", (int)size, "");
            CPPUNIT_ASSERT_EQUAL(size, buf.length());
        }
    }

    //////////////////////////////////////////////////////// Test /////
    void testReset() {
        StringBuffer s("Test reset");
        s.reset();
        CPPUNIT_ASSERT(s.c_str() == NULL);
    }

    //////////////////////////////////////////////////////// Test /////
    void testLength() {
        StringBuffer s("Test length");
        CPPUNIT_ASSERT_EQUAL((unsigned long)strlen(s.c_str()), s.length());
    }

    //////////////////////////////////////////////////////// Test /////
    void testUpperCase() {
        StringBuffer s("Test Uppercase");
        StringBuffer &ref = s.upperCase();

        CPPUNIT_ASSERT(s == "TEST UPPERCASE");
        CPPUNIT_ASSERT(ref == s);
    }

    //////////////////////////////////////////////////////// Test /////
    void testLowerCase() {
        StringBuffer s("Test LowerCase");
        StringBuffer &ref = s.lowerCase();

        CPPUNIT_ASSERT(s == "test lowercase");
        CPPUNIT_ASSERT(ref == s);
    }

    //////////////////////////////////////////////////////// Test /////
    // Test null() and empty() behavior
    void testEmpty() {
        StringBuffer s;
        CPPUNIT_ASSERT(s.empty());
        CPPUNIT_ASSERT(s.null());

        s = "";

        CPPUNIT_ASSERT( s.empty() );
        CPPUNIT_ASSERT( !s.null() );

    }

    //////////////////////////////////////////////////////// Test /////
    //
    void testClone() {
        StringBuffer s("Test Clone");

        StringBuffer* cloned = (StringBuffer*)s.clone();

        CPPUNIT_ASSERT_EQUAL( s, *cloned);

        delete cloned;
    }

    //////////////////////////////////////////////////////// Test /////
    // Test null() and empty() behavior
    void testEndsWith() {
        StringBuffer s("Test Ends With");

        CPPUNIT_ASSERT(s.endsWith('h'));
        CPPUNIT_ASSERT(s.endsWith(" With"));
        CPPUNIT_ASSERT(!s.endsWith('t'));
        CPPUNIT_ASSERT(!s.endsWith("with"));

        StringBuffer s2("th");

        CPPUNIT_ASSERT(!s2.endsWith("with"));
        CPPUNIT_ASSERT(!s2.endsWith(""));

        StringBuffer s3;
        CPPUNIT_ASSERT(!s3.endsWith('t'));
        CPPUNIT_ASSERT(!s3.endsWith("t"));
    }

    //----------------------------------------- Utility functions
    StringBuffer doSprintf(const char* format, ...) {
        va_list ap;
        StringBuffer buf;

        va_start(ap, format);
        buf.vsprintf(format, ap);
        va_end(ap);

        return buf;
    }
};

CPPUNIT_TEST_SUITE_REGISTRATION( StringBufferTest );

<commit_msg>fixed test on conversion<commit_after>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/util/StringBuffer.h"

#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>
#include "base/globalsdef.h"

USE_NAMESPACE

/**
 * Test case for the class StringBuffer.
 */
class StringBufferTest : public CppUnit::TestFixture {
    CPPUNIT_TEST_SUITE(StringBufferTest);
    CPPUNIT_TEST(testConstruct);
    CPPUNIT_TEST(testCompare);
    CPPUNIT_TEST(testAssign);
    CPPUNIT_TEST(testConvert);
    CPPUNIT_TEST(testSprintf);
    CPPUNIT_TEST(testReset);
    CPPUNIT_TEST(testLength);
    CPPUNIT_TEST(testEndsWith);
    CPPUNIT_TEST_SUITE_END();

private:

    ///////////////////////////////////////////////////////// Test /////
    // test the different constructor and the c_str() method.
    void testConstruct() {
        StringBuffer s1;
        CPPUNIT_ASSERT(s1.c_str() == NULL);

        StringBuffer s2("");
        CPPUNIT_ASSERT(strcmp(s2.c_str(), "") == 0);

        StringBuffer s3("test");
        CPPUNIT_ASSERT(strcmp(s3.c_str(), "test") == 0);

        StringBuffer s4("0123456789", 4);
        CPPUNIT_ASSERT(strcmp(s4.c_str(), "0123") == 0);

        StringBuffer copy(s3);
        CPPUNIT_ASSERT(strcmp(copy, s3) == 0);
    }

    //////////////////////////////////////////////////////// Test /////
    // test the comparison operators and methods
    void testCompare() {
        StringBuffer s("Test");

        CPPUNIT_ASSERT(s == "Test");
        CPPUNIT_ASSERT(s != "tEST");
        CPPUNIT_ASSERT(s.icmp("tEST"));
    }

    //////////////////////////////////////////////////////// Test /////
    // test assignment operators and methods
    void testAssign() {
        StringBuffer s;

        s.assign("First test string");
        CPPUNIT_ASSERT(s == "First test string");

        s = "Second test string";
        CPPUNIT_ASSERT(s == "Second test string");
    }

    //////////////////////////////////////////////////////// Test /////
    // test WCHAR converison

#define TEST_STRING  "Quant' bella giovinezza.."

    void testConvert() {

        StringBuffer str(TEST_STRING);

        char* toUtf8   = toMultibyte(TEXT(TEST_STRING));
        char* toLatin1 = toMultibyte(TEXT(TEST_STRING), "iso_8859-1");

        StringBuffer cnv;
        cnv.convert(TEXT(TEST_STRING));
        fprintf(stderr, "\nConverted string: %s\n", cnv.c_str());
        CPPUNIT_ASSERT((strcmp(cnv.c_str(), toUtf8) == 0));

        cnv.convert(TEXT(TEST_STRING), "iso_8859-1");
        fprintf(stderr, "\nConverted string: %s\n", cnv.c_str());
        CPPUNIT_ASSERT((strcmp(cnv.c_str(), toLatin1) == 0));
    }

    //////////////////////////////////////////////////////// Test /////
    void testSprintf() {
        StringBuffer buf;

        buf.sprintf("foo %s %d", "bar", 42);
        CPPUNIT_ASSERT(buf == "foo bar 42");

        buf = doSprintf("foo %s %d", "bar", 42);
        CPPUNIT_ASSERT(buf == "foo bar 42");

        for (unsigned long size = 1; size < (1<<10); size *= 2) {
            buf.sprintf("%*s", (int)size, "");
            CPPUNIT_ASSERT_EQUAL(size, buf.length());
        }
    }

    //////////////////////////////////////////////////////// Test /////
    void testReset() {
        StringBuffer s("Test reset");
        s.reset();
        CPPUNIT_ASSERT(s.c_str() == NULL);
    }

    //////////////////////////////////////////////////////// Test /////
    void testLength() {
        StringBuffer s("Test length");
        CPPUNIT_ASSERT_EQUAL((unsigned long)strlen(s.c_str()), s.length());
    }

    //////////////////////////////////////////////////////// Test /////
    void testUpperCase() {
        StringBuffer s("Test Uppercase");
        StringBuffer &ref = s.upperCase();

        CPPUNIT_ASSERT(s == "TEST UPPERCASE");
        CPPUNIT_ASSERT(ref == s);
    }

    //////////////////////////////////////////////////////// Test /////
    void testLowerCase() {
        StringBuffer s("Test LowerCase");
        StringBuffer &ref = s.lowerCase();

        CPPUNIT_ASSERT(s == "test lowercase");
        CPPUNIT_ASSERT(ref == s);
    }

    //////////////////////////////////////////////////////// Test /////
    // Test null() and empty() behavior
    void testEmpty() {
        StringBuffer s;
        CPPUNIT_ASSERT(s.empty());
        CPPUNIT_ASSERT(s.null());

        s = "";

        CPPUNIT_ASSERT( s.empty() );
        CPPUNIT_ASSERT( !s.null() );

    }

    //////////////////////////////////////////////////////// Test /////
    //
    void testClone() {
        StringBuffer s("Test Clone");

        StringBuffer* cloned = (StringBuffer*)s.clone();

        CPPUNIT_ASSERT_EQUAL( s, *cloned);

        delete cloned;
    }

    //////////////////////////////////////////////////////// Test /////
    // Test null() and empty() behavior
    void testEndsWith() {
        StringBuffer s("Test Ends With");

        CPPUNIT_ASSERT(s.endsWith('h'));
        CPPUNIT_ASSERT(s.endsWith(" With"));
        CPPUNIT_ASSERT(!s.endsWith('t'));
        CPPUNIT_ASSERT(!s.endsWith("with"));

        StringBuffer s2("th");

        CPPUNIT_ASSERT(!s2.endsWith("with"));
        CPPUNIT_ASSERT(!s2.endsWith(""));

        StringBuffer s3;
        CPPUNIT_ASSERT(!s3.endsWith('t'));
        CPPUNIT_ASSERT(!s3.endsWith("t"));
    }

    //----------------------------------------- Utility functions
    StringBuffer doSprintf(const char* format, ...) {
        va_list ap;
        StringBuffer buf;

        va_start(ap, format);
        buf.vsprintf(format, ap);
        va_end(ap);

        return buf;
    }
};

CPPUNIT_TEST_SUITE_REGISTRATION( StringBufferTest );

<|endoftext|>