<commit_before>
#include "../../Flare.h"
#include "FlareCargoInfo.h"
#include "../../Spacecrafts/FlareSpacecraftInterface.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#include "../../Economy/FlareCargoBay.h"

#define LOCTEXT_NAMESPACE "FlareCargoInfo"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareCargoInfo::Construct(const FArguments& InArgs)
{
	// Params
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	TargetSpacecraft = InArgs._Spacecraft;
	CargoIndex = InArgs._CargoIndex;
	OnClicked = InArgs._OnClicked;
	TSharedPtr<SButton> Button;

	// Layout
	ChildSlot
	.HAlign(HAlign_Left)
	.VAlign(VAlign_Top)
	.Padding(FMargin(1))
	[
		SNew(SVerticalBox)

		// Main
		+ SVerticalBox::Slot()
		.AutoHeight()
		.Padding(FMargin(0))
		[
			// Button (behaviour only, no display)
			SAssignNew(Button, SButton)
			.OnClicked(this, &SFlareCargoInfo::OnButtonClicked)
			.ContentPadding(FMargin(0))
			.ButtonStyle(FCoreStyle::Get(), "NoBorder")
			[
				SNew(SBorder)
				.Padding(FMargin(0))
				.BorderImage(this, &SFlareCargoInfo::GetResourceIcon)
				[
					SNew(SBox)
					.WidthOverride(Theme.ResourceWidth)
					.HeightOverride(Theme.ResourceHeight)
					.Padding(FMargin(0))
					[
						SNew(SVerticalBox)

						// Resource name
						+ SVerticalBox::Slot()
						.Padding(Theme.SmallContentPadding)
						[
							SNew(STextBlock)
							.TextStyle(&Theme.TextFont)
							.Text(this, &SFlareCargoInfo::GetResourceAcronym)
						]

						// Resource quantity
						+ SVerticalBox::Slot()
						.AutoHeight()
						.Padding(Theme.SmallContentPadding)
						.VAlign(VAlign_Bottom)
						.HAlign(HAlign_Center)
						[
							SNew(STextBlock)
							.TextStyle(&Theme.SmallFont)
							.Text(this, &SFlareCargoInfo::GetResourceQuantity)
						]
					]
				]
			]
		]

		// Dump
		+ SVerticalBox::Slot()
		.AutoHeight()
		.Padding(FMargin(0))
		[
			SAssignNew(DumpButton, SFlareButton)
			.Transparent(true)
			.Text(FText())
			.HelpText(LOCTEXT("DumpResourceHelp", "Dump this resource"))
			.Icon(FFlareStyleSet::GetIcon("Stop"))
			.OnClicked(this, &SFlareCargoInfo::OnDumpClicked)
			.Width(1)
		]
	];

	// Don't intercept clicks if it's not interactive
	if (!OnClicked.IsBound())
	{
		Button->SetVisibility(EVisibility::HitTestInvisible);
	}
	DumpButton->SetVisibility(EVisibility::Collapsed);
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

void SFlareCargoInfo::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent)
{
	SWidget::OnMouseEnter(MyGeometry, MouseEvent);

	AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton();
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);
	check(Cargo);

	// Tooltip
	if (MenuManager)
	{
		FText TitleText = Cargo->Resource ? Cargo->Resource->Name : LOCTEXT("EmptyTitle", "Empty bay");
		FText InfoText = Cargo->Resource ? Cargo->Resource->Description : LOCTEXT("EmptyInfo", "This cargo bay is empty.");
		MenuManager->ShowTooltip(this, FText::Format(LOCTEXT("CargoBayFormat", "Cargo bay : {0}"), TitleText), InfoText);
	}

	// Dump button
	bool CanDump = Cargo->Resource && TargetSpacecraft && TargetSpacecraft->GetCompany() == MenuManager->GetPC()->GetCompany();
	DumpButton->SetVisibility(CanDump ? EVisibility::Visible : EVisibility::Collapsed);
}

void SFlareCargoInfo::OnMouseLeave(const FPointerEvent& MouseEvent)
{
	SWidget::OnMouseLeave(MouseEvent);

	AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton();
	if (MenuManager)
	{
		MenuManager->HideTooltip(this);
	}

	DumpButton->SetVisibility(EVisibility::Collapsed);
}

const FSlateBrush* SFlareCargoInfo::GetResourceIcon() const
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);
	check(Cargo);

	if (Cargo->Resource)
	{
		return &Cargo->Resource->Icon;
	}
	else
	{
		const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
		return &Theme.ResourceBackground;
	}
}

FText SFlareCargoInfo::GetResourceAcronym() const
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);
	check(Cargo);

	if (Cargo->Resource)
	{
		return Cargo->Resource->Acronym;
	}
	else
	{
		return LOCTEXT("Empty", " ");
	}
}

FText SFlareCargoInfo::GetResourceQuantity() const
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);
	check(Cargo);

	return FText::FromString(FString::Printf(TEXT("%u/%u"), Cargo->Quantity, Cargo->Capacity)); //FString needed here
}

FReply SFlareCargoInfo::OnButtonClicked()
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);

	if (Cargo && Cargo->Resource)
	{
		OnClicked.ExecuteIfBound();
	}

	return FReply::Handled();
}

void SFlareCargoInfo::OnDumpClicked()
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);

	if (Cargo && Cargo->Resource)
	{
		TargetSpacecraft->GetCargoBay()->DumpCargo(Cargo);
	}
}

#undef LOCTEXT_NAMESPACE
<commit_msg>Fixed cargo info for long numerical values<commit_after>
#include "../../Flare.h"
#include "FlareCargoInfo.h"
#include "../../Spacecrafts/FlareSpacecraftInterface.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#include "../../Economy/FlareCargoBay.h"

#define LOCTEXT_NAMESPACE "FlareCargoInfo"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareCargoInfo::Construct(const FArguments& InArgs)
{
	// Params
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	TargetSpacecraft = InArgs._Spacecraft;
	CargoIndex = InArgs._CargoIndex;
	OnClicked = InArgs._OnClicked;
	TSharedPtr<SButton> Button;

	// Layout
	ChildSlot
	.HAlign(HAlign_Left)
	.VAlign(VAlign_Top)
	.Padding(FMargin(1))
	[
		SNew(SVerticalBox)

		// Main
		+ SVerticalBox::Slot()
		.AutoHeight()
		.Padding(FMargin(0))
		[
			// Button (behaviour only, no display)
			SAssignNew(Button, SButton)
			.OnClicked(this, &SFlareCargoInfo::OnButtonClicked)
			.ContentPadding(FMargin(0))
			.ButtonStyle(FCoreStyle::Get(), "NoBorder")
			[
				SNew(SBorder)
				.Padding(FMargin(0))
				.BorderImage(this, &SFlareCargoInfo::GetResourceIcon)
				[
					SNew(SBox)
					.WidthOverride(Theme.ResourceWidth)
					.HeightOverride(Theme.ResourceHeight)
					.Padding(FMargin(0))
					[
						SNew(SVerticalBox)

						// Resource name
						+ SVerticalBox::Slot()
						.Padding(Theme.SmallContentPadding)
						[
							SNew(STextBlock)
							.TextStyle(&Theme.TextFont)
							.Text(this, &SFlareCargoInfo::GetResourceAcronym)
						]

						// Resource quantity
						+ SVerticalBox::Slot()
						.AutoHeight()
						.Padding(Theme.SmallContentPadding)
						.VAlign(VAlign_Bottom)
						.HAlign(HAlign_Right)
						[
							SNew(STextBlock)
							.TextStyle(&Theme.SmallFont)
							.Text(this, &SFlareCargoInfo::GetResourceQuantity)
						]
					]
				]
			]
		]

		// Dump
		+ SVerticalBox::Slot()
		.AutoHeight()
		.Padding(FMargin(0))
		[
			SAssignNew(DumpButton, SFlareButton)
			.Transparent(true)
			.Text(FText())
			.HelpText(LOCTEXT("DumpResourceHelp", "Dump this resource"))
			.Icon(FFlareStyleSet::GetIcon("Stop"))
			.OnClicked(this, &SFlareCargoInfo::OnDumpClicked)
			.Width(1)
		]
	];

	// Don't intercept clicks if it's not interactive
	if (!OnClicked.IsBound())
	{
		Button->SetVisibility(EVisibility::HitTestInvisible);
	}
	DumpButton->SetVisibility(EVisibility::Collapsed);
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

void SFlareCargoInfo::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent)
{
	SWidget::OnMouseEnter(MyGeometry, MouseEvent);

	AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton();
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);
	check(Cargo);

	// Tooltip
	if (MenuManager)
	{
		FText TitleText = Cargo->Resource ? Cargo->Resource->Name : LOCTEXT("EmptyTitle", "Empty bay");
		FText InfoText = Cargo->Resource ? Cargo->Resource->Description : LOCTEXT("EmptyInfo", "This cargo bay is empty.");
		MenuManager->ShowTooltip(this, FText::Format(LOCTEXT("CargoBayFormat", "Cargo bay : {0}"), TitleText), InfoText);
	}

	// Dump button
	bool CanDump = Cargo->Resource && TargetSpacecraft && TargetSpacecraft->GetCompany() == MenuManager->GetPC()->GetCompany();
	DumpButton->SetVisibility(CanDump ? EVisibility::Visible : EVisibility::Collapsed);
}

void SFlareCargoInfo::OnMouseLeave(const FPointerEvent& MouseEvent)
{
	SWidget::OnMouseLeave(MouseEvent);

	AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton();
	if (MenuManager)
	{
		MenuManager->HideTooltip(this);
	}

	DumpButton->SetVisibility(EVisibility::Collapsed);
}

const FSlateBrush* SFlareCargoInfo::GetResourceIcon() const
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);
	check(Cargo);

	if (Cargo->Resource)
	{
		return &Cargo->Resource->Icon;
	}
	else
	{
		const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
		return &Theme.ResourceBackground;
	}
}

FText SFlareCargoInfo::GetResourceAcronym() const
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);
	check(Cargo);

	if (Cargo->Resource)
	{
		return Cargo->Resource->Acronym;
	}
	else
	{
		return LOCTEXT("Empty", " ");
	}
}

FText SFlareCargoInfo::GetResourceQuantity() const
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);
	check(Cargo);

	if (Cargo->Capacity > 999)
	{
		return FText::FromString(FString::Printf(TEXT(" %u\n/%u"), Cargo->Quantity, Cargo->Capacity));
	}
	else
	{
		return FText::FromString(FString::Printf(TEXT("%u/%u"), Cargo->Quantity, Cargo->Capacity));
	}
}

FReply SFlareCargoInfo::OnButtonClicked()
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);

	if (Cargo && Cargo->Resource)
	{
		OnClicked.ExecuteIfBound();
	}

	return FReply::Handled();
}

void SFlareCargoInfo::OnDumpClicked()
{
	FFlareCargo* Cargo = TargetSpacecraft->GetCargoBay()->GetSlot(CargoIndex);

	if (Cargo && Cargo->Resource)
	{
		TargetSpacecraft->GetCargoBay()->DumpCargo(Cargo);
	}
}

#undef LOCTEXT_NAMESPACE
<|endoftext|>


<commit_before>#ifndef __AST_NODE_HH__
#define __AST_NODE_HH__

#include <vector>
#include <typeinfo>

#include "checksieve.h"

namespace sieve
{

class ASTVisitor;

class ASTNode {
public:
    ASTNode() : _children() {}
    ASTNode(const yy::location &location)
        : _children()
        , _location(location.begin, location.end) {}

    virtual void accept(ASTVisitor& visitor) =0;

    const std::vector<ASTNode *> &children() const { return this->_children; }

    void push(ASTNode *child) { this->_children.push_back(child); }
    void push(std::vector<ASTNode *> children) {
        this->_children.insert(this->_children.end(), children.begin(), children.end());
    }

    yy::location location() const { return this->_location; }

private:
    std::vector<ASTNode *> _children;
    yy::location _location;
};

} // namespace sieve

#endif
<commit_msg>remove executable bit from ASTNode.hh<commit_after>#ifndef __AST_NODE_HH__
#define __AST_NODE_HH__

#include <vector>
#include <typeinfo>

#include "checksieve.h"

namespace sieve
{

class ASTVisitor;

class ASTNode {
public:
    ASTNode() : _children() {}
    ASTNode(const yy::location &location)
        : _children()
        , _location(location.begin, location.end) {}

    virtual void accept(ASTVisitor& visitor) =0;

    const std::vector<ASTNode *> &children() const { return this->_children; }

    void push(ASTNode *child) { this->_children.push_back(child); }
    void push(std::vector<ASTNode *> children) {
        this->_children.insert(this->_children.end(), children.begin(), children.end());
    }

    yy::location location() const { return this->_location; }

private:
    std::vector<ASTNode *> _children;
    yy::location _location;
};

} // namespace sieve

#endif
<|endoftext|>


<commit_before>/**
 * A wrapper code for creating a Node.js native addon.
 * Most of this code is taken from the official document of Node.js:
 * https://nodejs.org/api/addons.html
 *
 * Build:
 * $ node-gyp configure build
 */

#include <node.h>
extern "C" {
  #include "serialled.h"
}

namespace bky {

using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

const int SUCCESS = 0;
const int FAILURE = -1;

inline int convertArgs(const FunctionCallbackInfo<Value>& args,
                       int argv[], const int n)
{
  Isolate* isolate = args.GetIsolate();

  if (args.Length() < n) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong number of arguments")));
    return FAILURE;
  }

  // Convert the arguments
  for (int i = 0; i < n; i++) {
    if (!args[i]->IsNumber()) {
      isolate->ThrowException(Exception::TypeError(
          String::NewFromUtf8(isolate, "Wrong arguments")));
      return FAILURE;
    }
    argv[i] = args[i]->NumberValue();
  }

  return SUCCESS;
}

void SetColor(const FunctionCallbackInfo<Value>& args) {
  int v[4];
  if (convertArgs(args, v, 4) == FAILURE) { return; }

  ledSetColor(v[0], v[1], v[2], v[3]);

  Local<Number> ret = Number::New(args.GetIsolate(), 0.0);
  args.GetReturnValue().Set(ret);
}

void Setup(const FunctionCallbackInfo<Value>& args) {
  int v[2];
  if (convertArgs(args, v, 2) == FAILURE) { return; }

  int result = ledSetup(v[0], v[1]);

  Local<Number> ret = Number::New(args.GetIsolate(), result);
  args.GetReturnValue().Set(ret);
}

void Cleanup(const FunctionCallbackInfo<Value>& args) {
  ledCleanup();
  Local<Number> ret = Number::New(args.GetIsolate(), 0.0);
  args.GetReturnValue().Set(ret);
}

void Send(const FunctionCallbackInfo<Value>& args) {
  ledSend();
  Local<Number> ret = Number::New(args.GetIsolate(), 0.0);
  args.GetReturnValue().Set(ret);
}

void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "setColor", SetColor);
  NODE_SET_METHOD(exports, "setup",    Setup);
  NODE_SET_METHOD(exports, "cleanup",  Cleanup);
  NODE_SET_METHOD(exports, "send",     Send);
}

NODE_MODULE(addon, Init)

}  // namespace bky
<commit_msg>remove unnecessary return values<commit_after>/**
 * A wrapper code for creating a Node.js native addon.
 * Most of this code is taken from the official document of Node.js:
 * https://nodejs.org/api/addons.html
 *
 * Build:
 * $ node-gyp configure build
 */

#include <node.h>
extern "C" {
  #include "serialled.h"
}

namespace serialled {

using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

const int SUCCESS = 0;
const int FAILURE = -1;

inline int convertArgs(const FunctionCallbackInfo<Value>& args,
                       int argv[], const int n)
{
  Isolate* isolate = args.GetIsolate();

  if (args.Length() < n) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong number of arguments")));
    return FAILURE;
  }

  // Convert the arguments
  for (int i = 0; i < n; i++) {
    if (!args[i]->IsNumber()) {
      isolate->ThrowException(Exception::TypeError(
          String::NewFromUtf8(isolate, "Wrong arguments")));
      return FAILURE;
    }
    argv[i] = args[i]->NumberValue();
  }

  return SUCCESS;
}

void SetColor(const FunctionCallbackInfo<Value>& args) {
  int v[4];
  if (convertArgs(args, v, 4) == FAILURE) { return; }

  ledSetColor(v[0], v[1], v[2], v[3]);
}

void Setup(const FunctionCallbackInfo<Value>& args) {
  int v[2];
  if (convertArgs(args, v, 2) == FAILURE) { return; }

  int result = ledSetup(v[0], v[1]);

  Local<Number> ret = Number::New(args.GetIsolate(), result);
  args.GetReturnValue().Set(ret);
}

void Cleanup(const FunctionCallbackInfo<Value>& args) {
  ledCleanup();
}

void Send(const FunctionCallbackInfo<Value>& args) {
  ledSend();
}

void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "setColor", SetColor);
  NODE_SET_METHOD(exports, "setup",    Setup);
  NODE_SET_METHOD(exports, "cleanup",  Cleanup);
  NODE_SET_METHOD(exports, "send",     Send);
}

NODE_MODULE(addon, Init)

}  // namespace serialled
<|endoftext|>


<commit_before><commit_msg>*** empty log message ***<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "platform/fonts/FontCache.h"

#include "platform/fonts/SimpleFontData.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"

#include "SkTypeface_android.h"

namespace blink {

static AtomicString getFamilyNameForCharacter(UChar32 c, UScriptCode script)
{
    // This is a hack to use the preferred font for CJK scripts.
    // FIXME: Use new Skia API once Android system supports per-family and per-script fallback fonts.
    const char* locale;
    switch (script) {
    case USCRIPT_SIMPLIFIED_HAN:
        locale = "zh-CN";
        break;
    case USCRIPT_TRADITIONAL_HAN:
        locale = "zh-TW";
        break;
    case USCRIPT_KATAKANA_OR_HIRAGANA:
        locale = "ja";
        break;
    case USCRIPT_HANGUL:
        locale = "ko";
        break;
    default:
        locale = 0;
        break;
    }

    SkString skiaFamilyName;
    if (!SkGetFallbackFamilyNameForChar(c, locale, &skiaFamilyName) || skiaFamilyName.isEmpty())
        return emptyAtom;

    return skiaFamilyName.c_str();
}

PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 c, const SimpleFontData*)
{
    AtomicString familyName = getFamilyNameForCharacter(c, fontDescription.script());
    if (familyName.isEmpty())
        return getLastResortFallbackFont(fontDescription, DoNotRetain);
    return fontDataFromFontPlatformData(getFontPlatformData(fontDescription, FontFaceCreationParams(familyName)), DoNotRetain);
}

// static
AtomicString FontCache::getGenericFamilyNameForScript(const AtomicString& familyName, UScriptCode script)
{
    // This is a hack to use the preferred font for CJK scripts.
    // FIXME: Use new Skia API once Android system supports per-family and per-script fallback fonts.
    UChar32 examplerChar;
    switch (script) {
    case USCRIPT_SIMPLIFIED_HAN:
    case USCRIPT_TRADITIONAL_HAN:
    case USCRIPT_KATAKANA_OR_HIRAGANA:
        examplerChar = 0x4E00; // A common character in Japanese and Chinese.
        break;
    case USCRIPT_HANGUL:
        examplerChar = 0xAC00;
        break;
    default:
        // For other scripts, use the default generic family mapping logic.
        return familyName;
    }

    return getFamilyNameForCharacter(examplerChar, script);
}

} // namespace blink
<commit_msg>Use font manager for fallback on Android.<commit_after>/*
 * Copyright (c) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "platform/fonts/FontCache.h"

#include "platform/fonts/SimpleFontData.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "third_party/skia/include/ports/SkFontMgr.h"

namespace blink {

static AtomicString getFamilyNameForCharacter(UChar32 c, UScriptCode script)
{
    // This is a hack to use the preferred font for CJK scripts.
    // FIXME: Use new Skia API once Android system supports per-family and per-script fallback fonts.
    const char* locale;
    switch (script) {
    case USCRIPT_SIMPLIFIED_HAN:
        locale = "zh-CN";
        break;
    case USCRIPT_TRADITIONAL_HAN:
        locale = "zh-TW";
        break;
    case USCRIPT_KATAKANA_OR_HIRAGANA:
        locale = "ja";
        break;
    case USCRIPT_HANGUL:
        locale = "ko";
        break;
    default:
        locale = 0;
        break;
    }

    RefPtr<SkFontMgr> fm = adoptRef(SkFontMgr::RefDefault());
    RefPtr<SkTypeface> typeface = adoptRef(fm->matchFamilyStyleCharacter(0, SkFontStyle(), locale, c));
    if (!typeface)
        return emptyAtom;

    SkString skiaFamilyName;
    typeface->getFamilyName(&skiaFamilyName);
    return skiaFamilyName.c_str();
}

PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 c, const SimpleFontData*)
{
    AtomicString familyName = getFamilyNameForCharacter(c, fontDescription.script());
    if (familyName.isEmpty())
        return getLastResortFallbackFont(fontDescription, DoNotRetain);
    return fontDataFromFontPlatformData(getFontPlatformData(fontDescription, FontFaceCreationParams(familyName)), DoNotRetain);
}

// static
AtomicString FontCache::getGenericFamilyNameForScript(const AtomicString& familyName, UScriptCode script)
{
    // This is a hack to use the preferred font for CJK scripts.
    // FIXME: Use new Skia API once Android system supports per-family and per-script fallback fonts.
    UChar32 examplerChar;
    switch (script) {
    case USCRIPT_SIMPLIFIED_HAN:
    case USCRIPT_TRADITIONAL_HAN:
    case USCRIPT_KATAKANA_OR_HIRAGANA:
        examplerChar = 0x4E00; // A common character in Japanese and Chinese.
        break;
    case USCRIPT_HANGUL:
        examplerChar = 0xAC00;
        break;
    default:
        // For other scripts, use the default generic family mapping logic.
        return familyName;
    }

    return getFamilyNameForCharacter(examplerChar, script);
}

} // namespace blink
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// Minimal hello world.
//------------------------------------------------------------------------------
#include <sstream>

#include <thread>
#include <malcpp/malcpp_lean.hpp>

malcpp::malcpp<> logger;
//------------------------------------------------------------------------------
int main (int argc, char const* argv[])
{
  /* destination register: adding logging to stdout/stderr */
  logger.add_destination<malcpp::stdouterr_dst>();
  logger.add_destination<malcpp::file_dst>();
  logger.init();

  std::thread thr;
  thr = std::thread ([](){
    log_error_i (logger, "Hello malc, testing {}, {}, {.1}", 1, 2, 3.f);
  });
  thr.join();
  return 0;
}
//------------------------------------------------------------------------------
<commit_msg>cpp: example: hello malc: remove unnecessary header<commit_after>//------------------------------------------------------------------------------
// Minimal hello world.
//------------------------------------------------------------------------------
#include <thread>
#include <malcpp/malcpp_lean.hpp>

malcpp::malcpp<> logger;
//------------------------------------------------------------------------------
int main (int argc, char const* argv[])
{
  /* destination register: adding logging to stdout/stderr */
  logger.add_destination<malcpp::stdouterr_dst>();
  logger.add_destination<malcpp::file_dst>();
  logger.init();

  std::thread thr;
  thr = std::thread ([](){
    log_error_i (logger, "Hello malc, testing {}, {}, {.1}", 1, 2, 3.f);
  });
  thr.join();
  return 0;
}
//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>#include <itkImageRegionConstIterator.h>
#include <itkStreamingImageFilter.h>

#include "rtkConfiguration.h"
#include "rtkTestConfiguration.h"
#include "rtkTest.h"
#include "rtkSheppLoganPhantomFilter.h"
#include "rtkDrawSheppLoganFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"

#ifdef USE_CUDA
#  include "rtkCudaIterativeFDKConeBeamReconstructionFilter.h"
#else
#  include "rtkIterativeFDKConeBeamReconstructionFilter.h"
#endif

/**
 * \file rtkiterativefdktest.cxx
 *
 * \brief Functional test for iterative FDK reconstruction
 *
 * This test generates the projections of a simulated Shepp-Logan phantom.
 * A CT image is reconstructed from the set of generated projection images
 * using the iterative FDK algorithm and the reconstructed CT image is compared
 * to the expected results which is analytically computed.
 *
 * \author Simon Rit
 */

int main(int, char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;
#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif

#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 180;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  ConstantImageSourceType::Pointer tomographySource  = ConstantImageSourceType::New();
  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 32;
  size[1] = 32;
  size[2] = 32;
  spacing[0] = 8.;
  spacing[1] = 8.;
  spacing[2] = 8.;
#else
  size[0] = 128;
  size[1] = 128;
  size[2] = 128;
  spacing[0] = 2.;
  spacing[1] = 2.;
  spacing[2] = 2.;
#endif
  tomographySource->SetOrigin( origin );
  tomographySource->SetSpacing( spacing );
  tomographySource->SetSize( size );
  tomographySource->SetConstant( 0. );

  ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
  origin[0] = -254.;
  origin[1] = -254.;
  origin[2] = -254.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 32;
  size[1] = 32;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 32.;
  spacing[1] = 32.;
  spacing[2] = 32.;
#else
  size[0] = 128;
  size[1] = 128;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  projectionsSource->SetOrigin( origin );
  projectionsSource->SetSpacing( spacing );
  projectionsSource->SetSize( size );
  projectionsSource->SetConstant( 0. );

  // Geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
    geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);

  // Shepp Logan projections filter
  typedef rtk::SheppLoganPhantomFilter<OutputImageType, OutputImageType> SLPType;
  SLPType::Pointer slp=SLPType::New();
  slp->SetInput( projectionsSource->GetOutput() );
  slp->SetGeometry(geometry);
  slp->SetPhantomScale(116);
  TRY_AND_EXIT_ON_ITK_EXCEPTION( slp->Update() );

  // Create a reference object (in this case a 3D phantom reference).
  typedef rtk::DrawSheppLoganFilter<OutputImageType, OutputImageType> DSLType;
  DSLType::Pointer dsl = DSLType::New();
  dsl->SetInput( tomographySource->GetOutput() );
  dsl->SetPhantomScale(116);
  TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )

  // FDK reconstruction filtering
#ifdef USE_CUDA
  typedef rtk::CudaIterativeFDKConeBeamReconstructionFilter                FDKType;
#else
  typedef rtk::IterativeFDKConeBeamReconstructionFilter< OutputImageType > FDKType;
#endif
  FDKType::Pointer ifdk = FDKType::New();
  ifdk->SetInput( 0, tomographySource->GetOutput() );
  ifdk->SetInput( 1, slp->GetOutput() );
  ifdk->SetGeometry( geometry );
  ifdk->SetNumberOfIterations(3);
#ifdef USE_CUDA
  ifdk->SetForwardProjectionFilter(2);
  ifdk->SetBackProjectionFilter(2);
#else
  ifdk->SetForwardProjectionFilter(0);
  ifdk->SetBackProjectionFilter(0);
#endif
  TRY_AND_EXIT_ON_ITK_EXCEPTION( ifdk->Update() );

  // FOV
  typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType;
  FOVFilterType::Pointer fov=FOVFilterType::New();
  fov->SetInput(0, ifdk->GetOutput());
  fov->SetProjectionsStack(slp->GetOutput());
  fov->SetGeometry( geometry );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( fov->Update() );

  CheckImageQuality<OutputImageType>(fov->GetOutput(), dsl->GetOutput(), 0.027, 27, 2.0);
  std::cout << "Test PASSED! " << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>FIX: don't change backprojection in rtkiterativefdktest<commit_after>#include <itkImageRegionConstIterator.h>
#include <itkStreamingImageFilter.h>

#include "rtkConfiguration.h"
#include "rtkTestConfiguration.h"
#include "rtkTest.h"
#include "rtkSheppLoganPhantomFilter.h"
#include "rtkDrawSheppLoganFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"

#ifdef USE_CUDA
#  include "rtkCudaIterativeFDKConeBeamReconstructionFilter.h"
#else
#  include "rtkIterativeFDKConeBeamReconstructionFilter.h"
#endif

/**
 * \file rtkiterativefdktest.cxx
 *
 * \brief Functional test for iterative FDK reconstruction
 *
 * This test generates the projections of a simulated Shepp-Logan phantom.
 * A CT image is reconstructed from the set of generated projection images
 * using the iterative FDK algorithm and the reconstructed CT image is compared
 * to the expected results which is analytically computed.
 *
 * \author Simon Rit
 */

int main(int, char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;
#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif

#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 180;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  ConstantImageSourceType::Pointer tomographySource  = ConstantImageSourceType::New();
  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 32;
  size[1] = 32;
  size[2] = 32;
  spacing[0] = 8.;
  spacing[1] = 8.;
  spacing[2] = 8.;
#else
  size[0] = 128;
  size[1] = 128;
  size[2] = 128;
  spacing[0] = 2.;
  spacing[1] = 2.;
  spacing[2] = 2.;
#endif
  tomographySource->SetOrigin( origin );
  tomographySource->SetSpacing( spacing );
  tomographySource->SetSize( size );
  tomographySource->SetConstant( 0. );

  ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
  origin[0] = -254.;
  origin[1] = -254.;
  origin[2] = -254.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 32;
  size[1] = 32;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 32.;
  spacing[1] = 32.;
  spacing[2] = 32.;
#else
  size[0] = 128;
  size[1] = 128;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  projectionsSource->SetOrigin( origin );
  projectionsSource->SetSpacing( spacing );
  projectionsSource->SetSize( size );
  projectionsSource->SetConstant( 0. );

  // Geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
    geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);

  // Shepp Logan projections filter
  typedef rtk::SheppLoganPhantomFilter<OutputImageType, OutputImageType> SLPType;
  SLPType::Pointer slp=SLPType::New();
  slp->SetInput( projectionsSource->GetOutput() );
  slp->SetGeometry(geometry);
  slp->SetPhantomScale(116);
  TRY_AND_EXIT_ON_ITK_EXCEPTION( slp->Update() );

  // Create a reference object (in this case a 3D phantom reference).
  typedef rtk::DrawSheppLoganFilter<OutputImageType, OutputImageType> DSLType;
  DSLType::Pointer dsl = DSLType::New();
  dsl->SetInput( tomographySource->GetOutput() );
  dsl->SetPhantomScale(116);
  TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )

  // FDK reconstruction filtering
#ifdef USE_CUDA
  typedef rtk::CudaIterativeFDKConeBeamReconstructionFilter                FDKType;
#else
  typedef rtk::IterativeFDKConeBeamReconstructionFilter< OutputImageType > FDKType;
#endif
  FDKType::Pointer ifdk = FDKType::New();
  ifdk->SetInput( 0, tomographySource->GetOutput() );
  ifdk->SetInput( 1, slp->GetOutput() );
  ifdk->SetGeometry( geometry );
  ifdk->SetNumberOfIterations(3);
#ifdef USE_CUDA
  ifdk->SetForwardProjectionFilter(2);
#else
  ifdk->SetForwardProjectionFilter(0);
#endif
  TRY_AND_EXIT_ON_ITK_EXCEPTION( ifdk->Update() );

  // FOV
  typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType;
  FOVFilterType::Pointer fov=FOVFilterType::New();
  fov->SetInput(0, ifdk->GetOutput());
  fov->SetProjectionsStack(slp->GetOutput());
  fov->SetGeometry( geometry );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( fov->Update() );

  CheckImageQuality<OutputImageType>(fov->GetOutput(), dsl->GetOutput(), 0.027, 27, 2.0);
  std::cout << "Test PASSED! " << std::endl;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "helpwidget.h"

#include "helpconstants.h"
#include "helpplugin.h"
#include "helpviewer.h"

#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/findplaceholder.h>
#include <texteditor/texteditorconstants.h>
#include <utils/qtcassert.h>
#include <utils/styledbar.h>

#include <QHBoxLayout>
#include <QMenu>
#include <QToolButton>

static QToolButton *toolButton(QAction *action)
{
    QToolButton *button = new QToolButton;
    button->setDefaultAction(action);
    button->setPopupMode(QToolButton::DelayedPopup);
    return button;
}

namespace Help {
namespace Internal {

HelpWidget::HelpWidget(const Core::Context &context, WidgetStyle style, QWidget *parent) :
    QWidget(parent),
    m_scaleUp(0),
    m_scaleDown(0),
    m_resetScale(0),
    m_style(style)
{
    Utils::StyledBar *toolBar = new Utils::StyledBar();

    m_switchToHelp = new QAction(tr("Go to Help Mode"), toolBar);
    connect(m_switchToHelp, SIGNAL(triggered()), this, SLOT(helpModeButtonClicked()));
    updateHelpModeButtonToolTip();

    QAction *back = new QAction(QIcon(QLatin1String(":/help/images/previous.png")),
        tr("Back"), toolBar);
    m_backMenu = new QMenu(toolBar);
    connect(m_backMenu, SIGNAL(aboutToShow()), this, SLOT(updateBackMenu()));
    back->setMenu(m_backMenu);
    QAction *forward = new QAction(QIcon(QLatin1String(":/help/images/next.png")),
        tr("Forward"), toolBar);
    m_forwardMenu = new QMenu(toolBar);
    connect(m_forwardMenu, SIGNAL(aboutToShow()), this, SLOT(updateForwardMenu()));
    forward->setMenu(m_forwardMenu);

    QHBoxLayout *layout = new QHBoxLayout(toolBar);
    layout->setSpacing(0);
    layout->setMargin(0);

    layout->addWidget(toolButton(m_switchToHelp));
    layout->addWidget(toolButton(back));
    layout->addWidget(toolButton(forward));
    layout->addStretch();

    m_viewer = HelpPlugin::createHelpViewer(qreal(0.0));

    QVBoxLayout *vLayout = new QVBoxLayout(this);
    vLayout->setMargin(0);
    vLayout->setSpacing(0);
    vLayout->addWidget(toolBar);
    vLayout->addWidget(m_viewer);
    Core::FindToolBarPlaceHolder *fth = new Core::FindToolBarPlaceHolder(this);
    vLayout->addWidget(fth);

    setFocusProxy(m_viewer);

    Core::IContext *icontext = new Core::IContext(this);
    icontext->setContext(context);
    icontext->setWidget(m_viewer);
    Core::ICore::addContextObject(icontext);

    back->setEnabled(m_viewer->isBackwardAvailable());
    connect(back, SIGNAL(triggered()), m_viewer, SLOT(backward()));
    connect(m_viewer, SIGNAL(backwardAvailable(bool)), back,
        SLOT(setEnabled(bool)));

    forward->setEnabled(m_viewer->isForwardAvailable());
    connect(forward, SIGNAL(triggered()), m_viewer, SLOT(forward()));
    connect(m_viewer, SIGNAL(forwardAvailable(bool)), forward,
        SLOT(setEnabled(bool)));

    m_copy = new QAction(this);
    Core::Command *cmd = Core::ActionManager::registerAction(m_copy, Core::Constants::COPY, context);
    connect(m_copy, SIGNAL(triggered()), m_viewer, SLOT(copy()));

    m_openHelpMode = new QAction(this);
    cmd = Core::ActionManager::registerAction(m_openHelpMode,
                                              Help::Constants::CONTEXT_HELP,
                                              context);
    connect(cmd, SIGNAL(keySequenceChanged()), this, SLOT(updateHelpModeButtonToolTip()));
    connect(m_openHelpMode, SIGNAL(triggered()), this, SLOT(helpModeButtonClicked()));

    Core::ActionContainer *advancedMenu = Core::ActionManager::actionContainer(Core::Constants::M_EDIT_ADVANCED);
    QTC_CHECK(advancedMenu);
    if (advancedMenu) {
        // reuse TextEditor constants to avoid a second pair of menu actions
        m_scaleUp = new QAction(tr("Increase Font Size"), this);
        cmd = Core::ActionManager::registerAction(m_scaleUp, TextEditor::Constants::INCREASE_FONT_SIZE,
                                                  context);
        connect(m_scaleUp, SIGNAL(triggered()), m_viewer, SLOT(scaleUp()));
        advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);

        m_scaleDown = new QAction(tr("Decrease Font Size"), this);
        cmd = Core::ActionManager::registerAction(m_scaleDown, TextEditor::Constants::DECREASE_FONT_SIZE,
                                                  context);
        connect(m_scaleDown, SIGNAL(triggered()), m_viewer, SLOT(scaleDown()));
        advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);

        m_resetScale = new QAction(tr("Reset Font Size"), this);
        cmd = Core::ActionManager::registerAction(m_resetScale, TextEditor::Constants::RESET_FONT_SIZE,
                                                  context);
        connect(m_resetScale, SIGNAL(triggered()), m_viewer, SLOT(resetScale()));
        advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);
    }

    if (style == SideBarWidget) {
        QAction *close = new QAction(QIcon(QLatin1String(Core::Constants::ICON_CLOSE_DOCUMENT)),
            QString(), toolBar);
        connect(close, SIGNAL(triggered()), this, SIGNAL(closeButtonClicked()));
        layout->addWidget(toolButton(close));
        m_viewer->setOpenInNewWindowActionVisible(false);
    } else if (style == ExternalWindow) {
        setAttribute(Qt::WA_DeleteOnClose);
        setAttribute(Qt::WA_QuitOnClose, false); // don't prevent Qt Creator from closing
        connect(m_viewer, SIGNAL(titleChanged()), this, SLOT(updateWindowTitle()));
        updateWindowTitle();
        m_viewer->setOpenInNewWindowActionVisible(false);
    }
}

HelpWidget::~HelpWidget()
{
    Core::ActionManager::unregisterAction(m_copy, Core::Constants::COPY);
    Core::ActionManager::unregisterAction(m_openHelpMode, Help::Constants::CONTEXT_HELP);
    if (m_scaleUp)
        Core::ActionManager::unregisterAction(m_scaleUp, TextEditor::Constants::INCREASE_FONT_SIZE);
    if (m_scaleDown)
        Core::ActionManager::unregisterAction(m_scaleDown, TextEditor::Constants::DECREASE_FONT_SIZE);
    if (m_resetScale)
        Core::ActionManager::unregisterAction(m_resetScale, TextEditor::Constants::RESET_FONT_SIZE);
}

HelpViewer *HelpWidget::currentViewer() const
{
    return m_viewer;
}

void HelpWidget::closeEvent(QCloseEvent *)
{
    emit aboutToClose();
}

void HelpWidget::updateBackMenu()
{
    m_backMenu->clear();
    m_viewer->addBackHistoryItems(m_backMenu);
}

void HelpWidget::updateForwardMenu()
{
    m_forwardMenu->clear();
    m_viewer->addForwardHistoryItems(m_forwardMenu);
}

void HelpWidget::updateWindowTitle()
{
    const QString pageTitle = m_viewer->title();
    if (pageTitle.isEmpty())
        setWindowTitle(tr("Help"));
    else
        setWindowTitle(tr("Help - %1").arg(pageTitle));
}

void HelpWidget::helpModeButtonClicked()
{
    emit openHelpMode(m_viewer->source());
    if (m_style == ExternalWindow)
        close();
}

void HelpWidget::updateHelpModeButtonToolTip()
{
    Core::Command *cmd = Core::ActionManager::command(Constants::CONTEXT_HELP);
    QTC_ASSERT(cmd, return);
    m_switchToHelp->setToolTip(cmd->stringWithAppendedShortcut(m_switchToHelp->text()));
}

} // Internal
} // Help
<commit_msg>Help: Add window actions (fullscreen etc) to external help window<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "helpwidget.h"

#include "helpconstants.h"
#include "helpplugin.h"
#include "helpviewer.h"

#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/findplaceholder.h>
#include <texteditor/texteditorconstants.h>
#include <utils/qtcassert.h>
#include <utils/styledbar.h>

#include <QHBoxLayout>
#include <QMenu>
#include <QToolButton>

static QToolButton *toolButton(QAction *action)
{
    QToolButton *button = new QToolButton;
    button->setDefaultAction(action);
    button->setPopupMode(QToolButton::DelayedPopup);
    return button;
}

namespace Help {
namespace Internal {

HelpWidget::HelpWidget(const Core::Context &context, WidgetStyle style, QWidget *parent) :
    QWidget(parent),
    m_scaleUp(0),
    m_scaleDown(0),
    m_resetScale(0),
    m_style(style)
{
    Utils::StyledBar *toolBar = new Utils::StyledBar();

    m_switchToHelp = new QAction(tr("Go to Help Mode"), toolBar);
    connect(m_switchToHelp, SIGNAL(triggered()), this, SLOT(helpModeButtonClicked()));
    updateHelpModeButtonToolTip();

    QAction *back = new QAction(QIcon(QLatin1String(":/help/images/previous.png")),
        tr("Back"), toolBar);
    m_backMenu = new QMenu(toolBar);
    connect(m_backMenu, SIGNAL(aboutToShow()), this, SLOT(updateBackMenu()));
    back->setMenu(m_backMenu);
    QAction *forward = new QAction(QIcon(QLatin1String(":/help/images/next.png")),
        tr("Forward"), toolBar);
    m_forwardMenu = new QMenu(toolBar);
    connect(m_forwardMenu, SIGNAL(aboutToShow()), this, SLOT(updateForwardMenu()));
    forward->setMenu(m_forwardMenu);

    QHBoxLayout *layout = new QHBoxLayout(toolBar);
    layout->setSpacing(0);
    layout->setMargin(0);

    layout->addWidget(toolButton(m_switchToHelp));
    layout->addWidget(toolButton(back));
    layout->addWidget(toolButton(forward));
    layout->addStretch();

    m_viewer = HelpPlugin::createHelpViewer(qreal(0.0));

    QVBoxLayout *vLayout = new QVBoxLayout(this);
    vLayout->setMargin(0);
    vLayout->setSpacing(0);
    vLayout->addWidget(toolBar);
    vLayout->addWidget(m_viewer);
    Core::FindToolBarPlaceHolder *fth = new Core::FindToolBarPlaceHolder(this);
    vLayout->addWidget(fth);

    setFocusProxy(m_viewer);

    Core::IContext *icontext = new Core::IContext(this);
    icontext->setContext(context);
    icontext->setWidget(m_viewer);
    Core::ICore::addContextObject(icontext);

    back->setEnabled(m_viewer->isBackwardAvailable());
    connect(back, SIGNAL(triggered()), m_viewer, SLOT(backward()));
    connect(m_viewer, SIGNAL(backwardAvailable(bool)), back,
        SLOT(setEnabled(bool)));

    forward->setEnabled(m_viewer->isForwardAvailable());
    connect(forward, SIGNAL(triggered()), m_viewer, SLOT(forward()));
    connect(m_viewer, SIGNAL(forwardAvailable(bool)), forward,
        SLOT(setEnabled(bool)));

    m_copy = new QAction(this);
    Core::Command *cmd = Core::ActionManager::registerAction(m_copy, Core::Constants::COPY, context);
    connect(m_copy, SIGNAL(triggered()), m_viewer, SLOT(copy()));

    m_openHelpMode = new QAction(this);
    cmd = Core::ActionManager::registerAction(m_openHelpMode,
                                              Help::Constants::CONTEXT_HELP,
                                              context);
    connect(cmd, SIGNAL(keySequenceChanged()), this, SLOT(updateHelpModeButtonToolTip()));
    connect(m_openHelpMode, SIGNAL(triggered()), this, SLOT(helpModeButtonClicked()));

    Core::ActionContainer *advancedMenu = Core::ActionManager::actionContainer(Core::Constants::M_EDIT_ADVANCED);
    QTC_CHECK(advancedMenu);
    if (advancedMenu) {
        // reuse TextEditor constants to avoid a second pair of menu actions
        m_scaleUp = new QAction(tr("Increase Font Size"), this);
        cmd = Core::ActionManager::registerAction(m_scaleUp, TextEditor::Constants::INCREASE_FONT_SIZE,
                                                  context);
        connect(m_scaleUp, SIGNAL(triggered()), m_viewer, SLOT(scaleUp()));
        advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);

        m_scaleDown = new QAction(tr("Decrease Font Size"), this);
        cmd = Core::ActionManager::registerAction(m_scaleDown, TextEditor::Constants::DECREASE_FONT_SIZE,
                                                  context);
        connect(m_scaleDown, SIGNAL(triggered()), m_viewer, SLOT(scaleDown()));
        advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);

        m_resetScale = new QAction(tr("Reset Font Size"), this);
        cmd = Core::ActionManager::registerAction(m_resetScale, TextEditor::Constants::RESET_FONT_SIZE,
                                                  context);
        connect(m_resetScale, SIGNAL(triggered()), m_viewer, SLOT(resetScale()));
        advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);
    }

    if (style == SideBarWidget) {
        QAction *close = new QAction(QIcon(QLatin1String(Core::Constants::ICON_CLOSE_DOCUMENT)),
            QString(), toolBar);
        connect(close, SIGNAL(triggered()), this, SIGNAL(closeButtonClicked()));
        layout->addWidget(toolButton(close));
        m_viewer->setOpenInNewWindowActionVisible(false);
    } else if (style == ExternalWindow) {
        static int windowId = 0;
        Core::ICore::registerWindow(this,
                                    Core::Context(Core::Id("Help.Window.").withSuffix(++windowId)));
        setAttribute(Qt::WA_DeleteOnClose);
        setAttribute(Qt::WA_QuitOnClose, false); // don't prevent Qt Creator from closing
        connect(m_viewer, SIGNAL(titleChanged()), this, SLOT(updateWindowTitle()));
        updateWindowTitle();
        m_viewer->setOpenInNewWindowActionVisible(false);
    }
}

HelpWidget::~HelpWidget()
{
    Core::ActionManager::unregisterAction(m_copy, Core::Constants::COPY);
    Core::ActionManager::unregisterAction(m_openHelpMode, Help::Constants::CONTEXT_HELP);
    if (m_scaleUp)
        Core::ActionManager::unregisterAction(m_scaleUp, TextEditor::Constants::INCREASE_FONT_SIZE);
    if (m_scaleDown)
        Core::ActionManager::unregisterAction(m_scaleDown, TextEditor::Constants::DECREASE_FONT_SIZE);
    if (m_resetScale)
        Core::ActionManager::unregisterAction(m_resetScale, TextEditor::Constants::RESET_FONT_SIZE);
}

HelpViewer *HelpWidget::currentViewer() const
{
    return m_viewer;
}

void HelpWidget::closeEvent(QCloseEvent *)
{
    emit aboutToClose();
}

void HelpWidget::updateBackMenu()
{
    m_backMenu->clear();
    m_viewer->addBackHistoryItems(m_backMenu);
}

void HelpWidget::updateForwardMenu()
{
    m_forwardMenu->clear();
    m_viewer->addForwardHistoryItems(m_forwardMenu);
}

void HelpWidget::updateWindowTitle()
{
    const QString pageTitle = m_viewer->title();
    if (pageTitle.isEmpty())
        setWindowTitle(tr("Help"));
    else
        setWindowTitle(tr("Help - %1").arg(pageTitle));
}

void HelpWidget::helpModeButtonClicked()
{
    emit openHelpMode(m_viewer->source());
    if (m_style == ExternalWindow)
        close();
}

void HelpWidget::updateHelpModeButtonToolTip()
{
    Core::Command *cmd = Core::ActionManager::command(Constants::CONTEXT_HELP);
    QTC_ASSERT(cmd, return);
    m_switchToHelp->setToolTip(cmd->stringWithAppendedShortcut(m_switchToHelp->text()));
}

} // Internal
} // Help
<|endoftext|>


<commit_before>// g++ -Wall -I.. -I../apache2 Server.cpp -o server ../libboost_oxt.a ../apache2/Utils.o ../apache2/Logging.o -lpthread
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <cstring>
#include <unistd.h>
#include <errno.h>

#include <set>

#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include "oxt/thread.hpp"
#include "oxt/system_calls.hpp"

#include "ScgiRequestParser.h"
#include "HttpStatusExtractor.h"

#include "StandardApplicationPool.h"
#include "Application.h"
#include "PoolOptions.h"
#include "Exceptions.h"
#include "Utils.h"

using namespace boost;
using namespace oxt;
using namespace Passenger;

/**
 * Wrapper class around a file descriptor integer, for RAII behavior.
 *
 * A FileDescriptor object behaves just like an int, so that you can pass it to
 * system calls such as read(). It performs reference counting. When the last
 * copy of a FileDescriptor has been destroyed, the underlying file descriptor
 * will be automatically closed.
 */
class FileDescriptor {
private:
	struct SharedData {
		int fd;

		SharedData(int fd) {
			this->fd = fd;
		}

		~SharedData() {
			if (syscalls::close(fd) == -1) {
				throw SystemException("Cannot close file descriptor", errno);
			}
		}
	};

	shared_ptr<SharedData> data;

public:
	FileDescriptor(int fd) {
		data = ptr(new SharedData(fd));
	}

	operator int () const {
		return data->fd;
	}
};

class Client {
private:
	static const int CLIENT_THREAD_STACK_SIZE = 1024 * 128;

	StandardApplicationPoolPtr pool;
	int serverSocket;
	oxt::thread *thr;

	FileDescriptor acceptConnection() {
		struct sockaddr_un addr;
		socklen_t addrlen = sizeof(addr);
		int fd = syscalls::accept(serverSocket,
			(struct sockaddr *) &addr,
			&addrlen);
		if (fd == -1) {
			throw SystemException("Cannot accept new connection", errno);
		} else {
			return FileDescriptor(fd);
		}
	}

	bool readAndParseResponseHeaders(FileDescriptor &fd, ScgiRequestParser &parser) {
		char buf[1024 * 16];
		ssize_t size;
		unsigned int accepted;

		do {
			size = syscalls::read(fd, buf, sizeof(buf));
			accepted = parser.feed(buf, size);
		} while (parser.acceptingInput());

		return parser.hasHeader("DOCUMENT_ROOT");
	}

	void forwardResponse(Application::SessionPtr &session, FileDescriptor &clientFd) {
		HttpStatusExtractor ex;
		int stream = session->getStream();
		int eof = false;
		MessageChannel output(clientFd);
		char buf[1024 * 32];
		ssize_t size;

		/* Read data from the backend process until we're able to
		 * extract the HTTP status line from it.
		 */
		while (!eof) {
			size = syscalls::read(stream, buf, sizeof(buf));
			if (size <= 0) {
				eof = true;
			} else if (ex.feed(buf, size)) {
				/* We now have an HTTP status line. Send back
				 * a proper HTTP response, then exit this while
				 * loop and continue with forwarding the rest
				 * of the response data.
				 */
				string statusLine("HTTP/1.1 ");
				statusLine.append(ex.getStatusLine());
				output.writeRaw(statusLine.c_str(), statusLine.size());
				output.writeRaw(ex.getBuffer().c_str(), ex.getBuffer().size());
				break;
			}
		}
		while (!eof) {
			size = syscalls::read(stream, buf, sizeof(buf));
			if (size <= 0) {
				eof = true;
			} else {
				output.writeRaw(buf, size);
			}
		}
	}

	void handleRequest(FileDescriptor &clientFd) {
		ScgiRequestParser parser;
		if (!readAndParseResponseHeaders(clientFd, parser)) {
			return;
		}

		PoolOptions options(canonicalizePath(parser.getHeader("DOCUMENT_ROOT") + "/.."));
		Application::SessionPtr session(pool->get(options));

		session->sendHeaders(parser.getHeaderData().c_str(),
			parser.getHeaderData().size());
		session->shutdownWriter();
		forwardResponse(session, clientFd);
	}

	void threadMain() {
		while (true) {
			try {
				FileDescriptor fd = acceptConnection();
				handleRequest(fd);
			} catch (const boost::thread_interrupted &) {
				P_TRACE(2, "Client thread " << this << " interrupted.");
				break;
			} catch (const tracable_exception &e) {
				P_TRACE(2, "Uncaught exception in PassengerServer client thread:\n"
					<< "   message: " << toString(args) << "\n"
					<< "   exception: " << e.what() << "\n"
					<< "   backtrace:\n" << e.backtrace());
				abort();
			} catch (const exception &e) {
				P_TRACE(2, "Uncaught exception in PassengerServer client thread:\n"
					<< "   message: " << toString(args) << "\n"
					<< "   exception: " << e.what() << "\n"
					<< "   backtrace: not available");
				abort();
			} catch (...) {
				P_TRACE(2, "Uncaught unknown exception in PassengerServer client thread.");
				throw;
			}
		}
	}

public:
	Client(StandardApplicationPoolPtr &pool, int serverSocket) {
		this->pool = pool;
		this->serverSocket = serverSocket;
		thr = new oxt::thread(
			bind(&Client::threadMain, this),
			"Thread", CLIENT_THREAD_STACK_SIZE
		);
	}
};

typedef shared_ptr<Client> ClientPtr;

class Server {
private:
	static const unsigned int BACKLOG_SIZE = 50;

	int serverSocket;
	unsigned int numberOfThreads;
	set<ClientPtr> clients;
	StandardApplicationPoolPtr pool;

	void initializePool(unsigned int maxPoolSize) {
		pool = ptr(new StandardApplicationPool(
			"/home/hongli/Projects/mod_rails/bin/passenger-spawn-server",
			"",
			"/opt/r8ee/bin/ruby"
		));
		pool->setMax(maxPoolSize);
	}

	void startListening() {
		this_thread::disable_syscall_interruption dsi;
		const char socketName[] = "/tmp/passenger_scgi.sock";
		struct sockaddr_un addr;
		int ret;

		serverSocket = syscalls::socket(PF_UNIX, SOCK_STREAM, 0);
		if (serverSocket == -1) {
			throw SystemException("Cannot create an unconnected Unix socket", errno);
		}

		addr.sun_family = AF_UNIX;
		strncpy(addr.sun_path, socketName, sizeof(addr.sun_path));
		addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
		syscalls::unlink(socketName);

		ret = syscalls::bind(serverSocket, (const struct sockaddr *) &addr, sizeof(addr));
		if (ret == -1) {
			int e = errno;
			syscalls::close(serverSocket);

			string message("Cannot bind on Unix socket '");
			message.append(socketName);
			message.append("'");
			throw SystemException(message, e);
		}

		ret = syscalls::listen(serverSocket, BACKLOG_SIZE);
		if (ret == -1) {
			int e = errno;
			syscalls::close(serverSocket);

			string message("Cannot bind on Unix socket '");
			message.append(socketName);
			message.append("'");
			throw SystemException(message, e);
		}
	}

	void startClientHandlerThreads() {
		for (unsigned int i = 0; i < numberOfThreads; i++) {
			ClientPtr client(new Client(pool, serverSocket));
			clients.insert(client);
		}
	}

public:
	Server(unsigned int maxPoolSize) {
		numberOfThreads = maxPoolSize * 4;
		setup_syscall_interruption_support();
		initializePool(maxPoolSize);
		startListening();
	}

	~Server() {
		syscalls::close(serverSocket);
	}

	void start() {
		startClientHandlerThreads();
		while (true) {
			sleep(1);
		}
	}
};

int
main() {
	try {
		Server(6).start();
		return 0;
	} catch (const tracable_exception &e) {
		P_ERROR(e.what() << "\n" << e.backtrace());
		return 1;
	} catch (const exception &e) {
		P_ERROR(e.what());
		return 1;
	} catch (...) {
		P_ERROR("Unknown exception thrown in main thread.");
		throw;
	}
}

<commit_msg>Make the SCGI server more fault-tolerant.<commit_after>// g++ -Wall -I.. -I../apache2 Server.cpp -o server ../libboost_oxt.a ../apache2/Utils.o ../apache2/Logging.o -lpthread
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <cstring>
#include <unistd.h>
#include <errno.h>
#include <signal.h>

#include <set>

#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include "oxt/thread.hpp"
#include "oxt/system_calls.hpp"

#include "ScgiRequestParser.h"
#include "HttpStatusExtractor.h"

#include "StandardApplicationPool.h"
#include "Application.h"
#include "PoolOptions.h"
#include "Exceptions.h"
#include "Utils.h"

using namespace boost;
using namespace oxt;
using namespace Passenger;

/**
 * Wrapper class around a file descriptor integer, for RAII behavior.
 *
 * A FileDescriptor object behaves just like an int, so that you can pass it to
 * system calls such as read(). It performs reference counting. When the last
 * copy of a FileDescriptor has been destroyed, the underlying file descriptor
 * will be automatically closed.
 */
class FileDescriptor {
private:
	struct SharedData {
		int fd;

		SharedData(int fd) {
			this->fd = fd;
		}

		~SharedData() {
			if (syscalls::close(fd) == -1) {
				throw SystemException("Cannot close file descriptor", errno);
			}
		}
	};

	shared_ptr<SharedData> data;

public:
	FileDescriptor() {
		// Do nothing.
	}

	FileDescriptor(int fd) {
		data = ptr(new SharedData(fd));
	}

	operator int () const {
		return data->fd;
	}
};

class Client {
private:
	static const int CLIENT_THREAD_STACK_SIZE = 1024 * 128;

	StandardApplicationPoolPtr pool;
	int serverSocket;
	oxt::thread *thr;

	FileDescriptor acceptConnection() {
		TRACE_POINT();
		struct sockaddr_un addr;
		socklen_t addrlen = sizeof(addr);
		int fd = syscalls::accept(serverSocket,
			(struct sockaddr *) &addr,
			&addrlen);
		if (fd == -1) {
			throw SystemException("Cannot accept new connection", errno);
		} else {
			return FileDescriptor(fd);
		}
	}

	bool readAndParseResponseHeaders(FileDescriptor &fd, ScgiRequestParser &parser) {
		TRACE_POINT();
		char buf[1024 * 16];
		ssize_t size;
		unsigned int accepted;

		do {
			size = syscalls::read(fd, buf, sizeof(buf));
			accepted = parser.feed(buf, size);
		} while (parser.acceptingInput());

		return parser.hasHeader("DOCUMENT_ROOT");
	}

	void forwardResponse(Application::SessionPtr &session, FileDescriptor &clientFd) {
		TRACE_POINT();
		HttpStatusExtractor ex;
		int stream = session->getStream();
		int eof = false;
		MessageChannel output(clientFd);
		char buf[1024 * 32];
		ssize_t size;

		/* Read data from the backend process until we're able to
		 * extract the HTTP status line from it.
		 */
		while (!eof) {
			UPDATE_TRACE_POINT();
			size = syscalls::read(stream, buf, sizeof(buf));
			if (size <= 0) {
				eof = true;
			} else if (ex.feed(buf, size)) {
				/* We now have an HTTP status line. Send back
				 * a proper HTTP response, then exit this while
				 * loop and continue with forwarding the rest
				 * of the response data.
				 */
				UPDATE_TRACE_POINT();
				string statusLine("HTTP/1.1 ");
				statusLine.append(ex.getStatusLine());
				UPDATE_TRACE_POINT();
				output.writeRaw(statusLine.c_str(), statusLine.size());
				UPDATE_TRACE_POINT();
				output.writeRaw(ex.getBuffer().c_str(), ex.getBuffer().size());
				break;
			}
		}

		UPDATE_TRACE_POINT();
		while (!eof) {
			UPDATE_TRACE_POINT();
			size = syscalls::read(stream, buf, sizeof(buf));
			if (size <= 0) {
				eof = true;
			} else {
				UPDATE_TRACE_POINT();
				output.writeRaw(buf, size);
			}
		}
	}

	void handleRequest(FileDescriptor &clientFd) {
		TRACE_POINT();
		ScgiRequestParser parser;
		if (!readAndParseResponseHeaders(clientFd, parser)) {
			return;
		}

		try {
			PoolOptions options(canonicalizePath(parser.getHeader("DOCUMENT_ROOT") + "/.."));
			Application::SessionPtr session(pool->get(options));

			UPDATE_TRACE_POINT();
			session->sendHeaders(parser.getHeaderData().c_str(),
				parser.getHeaderData().size());
			session->shutdownWriter();
			forwardResponse(session, clientFd);
		} catch (const boost::thread_interrupted &) {
			throw;
		} catch (const tracable_exception &e) {
			P_ERROR("Uncaught exception in PassengerServer client thread:\n"
				<< "   exception: " << e.what() << "\n"
				<< "   backtrace:\n" << e.backtrace());
		} catch (const exception &e) {
			P_ERROR("Uncaught exception in PassengerServer client thread:\n"
				<< "   exception: " << e.what() << "\n"
				<< "   backtrace: not available");
		} catch (...) {
			P_ERROR("Uncaught unknown exception in PassengerServer client thread.");
		}
	}

	void threadMain() {
		TRACE_POINT();
		try {
			while (true) {
				UPDATE_TRACE_POINT();
				FileDescriptor fd(acceptConnection());
				handleRequest(fd);
			}
		} catch (const boost::thread_interrupted &) {
			P_TRACE(2, "Client thread " << this << " interrupted.");
		} catch (const tracable_exception &e) {
			P_ERROR("Uncaught exception in PassengerServer client thread:\n"
				<< "   exception: " << e.what() << "\n"
				<< "   backtrace:\n" << e.backtrace());
			abort();
		} catch (const exception &e) {
			P_ERROR("Uncaught exception in PassengerServer client thread:\n"
				<< "   exception: " << e.what() << "\n"
				<< "   backtrace: not available");
			abort();
		} catch (...) {
			P_ERROR("Uncaught unknown exception in PassengerServer client thread.");
			throw;
		}
	}

public:
	Client(StandardApplicationPoolPtr &pool, int serverSocket) {
		this->pool = pool;
		this->serverSocket = serverSocket;
		thr = new oxt::thread(
			bind(&Client::threadMain, this),
			"Thread", CLIENT_THREAD_STACK_SIZE
		);
	}
};

typedef shared_ptr<Client> ClientPtr;

class Server {
private:
	static const unsigned int BACKLOG_SIZE = 50;

	int serverSocket;
	unsigned int numberOfThreads;
	set<ClientPtr> clients;
	StandardApplicationPoolPtr pool;

	void initializePool(unsigned int maxPoolSize) {
		pool = ptr(new StandardApplicationPool(
			"/home/hongli/Projects/mod_rails/bin/passenger-spawn-server",
			"",
			"/opt/r8ee/bin/ruby"
		));
		pool->setMax(maxPoolSize);
	}

	void startListening() {
		this_thread::disable_syscall_interruption dsi;
		const char socketName[] = "/tmp/passenger_scgi.sock";
		struct sockaddr_un addr;
		int ret;

		serverSocket = syscalls::socket(PF_UNIX, SOCK_STREAM, 0);
		if (serverSocket == -1) {
			throw SystemException("Cannot create an unconnected Unix socket", errno);
		}

		addr.sun_family = AF_UNIX;
		strncpy(addr.sun_path, socketName, sizeof(addr.sun_path));
		addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
		syscalls::unlink(socketName);

		ret = syscalls::bind(serverSocket, (const struct sockaddr *) &addr, sizeof(addr));
		if (ret == -1) {
			int e = errno;
			syscalls::close(serverSocket);

			string message("Cannot bind on Unix socket '");
			message.append(socketName);
			message.append("'");
			throw SystemException(message, e);
		}

		ret = syscalls::listen(serverSocket, BACKLOG_SIZE);
		if (ret == -1) {
			int e = errno;
			syscalls::close(serverSocket);

			string message("Cannot bind on Unix socket '");
			message.append(socketName);
			message.append("'");
			throw SystemException(message, e);
		}
	}

	void startClientHandlerThreads() {
		for (unsigned int i = 0; i < numberOfThreads; i++) {
			ClientPtr client(new Client(pool, serverSocket));
			clients.insert(client);
		}
	}

public:
	Server(unsigned int maxPoolSize) {
		numberOfThreads = maxPoolSize * 4;
		setup_syscall_interruption_support();

		// Ignore SIGPIPE.
		struct sigaction action;
		action.sa_handler = SIG_IGN;
		action.sa_flags   = 0;
		sigemptyset(&action.sa_mask);
		sigaction(SIGPIPE, &action, NULL);

		initializePool(maxPoolSize);
		startListening();
	}

	~Server() {
		syscalls::close(serverSocket);
	}

	void start() {
		TRACE_POINT();
		startClientHandlerThreads();
		while (true) {
			sleep(1);
		}
	}
};

int
main() {
	try {
		TRACE_POINT();
		Server(6).start();
		return 0;
	} catch (const tracable_exception &e) {
		P_ERROR(e.what() << "\n" << e.backtrace());
		return 1;
	} catch (const exception &e) {
		P_ERROR(e.what());
		return 1;
	} catch (...) {
		P_ERROR("Unknown exception thrown in main thread.");
		throw;
	}
}

<|endoftext|>


<commit_before>
/*
 * Copyright 2008 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkColorPriv.h"

#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkMovie.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkCGUtils.h"

#ifdef SK_BUILD_FOR_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif

#ifdef SK_BUILD_FOR_IOS
#include <CoreGraphics/CoreGraphics.h>
#include <ImageIO/ImageIO.h>
#include <MobileCoreServices/MobileCoreServices.h>
#endif

static void malloc_release_proc(void* info, const void* data, size_t size) {
    sk_free(info);
}

static CGDataProviderRef SkStreamToDataProvider(SkStream* stream) {
    // TODO: use callbacks, so we don't have to load all the data into RAM
    size_t len = stream->getLength();
    void* data = sk_malloc_throw(len);
    stream->read(data, len);

    return CGDataProviderCreateWithData(data, data, len, malloc_release_proc);
}

static CGImageSourceRef SkStreamToCGImageSource(SkStream* stream) {
    CGDataProviderRef data = SkStreamToDataProvider(stream);
    CGImageSourceRef imageSrc = CGImageSourceCreateWithDataProvider(data, 0);
    CGDataProviderRelease(data);
    return imageSrc;
}

class SkImageDecoder_CG : public SkImageDecoder {
protected:
    virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode);
};

#define BITMAP_INFO (kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast)

bool SkImageDecoder_CG::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) {
    CGImageSourceRef imageSrc = SkStreamToCGImageSource(stream);

    if (NULL == imageSrc) {
        return false;
    }
    SkAutoTCallVProc<const void, CFRelease> arsrc(imageSrc);

    CGImageRef image = CGImageSourceCreateImageAtIndex(imageSrc, 0, NULL);
    if (NULL == image) {
        return false;
    }
    SkAutoTCallVProc<CGImage, CGImageRelease> arimage(image);

    const int width = CGImageGetWidth(image);
    const int height = CGImageGetHeight(image);
    bm->setConfig(SkBitmap::kARGB_8888_Config, width, height);
    if (SkImageDecoder::kDecodeBounds_Mode == mode) {
        return true;
    }

    if (!this->allocPixelRef(bm, NULL)) {
        return false;
    }

    bm->lockPixels();
    bm->eraseColor(0);

    // use the same colorspace, so we don't change the pixels at all
    CGColorSpaceRef cs = CGImageGetColorSpace(image);
    CGContextRef cg = CGBitmapContextCreate(bm->getPixels(), width, height,
                                            8, bm->rowBytes(), cs, BITMAP_INFO);
    CGContextDrawImage(cg, CGRectMake(0, 0, width, height), image);
    CGContextRelease(cg);

    // since CGImage won't tell us if it is opaque, we have to compute it.
    bm->computeAndSetOpaquePredicate();
    bm->unlockPixels();
    return true;
}

///////////////////////////////////////////////////////////////////////////////

SkImageDecoder* SkImageDecoder::Factory(SkStream* stream) {
    return SkNEW(SkImageDecoder_CG);
}

/////////////////////////////////////////////////////////////////////////

SkMovie* SkMovie::DecodeStream(SkStream* stream) {
    return NULL;
}

/////////////////////////////////////////////////////////////////////////

static size_t consumer_put(void* info, const void* buffer, size_t count) {
    SkWStream* stream = reinterpret_cast<SkWStream*>(info);
    return stream->write(buffer, count) ? count : 0;
}

static void consumer_release(void* info) {
    // we do nothing, since by design we don't "own" the stream (i.e. info)
}

static CGDataConsumerRef SkStreamToCGDataConsumer(SkWStream* stream) {
    CGDataConsumerCallbacks procs;
    procs.putBytes = consumer_put;
    procs.releaseConsumer = consumer_release;
    // we don't own/reference the stream, so it our consumer must not live
    // longer that our caller's ownership of the stream
    return CGDataConsumerCreate(stream, &procs);
}

static CGImageDestinationRef SkStreamToImageDestination(SkWStream* stream,
                                                        CFStringRef type) {
    CGDataConsumerRef consumer = SkStreamToCGDataConsumer(stream);
    if (NULL == consumer) {
        return NULL;
    }
    SkAutoTCallVProc<const void, CFRelease> arconsumer(consumer);

    return CGImageDestinationCreateWithDataConsumer(consumer, type, 1, NULL);
}

class SkImageEncoder_CG : public SkImageEncoder {
public:
    SkImageEncoder_CG(Type t) : fType(t) {}

protected:
    virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality);

private:
    Type fType;
};

/*  Encode bitmaps via CGImageDestination. We setup a DataConsumer which writes
    to our SkWStream. Since we don't reference/own the SkWStream, our consumer
    must only live for the duration of the onEncode() method.
 */
bool SkImageEncoder_CG::onEncode(SkWStream* stream, const SkBitmap& bm,
                                 int quality) {
    // Used for converting a bitmap to 8888.
    const SkBitmap* bmPtr = &bm;
    SkBitmap bitmap8888;

    CFStringRef type;
    switch (fType) {
        case kJPEG_Type:
            type = kUTTypeJPEG;
            break;
        case kPNG_Type:
            // PNG encoding an ARGB_4444 bitmap gives the following errors in GM:
            // <Error>: CGImageDestinationAddImage image could not be converted to destination
            // format.
            // <Error>: CGImageDestinationFinalize image destination does not have enough images
            // So instead we copy to 8888.
            if (bm.getConfig() == SkBitmap::kARGB_4444_Config) {
                bm.copyTo(&bitmap8888, SkBitmap::kARGB_8888_Config);
                bmPtr = &bitmap8888;
            }
            type = kUTTypePNG;
            break;
        default:
            return false;
    }

    CGImageDestinationRef dst = SkStreamToImageDestination(stream, type);
    if (NULL == dst) {
        return false;
    }
    SkAutoTCallVProc<const void, CFRelease> ardst(dst);

    CGImageRef image = SkCreateCGImageRef(*bmPtr);
    if (NULL == image) {
        return false;
    }
    SkAutoTCallVProc<CGImage, CGImageRelease> agimage(image);

    CGImageDestinationAddImage(dst, image, NULL);
    return CGImageDestinationFinalize(dst);
}

SkImageEncoder* SkImageEncoder::Create(Type t) {
    switch (t) {
        case kJPEG_Type:
        case kPNG_Type:
            break;
        default:
            return NULL;
    }
    return SkNEW_ARGS(SkImageEncoder_CG, (t));
}

<commit_msg>check to see if CGImage already knows if we're opaque Review URL: https://codereview.appspot.com/6838043<commit_after>
/*
 * Copyright 2008 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkColorPriv.h"

#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkMovie.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkCGUtils.h"

#ifdef SK_BUILD_FOR_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif

#ifdef SK_BUILD_FOR_IOS
#include <CoreGraphics/CoreGraphics.h>
#include <ImageIO/ImageIO.h>
#include <MobileCoreServices/MobileCoreServices.h>
#endif

static void malloc_release_proc(void* info, const void* data, size_t size) {
    sk_free(info);
}

static CGDataProviderRef SkStreamToDataProvider(SkStream* stream) {
    // TODO: use callbacks, so we don't have to load all the data into RAM
    size_t len = stream->getLength();
    void* data = sk_malloc_throw(len);
    stream->read(data, len);

    return CGDataProviderCreateWithData(data, data, len, malloc_release_proc);
}

static CGImageSourceRef SkStreamToCGImageSource(SkStream* stream) {
    CGDataProviderRef data = SkStreamToDataProvider(stream);
    CGImageSourceRef imageSrc = CGImageSourceCreateWithDataProvider(data, 0);
    CGDataProviderRelease(data);
    return imageSrc;
}

class SkImageDecoder_CG : public SkImageDecoder {
protected:
    virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode);
};

#define BITMAP_INFO (kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast)

bool SkImageDecoder_CG::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) {
    CGImageSourceRef imageSrc = SkStreamToCGImageSource(stream);

    if (NULL == imageSrc) {
        return false;
    }
    SkAutoTCallVProc<const void, CFRelease> arsrc(imageSrc);

    CGImageRef image = CGImageSourceCreateImageAtIndex(imageSrc, 0, NULL);
    if (NULL == image) {
        return false;
    }
    SkAutoTCallVProc<CGImage, CGImageRelease> arimage(image);

    const int width = CGImageGetWidth(image);
    const int height = CGImageGetHeight(image);
    bm->setConfig(SkBitmap::kARGB_8888_Config, width, height);
    if (SkImageDecoder::kDecodeBounds_Mode == mode) {
        return true;
    }

    if (!this->allocPixelRef(bm, NULL)) {
        return false;
    }

    bm->lockPixels();
    bm->eraseColor(0);

    // use the same colorspace, so we don't change the pixels at all
    CGColorSpaceRef cs = CGImageGetColorSpace(image);
    CGContextRef cg = CGBitmapContextCreate(bm->getPixels(), width, height,
                                            8, bm->rowBytes(), cs, BITMAP_INFO);
    CGContextDrawImage(cg, CGRectMake(0, 0, width, height), image);
    CGContextRelease(cg);

    CGImageAlphaInfo info = CGImageGetAlphaInfo(image);
    switch (info) {
        case kCGImageAlphaNone:
        case kCGImageAlphaNoneSkipLast:
        case kCGImageAlphaNoneSkipFirst:
            SkASSERT(SkBitmap::ComputeIsOpaque(*bm));
            bm->setIsOpaque(true);
            break;
        default:
            // we don't know if we're opaque or not, so compute it.
            bm->computeAndSetOpaquePredicate();
    }
    bm->unlockPixels();
    return true;
}

///////////////////////////////////////////////////////////////////////////////

SkImageDecoder* SkImageDecoder::Factory(SkStream* stream) {
    return SkNEW(SkImageDecoder_CG);
}

/////////////////////////////////////////////////////////////////////////

SkMovie* SkMovie::DecodeStream(SkStream* stream) {
    return NULL;
}

/////////////////////////////////////////////////////////////////////////

static size_t consumer_put(void* info, const void* buffer, size_t count) {
    SkWStream* stream = reinterpret_cast<SkWStream*>(info);
    return stream->write(buffer, count) ? count : 0;
}

static void consumer_release(void* info) {
    // we do nothing, since by design we don't "own" the stream (i.e. info)
}

static CGDataConsumerRef SkStreamToCGDataConsumer(SkWStream* stream) {
    CGDataConsumerCallbacks procs;
    procs.putBytes = consumer_put;
    procs.releaseConsumer = consumer_release;
    // we don't own/reference the stream, so it our consumer must not live
    // longer that our caller's ownership of the stream
    return CGDataConsumerCreate(stream, &procs);
}

static CGImageDestinationRef SkStreamToImageDestination(SkWStream* stream,
                                                        CFStringRef type) {
    CGDataConsumerRef consumer = SkStreamToCGDataConsumer(stream);
    if (NULL == consumer) {
        return NULL;
    }
    SkAutoTCallVProc<const void, CFRelease> arconsumer(consumer);

    return CGImageDestinationCreateWithDataConsumer(consumer, type, 1, NULL);
}

class SkImageEncoder_CG : public SkImageEncoder {
public:
    SkImageEncoder_CG(Type t) : fType(t) {}

protected:
    virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality);

private:
    Type fType;
};

/*  Encode bitmaps via CGImageDestination. We setup a DataConsumer which writes
    to our SkWStream. Since we don't reference/own the SkWStream, our consumer
    must only live for the duration of the onEncode() method.
 */
bool SkImageEncoder_CG::onEncode(SkWStream* stream, const SkBitmap& bm,
                                 int quality) {
    // Used for converting a bitmap to 8888.
    const SkBitmap* bmPtr = &bm;
    SkBitmap bitmap8888;

    CFStringRef type;
    switch (fType) {
        case kJPEG_Type:
            type = kUTTypeJPEG;
            break;
        case kPNG_Type:
            // PNG encoding an ARGB_4444 bitmap gives the following errors in GM:
            // <Error>: CGImageDestinationAddImage image could not be converted to destination
            // format.
            // <Error>: CGImageDestinationFinalize image destination does not have enough images
            // So instead we copy to 8888.
            if (bm.getConfig() == SkBitmap::kARGB_4444_Config) {
                bm.copyTo(&bitmap8888, SkBitmap::kARGB_8888_Config);
                bmPtr = &bitmap8888;
            }
            type = kUTTypePNG;
            break;
        default:
            return false;
    }

    CGImageDestinationRef dst = SkStreamToImageDestination(stream, type);
    if (NULL == dst) {
        return false;
    }
    SkAutoTCallVProc<const void, CFRelease> ardst(dst);

    CGImageRef image = SkCreateCGImageRef(*bmPtr);
    if (NULL == image) {
        return false;
    }
    SkAutoTCallVProc<CGImage, CGImageRelease> agimage(image);

    CGImageDestinationAddImage(dst, image, NULL);
    return CGImageDestinationFinalize(dst);
}

SkImageEncoder* SkImageEncoder::Create(Type t) {
    switch (t) {
        case kJPEG_Type:
        case kPNG_Type:
            break;
        default:
            return NULL;
    }
    return SkNEW_ARGS(SkImageEncoder_CG, (t));
}

<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file dagger.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * Dashimoto test functions.
 */

#include <fstream>
#include <random>
#include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h>
#include <libethcore/ProofOfWork.h>
#include <libethcore/Ethasher.h>
#include <boost/test/unit_test.hpp>
#include "TestHelper.h"

using namespace std;
using namespace dev;
using namespace dev::eth;

namespace js = json_spirit;

using dev::operator <<;

BOOST_AUTO_TEST_SUITE(DashimotoTests)

BOOST_AUTO_TEST_CASE(basic_test)
{
#if 0
	cnote << "Testing ProofOfWork...";
	// Test dagger
	{
		auto s = steady_clock::now();
		cout << hex << ProofOfWork().eval((h256)(u256)1, (h256)(u256)0);
		cout << " " << dec << duration_cast<milliseconds>(steady_clock::now() - s).count() << " ms" << endl;
		cout << hex << ProofOfWork().eval((h256)(u256)1, (h256)(u256)1);
		cout << " " << dec << duration_cast<milliseconds>(steady_clock::now() - s).count() << " ms" << endl;
	}
	{
		cnote << i.first;
		js::mObject& o = i.second.get_obj();
		vector<pair<string, string>> ss;
		BlockInfo header = BlockInfo::fromHeader(fromHex(o["header"].get_str()));
		h256 headerHash(o["header_hash"].get_str());
		Nonce nonce(o["nonce"].get_str());
		BOOST_REQUIRE_EQUAL(headerHash, header.headerHash(WithoutNonce));
		BOOST_REQUIRE_EQUAL(nonce, header.nonce);

		unsigned cacheSize(o["cache_size"].get_int());
		h256 cacheHash(o["cache_hash"].get_str());
		BOOST_REQUIRE_EQUAL(Ethasher::get()->cache(header).size(), cacheSize);
		BOOST_REQUIRE_EQUAL(sha3(Ethasher::get()->cache(header)), cacheHash);

#if TEST_FULL
		unsigned fullSize(o["full_size"].get_int());
		h256 fullHash(o["full_hash"].get_str());
		BOOST_REQUIRE_EQUAL(Ethasher::get()->full(header).size(), fullSize);
		BOOST_REQUIRE_EQUAL(sha3(Ethasher::get()->full(header)), fullHash);
#endif

		h256 result(o["result"].get_str());
		Ethasher::Result r = Ethasher::eval(header);
		BOOST_REQUIRE_EQUAL(r.value, result);
		BOOST_REQUIRE_EQUAL(r.mixHash, header.mixHash);
	}
#endif
	return 0;
}

BOOST_AUTO_TEST_SUITE_END()

<commit_msg>For Marek :) BlockChain::transaction(h256 _transactionHash) BlockChain::transactionHashes(h256 _blockHash)<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file dagger.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * Dashimoto test functions.
 */

#include <fstream>
#include <random>
#include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h>
#include <libethcore/ProofOfWork.h>
#include <libethcore/Ethasher.h>
#include <boost/test/unit_test.hpp>
#include "TestHelper.h"

using namespace std;
using namespace dev;
using namespace dev::eth;

namespace js = json_spirit;

using dev::operator <<;

BOOST_AUTO_TEST_SUITE(DashimotoTests)

BOOST_AUTO_TEST_CASE(basic_test)
{
	string testPath = test::getTestPath();

	testPath += "/PoWTests";

	cnote << "Testing Secure Trie...";
	js::mValue v;
	string s = asString(contents(testPath + "/ethash_tests.json"));
	BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of 'ethash_tests.json' is empty. Have you cloned the 'tests' repo branch develop?");
	js::read_string(s, v);
	for (auto& i: v.get_obj())
	{
		cnote << i.first;
		js::mObject& o = i.second.get_obj();
		vector<pair<string, string>> ss;
		BlockInfo header = BlockInfo::fromHeader(fromHex(o["header"].get_str()));
		h256 headerHash(o["header_hash"].get_str());
		Nonce nonce(o["nonce"].get_str());
		BOOST_REQUIRE_EQUAL(headerHash, header.headerHash(WithoutNonce));
		BOOST_REQUIRE_EQUAL(nonce, header.nonce);

		unsigned cacheSize(o["cache_size"].get_int());
		h256 cacheHash(o["cache_hash"].get_str());
		BOOST_REQUIRE_EQUAL(Ethasher::get()->cache(header).size(), cacheSize);
		BOOST_REQUIRE_EQUAL(sha3(Ethasher::get()->cache(header)), cacheHash);

#if TEST_FULL
		unsigned fullSize(o["full_size"].get_int());
		h256 fullHash(o["full_hash"].get_str());
		BOOST_REQUIRE_EQUAL(Ethasher::get()->full(header).size(), fullSize);
		BOOST_REQUIRE_EQUAL(sha3(Ethasher::get()->full(header)), fullHash);
#endif

		h256 result(o["result"].get_str());
		Ethasher::Result r = Ethasher::eval(header);
		BOOST_REQUIRE_EQUAL(r.value, result);
		BOOST_REQUIRE_EQUAL(r.mixHash, header.mixHash);
	}
}

BOOST_AUTO_TEST_SUITE_END()

<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "sparse_solver.h"

template<typename T> void test_simplicial_cholesky_T()
{
  SimplicialCholesky<SparseMatrix<T>, Lower> chol_colmajor_lower;
  SimplicialCholesky<SparseMatrix<T>, Upper> chol_colmajor_upper;
  SimplicialLLt<SparseMatrix<T>, Lower> llt_colmajor_lower;
  SimplicialLDLt<SparseMatrix<T>, Upper> llt_colmajor_upper;
  SimplicialLDLt<SparseMatrix<T>, Lower> ldlt_colmajor_lower;
  SimplicialLDLt<SparseMatrix<T>, Upper> ldlt_colmajor_upper;

  check_sparse_spd_solving(chol_colmajor_lower);
  check_sparse_spd_solving(chol_colmajor_upper);
  check_sparse_spd_solving(llt_colmajor_lower);
  check_sparse_spd_solving(llt_colmajor_upper);
  check_sparse_spd_solving(ldlt_colmajor_lower);
  check_sparse_spd_solving(ldlt_colmajor_upper);

  check_sparse_spd_determinant(chol_colmajor_lower);
  check_sparse_spd_determinant(chol_colmajor_upper);
  check_sparse_spd_determinant(llt_colmajor_lower);
  check_sparse_spd_determinant(llt_colmajor_upper);
  check_sparse_spd_determinant(ldlt_colmajor_lower);
  check_sparse_spd_determinant(ldlt_colmajor_upper);
}

void test_simplicial_cholesky()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1(test_simplicial_cholesky_T<double>());
    CALL_SUBTEST_2(test_simplicial_cholesky_T<std::complex<double> >());
  }
}
<commit_msg>update unit test for Simplicial-Cholesky<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "sparse_solver.h"

template<typename T> void test_simplicial_cholesky_T()
{
  SimplicialCholesky<SparseMatrix<T>, Lower> chol_colmajor_lower;
  SimplicialCholesky<SparseMatrix<T>, Upper> chol_colmajor_upper;
  SimplicialLLT<SparseMatrix<T>, Lower> llt_colmajor_lower;
  SimplicialLDLT<SparseMatrix<T>, Upper> llt_colmajor_upper;
  SimplicialLDLT<SparseMatrix<T>, Lower> ldlt_colmajor_lower;
  SimplicialLDLT<SparseMatrix<T>, Upper> ldlt_colmajor_upper;

  check_sparse_spd_solving(chol_colmajor_lower);
  check_sparse_spd_solving(chol_colmajor_upper);
  check_sparse_spd_solving(llt_colmajor_lower);
  check_sparse_spd_solving(llt_colmajor_upper);
  check_sparse_spd_solving(ldlt_colmajor_lower);
  check_sparse_spd_solving(ldlt_colmajor_upper);

  check_sparse_spd_determinant(chol_colmajor_lower);
  check_sparse_spd_determinant(chol_colmajor_upper);
  check_sparse_spd_determinant(llt_colmajor_lower);
  check_sparse_spd_determinant(llt_colmajor_upper);
  check_sparse_spd_determinant(ldlt_colmajor_lower);
  check_sparse_spd_determinant(ldlt_colmajor_upper);
}

void test_simplicial_cholesky()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1(test_simplicial_cholesky_T<double>());
    CALL_SUBTEST_2(test_simplicial_cholesky_T<std::complex<double> >());
  }
}
<|endoftext|>