<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "SerializerUtils.hpp"

namespace armnnSerializer
{

armnnSerializer::ComparisonOperation GetFlatBufferComparisonOperation(armnn::ComparisonOperation comparisonOperation)
{
    switch (comparisonOperation)
    {
        case armnn::ComparisonOperation::Equal:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_Equal;
        case armnn::ComparisonOperation::Greater:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_Greater;
        case armnn::ComparisonOperation::GreaterOrEqual:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_GreaterOrEqual;
        case armnn::ComparisonOperation::Less:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_Less;
        case armnn::ComparisonOperation::LessOrEqual:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_LessOrEqual;
        case armnn::ComparisonOperation::NotEqual:
        default:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_NotEqual;
    }
}

armnnSerializer::ConstTensorData GetFlatBufferConstTensorData(armnn::DataType dataType)
{
    switch (dataType)
    {
        case armnn::DataType::Float32:
        case armnn::DataType::Signed32:
            return armnnSerializer::ConstTensorData::ConstTensorData_IntData;
        case armnn::DataType::Float16:
            return armnnSerializer::ConstTensorData::ConstTensorData_ShortData;
        case armnn::DataType::QuantisedAsymm8:
        case armnn::DataType::Boolean:
            return armnnSerializer::ConstTensorData::ConstTensorData_ByteData;
        default:
            return armnnSerializer::ConstTensorData::ConstTensorData_NONE;
    }
}

armnnSerializer::DataType GetFlatBufferDataType(armnn::DataType dataType)
{
    switch (dataType)
    {
        case armnn::DataType::Float32:
            return armnnSerializer::DataType::DataType_Float32;
        case armnn::DataType::Float16:
            return armnnSerializer::DataType::DataType_Float16;
        case armnn::DataType::Signed32:
            return armnnSerializer::DataType::DataType_Signed32;
        case armnn::DataType::QuantisedAsymm8:
            return armnnSerializer::DataType::DataType_QuantisedAsymm8;
        case armnn::DataType::Boolean:
            return armnnSerializer::DataType::DataType_Boolean;
        default:
            return armnnSerializer::DataType::DataType_Float16;
    }
}

armnnSerializer::DataLayout GetFlatBufferDataLayout(armnn::DataLayout dataLayout)
{
    switch (dataLayout)
    {
        case armnn::DataLayout::NHWC:
            return armnnSerializer::DataLayout::DataLayout_NHWC;
        case armnn::DataLayout::NCHW:
        default:
            return armnnSerializer::DataLayout::DataLayout_NCHW;
    }
}

armnnSerializer::PoolingAlgorithm GetFlatBufferPoolingAlgorithm(armnn::PoolingAlgorithm poolingAlgorithm)
{
    switch (poolingAlgorithm)
    {
        case armnn::PoolingAlgorithm::Average:
            return armnnSerializer::PoolingAlgorithm::PoolingAlgorithm_Average;
        case armnn::PoolingAlgorithm::L2:
            return armnnSerializer::PoolingAlgorithm::PoolingAlgorithm_L2;
        case armnn::PoolingAlgorithm::Max:
        default:
            return armnnSerializer::PoolingAlgorithm::PoolingAlgorithm_Max;
    }
}

armnnSerializer::OutputShapeRounding GetFlatBufferOutputShapeRounding(armnn::OutputShapeRounding outputShapeRounding)
{
    switch (outputShapeRounding)
    {
        case armnn::OutputShapeRounding::Ceiling:
            return armnnSerializer::OutputShapeRounding::OutputShapeRounding_Ceiling;
        case armnn::OutputShapeRounding::Floor:
        default:
            return armnnSerializer::OutputShapeRounding::OutputShapeRounding_Floor;
    }
}

armnnSerializer::PaddingMethod GetFlatBufferPaddingMethod(armnn::PaddingMethod paddingMethod)
{
    switch (paddingMethod)
    {
        case armnn::PaddingMethod::IgnoreValue:
            return armnnSerializer::PaddingMethod::PaddingMethod_IgnoreValue;
        case armnn::PaddingMethod::Exclude:
        default:
            return armnnSerializer::PaddingMethod::PaddingMethod_Exclude;
    }
}

armnnSerializer::NormalizationAlgorithmChannel GetFlatBufferNormalizationAlgorithmChannel(
    armnn::NormalizationAlgorithmChannel normalizationAlgorithmChannel)
{
    switch (normalizationAlgorithmChannel)
    {
        case armnn::NormalizationAlgorithmChannel::Across:
            return armnnSerializer::NormalizationAlgorithmChannel::NormalizationAlgorithmChannel_Across;
        case armnn::NormalizationAlgorithmChannel::Within:
            return armnnSerializer::NormalizationAlgorithmChannel::NormalizationAlgorithmChannel_Within;
        default:
            return armnnSerializer::NormalizationAlgorithmChannel::NormalizationAlgorithmChannel_Across;
    }
}

armnnSerializer::NormalizationAlgorithmMethod GetFlatBufferNormalizationAlgorithmMethod(
    armnn::NormalizationAlgorithmMethod normalizationAlgorithmMethod)
{
    switch (normalizationAlgorithmMethod)
    {
        case armnn::NormalizationAlgorithmMethod::LocalBrightness:
            return armnnSerializer::NormalizationAlgorithmMethod::NormalizationAlgorithmMethod_LocalBrightness;
        case armnn::NormalizationAlgorithmMethod::LocalContrast:
            return armnnSerializer::NormalizationAlgorithmMethod::NormalizationAlgorithmMethod_LocalContrast;
        default:
            return armnnSerializer::NormalizationAlgorithmMethod::NormalizationAlgorithmMethod_LocalBrightness;
    }
}

armnnSerializer::ResizeMethod GetFlatBufferResizeMethod(armnn::ResizeMethod method)
{
    switch (method)
    {
        case armnn::ResizeMethod::NearestNeighbor:
            return armnnSerializer::ResizeMethod_NearestNeighbor;
        case armnn::ResizeMethod::Bilinear:
            return armnnSerializer::ResizeMethod_Bilinear;
        default:
            return armnnSerializer::ResizeMethod_NearestNeighbor;
    }
}

} // namespace armnnSerializer
<commit_msg>Bug fix on serialization of tensor with qsymm16 type<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "SerializerUtils.hpp"

namespace armnnSerializer
{

armnnSerializer::ComparisonOperation GetFlatBufferComparisonOperation(armnn::ComparisonOperation comparisonOperation)
{
    switch (comparisonOperation)
    {
        case armnn::ComparisonOperation::Equal:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_Equal;
        case armnn::ComparisonOperation::Greater:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_Greater;
        case armnn::ComparisonOperation::GreaterOrEqual:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_GreaterOrEqual;
        case armnn::ComparisonOperation::Less:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_Less;
        case armnn::ComparisonOperation::LessOrEqual:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_LessOrEqual;
        case armnn::ComparisonOperation::NotEqual:
        default:
            return armnnSerializer::ComparisonOperation::ComparisonOperation_NotEqual;
    }
}

armnnSerializer::ConstTensorData GetFlatBufferConstTensorData(armnn::DataType dataType)
{
    switch (dataType)
    {
        case armnn::DataType::Float32:
        case armnn::DataType::Signed32:
            return armnnSerializer::ConstTensorData::ConstTensorData_IntData;
        case armnn::DataType::Float16:
        case armnn::DataType::QuantisedSymm16:
            return armnnSerializer::ConstTensorData::ConstTensorData_ShortData;
        case armnn::DataType::QuantisedAsymm8:
        case armnn::DataType::Boolean:
            return armnnSerializer::ConstTensorData::ConstTensorData_ByteData;
        default:
            return armnnSerializer::ConstTensorData::ConstTensorData_NONE;
    }
}

armnnSerializer::DataType GetFlatBufferDataType(armnn::DataType dataType)
{
    switch (dataType)
    {
        case armnn::DataType::Float32:
            return armnnSerializer::DataType::DataType_Float32;
        case armnn::DataType::Float16:
            return armnnSerializer::DataType::DataType_Float16;
        case armnn::DataType::Signed32:
            return armnnSerializer::DataType::DataType_Signed32;
        case armnn::DataType::QuantisedSymm16:
            return armnnSerializer::DataType::DataType_QuantisedSymm16;
        case armnn::DataType::QuantisedAsymm8:
            return armnnSerializer::DataType::DataType_QuantisedAsymm8;
        case armnn::DataType::Boolean:
            return armnnSerializer::DataType::DataType_Boolean;
        default:
            return armnnSerializer::DataType::DataType_Float16;
    }
}

armnnSerializer::DataLayout GetFlatBufferDataLayout(armnn::DataLayout dataLayout)
{
    switch (dataLayout)
    {
        case armnn::DataLayout::NHWC:
            return armnnSerializer::DataLayout::DataLayout_NHWC;
        case armnn::DataLayout::NCHW:
        default:
            return armnnSerializer::DataLayout::DataLayout_NCHW;
    }
}

armnnSerializer::PoolingAlgorithm GetFlatBufferPoolingAlgorithm(armnn::PoolingAlgorithm poolingAlgorithm)
{
    switch (poolingAlgorithm)
    {
        case armnn::PoolingAlgorithm::Average:
            return armnnSerializer::PoolingAlgorithm::PoolingAlgorithm_Average;
        case armnn::PoolingAlgorithm::L2:
            return armnnSerializer::PoolingAlgorithm::PoolingAlgorithm_L2;
        case armnn::PoolingAlgorithm::Max:
        default:
            return armnnSerializer::PoolingAlgorithm::PoolingAlgorithm_Max;
    }
}

armnnSerializer::OutputShapeRounding GetFlatBufferOutputShapeRounding(armnn::OutputShapeRounding outputShapeRounding)
{
    switch (outputShapeRounding)
    {
        case armnn::OutputShapeRounding::Ceiling:
            return armnnSerializer::OutputShapeRounding::OutputShapeRounding_Ceiling;
        case armnn::OutputShapeRounding::Floor:
        default:
            return armnnSerializer::OutputShapeRounding::OutputShapeRounding_Floor;
    }
}

armnnSerializer::PaddingMethod GetFlatBufferPaddingMethod(armnn::PaddingMethod paddingMethod)
{
    switch (paddingMethod)
    {
        case armnn::PaddingMethod::IgnoreValue:
            return armnnSerializer::PaddingMethod::PaddingMethod_IgnoreValue;
        case armnn::PaddingMethod::Exclude:
        default:
            return armnnSerializer::PaddingMethod::PaddingMethod_Exclude;
    }
}

armnnSerializer::NormalizationAlgorithmChannel GetFlatBufferNormalizationAlgorithmChannel(
    armnn::NormalizationAlgorithmChannel normalizationAlgorithmChannel)
{
    switch (normalizationAlgorithmChannel)
    {
        case armnn::NormalizationAlgorithmChannel::Across:
            return armnnSerializer::NormalizationAlgorithmChannel::NormalizationAlgorithmChannel_Across;
        case armnn::NormalizationAlgorithmChannel::Within:
            return armnnSerializer::NormalizationAlgorithmChannel::NormalizationAlgorithmChannel_Within;
        default:
            return armnnSerializer::NormalizationAlgorithmChannel::NormalizationAlgorithmChannel_Across;
    }
}

armnnSerializer::NormalizationAlgorithmMethod GetFlatBufferNormalizationAlgorithmMethod(
    armnn::NormalizationAlgorithmMethod normalizationAlgorithmMethod)
{
    switch (normalizationAlgorithmMethod)
    {
        case armnn::NormalizationAlgorithmMethod::LocalBrightness:
            return armnnSerializer::NormalizationAlgorithmMethod::NormalizationAlgorithmMethod_LocalBrightness;
        case armnn::NormalizationAlgorithmMethod::LocalContrast:
            return armnnSerializer::NormalizationAlgorithmMethod::NormalizationAlgorithmMethod_LocalContrast;
        default:
            return armnnSerializer::NormalizationAlgorithmMethod::NormalizationAlgorithmMethod_LocalBrightness;
    }
}

armnnSerializer::ResizeMethod GetFlatBufferResizeMethod(armnn::ResizeMethod method)
{
    switch (method)
    {
        case armnn::ResizeMethod::NearestNeighbor:
            return armnnSerializer::ResizeMethod_NearestNeighbor;
        case armnn::ResizeMethod::Bilinear:
            return armnnSerializer::ResizeMethod_Bilinear;
        default:
            return armnnSerializer::ResizeMethod_NearestNeighbor;
    }
}

} // namespace armnnSerializer
<|endoftext|>


<commit_before>//..............................................................................
//
//  This file is part of the AXL library.
//
//  AXL is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/axl/license.txt
//
//..............................................................................

#include "pch.h"
#include "axl_enc_EscapeEncoding.h"
#include "axl_enc_HexEncoding.h"

namespace axl {
namespace enc {

//..............................................................................

char
EscapeEncoding::findEscapeChar(char x)
{
	switch (x)
	{
	case '\0':
		return '0';

	case '\a':
		return 'a';

	case '\b':
		return 'b';

	case '\t':
		return 't';

	case '\n':
		return 'n';

	case '\f':
		return 'f';

	case '\v':
		return 'v';

	case '\r':
		return 'r';

	case '\x1b':
		return 'e';

	default:
		return x;
	};
}

char
EscapeEncoding::findEscapeReplaceChar(char x)
{
	switch (x)
	{
	case '0':
		return '\0';

	case 'a':
		return '\a';

	case 'b':
		return '\b';

	case 't':
		return '\t';

	case 'n':
		return '\n';

	case 'f':
		return '\f';

	case 'v':
		return '\v';

	case 'r':
		return '\r';

	case 'e':
		return '\x1b';

	default:
		return x;
	};
}

size_t
EscapeEncoding::encode(
	sl::String* string,
	const sl::StringRef& source
	)
{
	string->clear();
	string->reserve(source.getLength());

	char escapeSequence[4] = { '\\' };

	const char* p = source.cp();
	const char* end = source.getEnd();
	const char* base = p;

	for (; p < end; p++)
	{
		if (*p == '\\')
		{
			string->append(base, p - base);

			escapeSequence[1] = '\\';
			string->append(escapeSequence, 2);

			base = p + 1;
		}
		else
		{
			if (isprint(*p))
				continue;

			string->append(base, p - base);

			char escape = findEscapeChar(*p);
			if (escape != *p)
			{
				escapeSequence[1] = escape;
				string->append(escapeSequence, 2);
			}
			else
			{
				escapeSequence[1] = 'x';
				escapeSequence[2] = HexEncoding::getHexChar_l(*p >> 4);
				escapeSequence[3] = HexEncoding::getHexChar_l(*p);
				string->append(escapeSequence, 4);
			}

			base = p + 1;
		}
	}

	string->append(base, p - base);

	return string->getLength();
}

static
inline
bool
isHexChar(char c)
{
	return
		c >= '0' && c <= '9' ||
		c >= 'a' && c <= 'f' ||
		c >= 'A' && c <= 'F';
}

size_t
EscapeEncoding::decode(
	sl::String* string,
	const sl::StringRef& source
	)
{
	enum State
	{
		State_Normal = 0,
		State_Escape,
		State_Hex,
	};

	State state = State_Normal;

	string->clear();
	string->reserve(source.getLength() / 2);

	char hexCodeString[16];
	size_t hexCodeLen;
	size_t hexCodeMaxLen;
	ulong_t hexCode;

	char replace;

	const char* p = source.cp();
	const char* end = source.getEnd();
	const char* base = p;

	for (; p < end; p++)
	{
		switch (state)
		{
		case State_Normal:
			if (*p == '\\')
			{
				string->append(base, p - base);
				state = State_Escape;
			}

			break;

		case State_Escape:
			switch (*p)
			{
			case 'x':
				state = State_Hex;
				hexCodeLen = 0;
				hexCodeMaxLen = 2;
				break;

			case 'u':
				state = State_Hex;
				hexCodeLen = 0;
				hexCodeMaxLen = 4;
				break;

			case 'U':
				state = State_Hex;
				hexCodeLen = 0;
				hexCodeMaxLen = 8;
				break;

			default:
				replace = findEscapeReplaceChar(*p);
				if (replace != *p)
				{
					string->append(replace, 1);
					base = p + 1;
				}
				else
				{
					base = p;
				}

				state = State_Normal;
			}

			break;

		case State_Hex:
			if (isHexChar(*p))
			{
				hexCodeString[hexCodeLen++] = *p;
				if (hexCodeLen < hexCodeMaxLen)
					break;

				base = p + 1;
			}
			else
			{
				base = p;
			}

			if (!hexCodeLen)
			{
				hexCode = '?';
				string->append((char const*) &hexCode, 1);
			}
			else
			{
				hexCodeString[hexCodeLen] = 0;
				hexCode = strtoul(hexCodeString, NULL, 16);

				if (hexCodeMaxLen == 2) // \x
				{
					string->append((char const*) &hexCode, 1);
				}
				else // \u
				{
					utf8_t buffer[8];
					size_t length = enc::Utf8::getEncodeCodePointLength(hexCode);
					enc::Utf8::encodeCodePoint(buffer, hexCode);
					string->append(buffer, length);
				}
			}

			state = State_Normal;
			break;
		}
	}

	string->append(base, p - base);
	return string->getLength();
}

//..............................................................................

} // namespace enc
} // namespace axl
<commit_msg>[axl_enc] fix: prevent sign-expansion of a character before passing it to isprint()<commit_after>//..............................................................................
//
//  This file is part of the AXL library.
//
//  AXL is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/axl/license.txt
//
//..............................................................................

#include "pch.h"
#include "axl_enc_EscapeEncoding.h"
#include "axl_enc_HexEncoding.h"

namespace axl {
namespace enc {

//..............................................................................

char
EscapeEncoding::findEscapeChar(char x)
{
	switch (x)
	{
	case '\0':
		return '0';

	case '\a':
		return 'a';

	case '\b':
		return 'b';

	case '\t':
		return 't';

	case '\n':
		return 'n';

	case '\f':
		return 'f';

	case '\v':
		return 'v';

	case '\r':
		return 'r';

	case '\x1b':
		return 'e';

	default:
		return x;
	};
}

char
EscapeEncoding::findEscapeReplaceChar(char x)
{
	switch (x)
	{
	case '0':
		return '\0';

	case 'a':
		return '\a';

	case 'b':
		return '\b';

	case 't':
		return '\t';

	case 'n':
		return '\n';

	case 'f':
		return '\f';

	case 'v':
		return '\v';

	case 'r':
		return '\r';

	case 'e':
		return '\x1b';

	default:
		return x;
	};
}

size_t
EscapeEncoding::encode(
	sl::String* string,
	const sl::StringRef& source
	)
{
	string->clear();
	string->reserve(source.getLength());

	char escapeSequence[4] = { '\\' };

	const char* p = source.cp();
	const char* end = source.getEnd();
	const char* base = p;

	for (; p < end; p++)
	{
		if (*p == '\\')
		{
			string->append(base, p - base);

			escapeSequence[1] = '\\';
			string->append(escapeSequence, 2);

			base = p + 1;
		}
		else
		{
			if (isprint(*(uchar_t*)p))
				continue;

			string->append(base, p - base);

			char escape = findEscapeChar(*p);
			if (escape != *p)
			{
				escapeSequence[1] = escape;
				string->append(escapeSequence, 2);
			}
			else
			{
				escapeSequence[1] = 'x';
				escapeSequence[2] = HexEncoding::getHexChar_l(*p >> 4);
				escapeSequence[3] = HexEncoding::getHexChar_l(*p);
				string->append(escapeSequence, 4);
			}

			base = p + 1;
		}
	}

	string->append(base, p - base);

	return string->getLength();
}

static
inline
bool
isHexChar(char c)
{
	return
		c >= '0' && c <= '9' ||
		c >= 'a' && c <= 'f' ||
		c >= 'A' && c <= 'F';
}

size_t
EscapeEncoding::decode(
	sl::String* string,
	const sl::StringRef& source
	)
{
	enum State
	{
		State_Normal = 0,
		State_Escape,
		State_Hex,
	};

	State state = State_Normal;

	string->clear();
	string->reserve(source.getLength() / 2);

	char hexCodeString[16];
	size_t hexCodeLen;
	size_t hexCodeMaxLen;
	ulong_t hexCode;

	char replace;

	const char* p = source.cp();
	const char* end = source.getEnd();
	const char* base = p;

	for (; p < end; p++)
	{
		switch (state)
		{
		case State_Normal:
			if (*p == '\\')
			{
				string->append(base, p - base);
				state = State_Escape;
			}

			break;

		case State_Escape:
			switch (*p)
			{
			case 'x':
				state = State_Hex;
				hexCodeLen = 0;
				hexCodeMaxLen = 2;
				break;

			case 'u':
				state = State_Hex;
				hexCodeLen = 0;
				hexCodeMaxLen = 4;
				break;

			case 'U':
				state = State_Hex;
				hexCodeLen = 0;
				hexCodeMaxLen = 8;
				break;

			default:
				replace = findEscapeReplaceChar(*p);
				if (replace != *p)
				{
					string->append(replace, 1);
					base = p + 1;
				}
				else
				{
					base = p;
				}

				state = State_Normal;
			}

			break;

		case State_Hex:
			if (isHexChar(*p))
			{
				hexCodeString[hexCodeLen++] = *p;
				if (hexCodeLen < hexCodeMaxLen)
					break;

				base = p + 1;
			}
			else
			{
				base = p;
			}

			if (!hexCodeLen)
			{
				hexCode = '?';
				string->append((char const*) &hexCode, 1);
			}
			else
			{
				hexCodeString[hexCodeLen] = 0;
				hexCode = strtoul(hexCodeString, NULL, 16);

				if (hexCodeMaxLen == 2) // \x
				{
					string->append((char const*) &hexCode, 1);
				}
				else // \u
				{
					utf8_t buffer[8];
					size_t length = enc::Utf8::getEncodeCodePointLength(hexCode);
					enc::Utf8::encodeCodePoint(buffer, hexCode);
					string->append(buffer, length);
				}
			}

			state = State_Normal;
			break;
		}
	}

	string->append(base, p - base);
	return string->getLength();
}

//..............................................................................

} // namespace enc
} // namespace axl
<|endoftext|>


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

#include "base/command_line.h"
#include "base/prefs/pref_service.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"

#if defined(OS_WIN) && defined(USE_AURA)
#include "content/public/browser/web_contents_view.h"
#include "ui/aura/root_window.h"
#endif

namespace {

class PrintPreviewTest : public InProcessBrowserTest {
 public:
  PrintPreviewTest() {}

#if !defined(GOOGLE_CHROME_BUILD)
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    command_line->AppendSwitch(switches::kEnablePrintPreview);
  }
#endif

  void Print() {
    content::TestNavigationObserver nav_observer(NULL);
    nav_observer.StartWatchingNewWebContents();
    chrome::ExecuteCommand(browser(), IDC_PRINT);
    nav_observer.Wait();
    nav_observer.StopWatchingNewWebContents();
  }
};

IN_PROC_BROWSER_TEST_F(PrintPreviewTest, PrintCommands) {
  // We start off at about:blank page.
  // Make sure there is 1 tab and print is enabled.
  ASSERT_EQ(1, browser()->tab_strip_model()->count());

  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_PRINT));

  // Make sure advanced print command (Ctrl+Shift+p) is enabled.
  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_ADVANCED_PRINT));

  // Create the print preview dialog.
  Print();

  // Make sure print is disabled.
  ASSERT_FALSE(chrome::IsCommandEnabled(browser(), IDC_PRINT));

  // Make sure advanced print command (Ctrl+Shift+p) is enabled.
  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_ADVANCED_PRINT));

  content::TestNavigationObserver reload_observer(
      browser()->tab_strip_model()->GetActiveWebContents());
  chrome::Reload(browser(), CURRENT_TAB);
  reload_observer.Wait();

  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_PRINT));

  // Make sure advanced print command (Ctrl+Shift+p) is enabled.
  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_ADVANCED_PRINT));
}

#if defined(OS_WIN) && defined(USE_AURA)

BOOL CALLBACK EnumerateChildren(HWND hwnd, LPARAM l_param) {
  HWND* child = reinterpret_cast<HWND*>(l_param);
  *child = hwnd;
  // The first child window is the plugin, then its children. So stop
  // enumerating after the first callback.
  return FALSE;
}

// This test verifies that constrained windows aren't covered by windowed NPAPI
// plugins. The code which fixes this is in WebContentsViewAura::WindowObserver.
IN_PROC_BROWSER_TEST_F(PrintPreviewTest, WindowedNPAPIPluginHidden) {
  browser()->profile()->GetPrefs()->SetBoolean(prefs::kPluginsAlwaysAuthorize,
                                               true);

  // First load the page and wait for the NPAPI plugin's window to display.
  string16 expected_title(ASCIIToUTF16("ready"));
  content::WebContents* tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  content::TitleWatcher title_watcher(tab, expected_title);

  GURL url = ui_test_utils::GetTestUrl(
      base::FilePath().AppendASCII("printing"),
      base::FilePath().AppendASCII("npapi_plugin.html"));
  ui_test_utils::NavigateToURL(browser(), url);

  EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  // Now get the region of the plugin before and after the print preview is
  // shown. They should be different.
  HWND hwnd =
      tab->GetView()->GetNativeView()->GetDispatcher()->GetAcceleratedWidget();
  HWND child = NULL;
  EnumChildWindows(hwnd, EnumerateChildren,reinterpret_cast<LPARAM>(&child));

  RECT region_before, region_after;
  int result = GetWindowRgnBox(child, &region_before);
  ASSERT_EQ(result, SIMPLEREGION);

  // Now print preview.
  Print();

  result = GetWindowRgnBox(child, &region_after);
  if (result == NULLREGION) {
    // Depending on the browser window size, the plugin could be full covered.
    return;
  }

  if (result == COMPLEXREGION) {
    // Complex region, by definition not equal to the initial region.
    return;
  }

  ASSERT_EQ(result, SIMPLEREGION);
  bool rects_equal =
      region_before.left == region_after.left &&
      region_before.top == region_after.top &&
      region_before.right == region_after.right &&
      region_before.bottom == region_after.bottom;
  ASSERT_FALSE(rects_equal);
}
#endif

}  // namespace
<commit_msg>fix build bustage<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/prefs/pref_service.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"

#if defined(OS_WIN) && defined(USE_AURA)
#include "content/public/browser/web_contents_view.h"
#include "ui/aura/root_window.h"
#endif

namespace {

class PrintPreviewTest : public InProcessBrowserTest {
 public:
  PrintPreviewTest() {}

#if !defined(GOOGLE_CHROME_BUILD)
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    command_line->AppendSwitch(switches::kEnablePrintPreview);
  }
#endif

  void Print() {
    content::TestNavigationObserver nav_observer(NULL);
    nav_observer.StartWatchingNewWebContents();
    chrome::ExecuteCommand(browser(), IDC_PRINT);
    nav_observer.Wait();
    nav_observer.StopWatchingNewWebContents();
  }
};

IN_PROC_BROWSER_TEST_F(PrintPreviewTest, PrintCommands) {
  // We start off at about:blank page.
  // Make sure there is 1 tab and print is enabled.
  ASSERT_EQ(1, browser()->tab_strip_model()->count());

  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_PRINT));

  // Make sure advanced print command (Ctrl+Shift+p) is enabled.
  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_ADVANCED_PRINT));

  // Create the print preview dialog.
  Print();

  // Make sure print is disabled.
  ASSERT_FALSE(chrome::IsCommandEnabled(browser(), IDC_PRINT));

  // Make sure advanced print command (Ctrl+Shift+p) is enabled.
  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_ADVANCED_PRINT));

  content::TestNavigationObserver reload_observer(
      browser()->tab_strip_model()->GetActiveWebContents());
  chrome::Reload(browser(), CURRENT_TAB);
  reload_observer.Wait();

  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_PRINT));

  // Make sure advanced print command (Ctrl+Shift+p) is enabled.
  ASSERT_TRUE(chrome::IsCommandEnabled(browser(), IDC_ADVANCED_PRINT));
}

#if defined(OS_WIN) && defined(USE_AURA)

BOOL CALLBACK EnumerateChildren(HWND hwnd, LPARAM l_param) {
  HWND* child = reinterpret_cast<HWND*>(l_param);
  *child = hwnd;
  // The first child window is the plugin, then its children. So stop
  // enumerating after the first callback.
  return FALSE;
}

// This test verifies that constrained windows aren't covered by windowed NPAPI
// plugins. The code which fixes this is in WebContentsViewAura::WindowObserver.
IN_PROC_BROWSER_TEST_F(PrintPreviewTest, WindowedNPAPIPluginHidden) {
  browser()->profile()->GetPrefs()->SetBoolean(prefs::kPluginsAlwaysAuthorize,
                                               true);

  // First load the page and wait for the NPAPI plugin's window to display.
  string16 expected_title(ASCIIToUTF16("ready"));
  content::WebContents* tab =
      browser()->tab_strip_model()->GetActiveWebContents();
  content::TitleWatcher title_watcher(tab, expected_title);

  GURL url = ui_test_utils::GetTestUrl(
      base::FilePath().AppendASCII("printing"),
      base::FilePath().AppendASCII("npapi_plugin.html"));
  ui_test_utils::NavigateToURL(browser(), url);

  EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  // Now get the region of the plugin before and after the print preview is
  // shown. They should be different.
  HWND hwnd =
      tab->GetView()->GetNativeView()->GetDispatcher()->GetAcceleratedWidget();
  HWND child = NULL;
  EnumChildWindows(hwnd, EnumerateChildren,reinterpret_cast<LPARAM>(&child));

  RECT region_before, region_after;
  int result = GetWindowRgnBox(child, &region_before);
  ASSERT_EQ(result, SIMPLEREGION);

  // Now print preview.
  Print();

  result = GetWindowRgnBox(child, &region_after);
  if (result == NULLREGION) {
    // Depending on the browser window size, the plugin could be full covered.
    return;
  }

  if (result == COMPLEXREGION) {
    // Complex region, by definition not equal to the initial region.
    return;
  }

  ASSERT_EQ(result, SIMPLEREGION);
  bool rects_equal =
      region_before.left == region_after.left &&
      region_before.top == region_after.top &&
      region_before.right == region_after.right &&
      region_before.bottom == region_after.bottom;
  ASSERT_FALSE(rects_equal);
}
#endif

}  // namespace
<|endoftext|>


<commit_before>/**************************************************************************

 The MIT License (MIT)

 Copyright (c) 2015 Dmitry Sovetov

 https://github.com/dmsovetov

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

 **************************************************************************/

#include "Composer.h"

#include "FileSystem.h"

#include "Widgets/Menu.h"
#include "Widgets/MainWindow.h"
#include "Widgets/AssetTree.h"

#include "Project/Project.h"

DC_BEGIN_COMPOSER

namespace Editors {

// --------------------------------------------------------------- SceneEditorInternal -------------------------------------------------------------- //

// ** SceneEditorInternal::SceneEditorInternal
SceneEditorInternal::SceneEditorInternal( Scene::SceneObjectWPtr parent, u8 flags ) : m_parent( parent ), m_flags( flags )
{

}

// ** SceneEditorInternal::parent
Scene::SceneObjectWPtr SceneEditorInternal::parent( void ) const
{
	return m_parent;
}

// ** SceneEditorInternal::isPrivate
bool SceneEditorInternal::isPrivate( void ) const
{
	return m_flags.is( Private );
}

// ** SceneEditorInternal::isHighlighted
bool SceneEditorInternal::isHighlighted( void ) const
{
	return m_flags.is( Highlighted );
}

// ** SceneEditorInternal::setHighlighted
void SceneEditorInternal::setHighlighted( bool value )
{
	m_flags.set( Highlighted, value );
}

// ** SceneEditorInternal::isSelected
bool SceneEditorInternal::isSelected( void ) const
{
	return m_flags.is( Selected );
}

// ** SceneEditorInternal::setSelected
void SceneEditorInternal::setSelected( bool value )
{
	m_flags.set( Selected, value );
}

} // namespace Editors

// -------------------------------------------------------------------- Composer -------------------------------------------------------------------- //

// ** Composer::kAssetMime
const String Composer::kAssetMime = "text/uri-list";

// ** Composer::Composer
Composer::Composer( int argc, char ** argv ) : QApplication( argc, argv ), m_project( NULL )
{
    // Setup default logger
    Logger::setStandardLogger();

    // Set application name
    setApplicationName( "Dreemchest Composer" );

    // Create the main window
    m_mainWindow = new Ui::MainWindow( applicationName() );

    // Create the file system
	m_fileSystem = new FileSystem( this );

    // Setup default log handlers
	Logger::setStandardLogger();
}

// ** Composer::project
ProjectQPtr Composer::project( void ) const
{
	return m_project;
}

// ** Composer::window
Ui::MainWindowQPtr Composer::window( void ) const
{
	return m_mainWindow;
}

// ** Composer::fileSystem
FileSystemQPtr Composer::fileSystem( void ) const
{
	return m_fileSystem;
}

// ** Composer::initialize
bool Composer::initialize( void )
{
	// Initialize the main window
	if( !m_mainWindow->initialize( this ) ) {
		return false;
	}

	// Add default menues
	m_menues[FileMenu] = m_mainWindow->addMenu( "&File" );
	m_menues[EditMenu] = m_mainWindow->addMenu( "&Edit" );

	// Add actions
	Ui::ActionQPtr create	= m_menues[FileMenu]->addAction( "&Create Project", BindAction( Composer::menuCreateProject ), "Ctrl+N", ":Common/Common/new.png" );
	Ui::ActionQPtr open	= m_menues[FileMenu]->addAction( "&Open Project", BindAction( Composer::menuOpenProject ), "Ctrl+O", ":Common/Common/open.png" );
	Ui::ActionQPtr save	= m_menues[FileMenu]->addAction( "&Save Project", BindAction( Composer::menuSaveProject ), "Ctrl+S", ":Common/Common/save.png" );

	// Add actions
	Ui::ActionQPtr undo	= m_menues[EditMenu]->addAction( "&Undo", BindAction( Composer::menuUndo ), "Ctrl+Z", ":Common/Common/undo.png" );
	Ui::ActionQPtr redo	= m_menues[EditMenu]->addAction( "&Redo", BindAction( Composer::menuRedo ), "Ctrl+Y", ":Common/Common/redo.png" );

	// Create tool bars
	Ui::ToolBarQPtr tools = m_mainWindow->addToolBar();
	tools->addAction( create );
	tools->addAction( open );
	tools->addAction( save );
	tools->addSeparator();
	tools->addAction( undo );
	tools->addAction( redo );

	return true;
}

// ** Composer::menuCreateProject
void Composer::menuCreateProject( Ui::ActionQPtr action )
{
	// Select the directory
	String path = m_fileSystem->selectExistingDirectory( "Create Project" );

	if( path == "" ) {
		return;
	}

	createProject( path );
}

// ** Composer::menuOpenProject
void Composer::menuOpenProject( Ui::ActionQPtr action )
{
	// Select the directory
	String path = m_fileSystem->selectExistingDirectory( "Open Project" );

	if( path == "" ) {
		return;
	}

	openProject( path );
}

// ** Composer::menuSaveProject
void Composer::menuSaveProject( Ui::ActionQPtr action )
{
	if( Ui::DocumentQPtr document = m_mainWindow->activeDocument() ) {
        document->assetEditor()->save();
    }
}

// ** Composer::menuUndo
void Composer::menuUndo( Ui::ActionQPtr action )
{
	m_mainWindow->message( "Not implemented yet.", Ui::MessageWarning );
}

// ** Composer::menuRedo
void Composer::menuRedo( Ui::ActionQPtr action )
{
	m_mainWindow->message( "Not implemented yet.", Ui::MessageWarning );
}

// ** Composer::createProject
void Composer::createProject( const String& path )
{
    // Close active project
    closeProject();

	// Create project instance
	m_project = new Project( this, path );

	// Create all project folders
	for( s32 i = 0; i < Project::TotalPaths; i++ ) {
		m_fileSystem->createDirectory( m_project->absolutePath( i ) );
	}

	// Emit the signal
    emit projectCreated( m_project );

	// Open created project
	openProject( path );
}

// ** Composer::closeProject
void Composer::closeProject( void )
{
    // No project opened
    if( !m_project ) {
        return;
    }

    // Emit the signal
    emit projectClosed( m_project );

    // Destroy project
    delete m_project;
    m_project = NULL;
}

// ** Composer::assetFromMime
Assets::Handle Composer::assetFromMime( MimeDataQPtr mime ) const
{
	Assets::AssetSet assets = assetsFromMime( mime );

	if( assets.empty() ) {
		return Assets::Handle();
	}

	return *assets.begin();
}

// ** Composer::assetsFromMime
Assets::AssetSet Composer::assetsFromMime( MimeDataQPtr mime ) const
{
	// Resulting asset set
	Assets::AssetSet result;

	// Get an array of attached assets
	QList<QUrl> assets = mime->urls();

	// Add assets to scene
	foreach( QUrl url, assets ) {
		// Read an attached meta data
		Archive meta = m_project->assetFileSystem()->metaData( url.toLocalFile().toStdString() );

        if( !meta.isValid() ) {
			continue;	// Unsupported asset type or just a folder
		}

        DC_ABORT_IF( !meta.type()->is<KeyValue>(), "asset meta data expected to be a KeyValue type" );

		// Find asset by UUID.
        String uuid = meta.as<KeyValue>().get<String>( "uuid" );

		Assets::Handle asset = m_project->assets().findAsset( uuid );
		DC_BREAK_IF( !asset.isValid() );

		// Add to set.
		result.insert( asset );
	}

	return result;
}

// ** Composer::openProject
void Composer::openProject( const String& path )
{
    // Close active project
    closeProject();

	// Create project instance
	m_project = new Project( this, path );

	// Emit the signal
    emit projectOpened( m_project );

	// Setup menues
	//m_menues[EditMenu]	 = m_mainWindow->addMenu( "&Edit" );
	m_menues[ViewMenu]	 = m_mainWindow->addMenu( "&View" );
	m_menues[AssetsMenu] = m_mainWindow->addMenu( "&Assets" );

	// Fill assets menu
	m_project->fillAssetMenu( m_menues[AssetsMenu] );
}

DC_END_COMPOSER

// ** main
int main(int argc, char *argv[])
{
	QCoreApplication::setLibraryPaths( QCoreApplication::libraryPaths() << "." << "imageformats" << "platforms" );

    Composer app( argc, argv );

    if( !app.initialize() ) {
        return -1;
    }

    // Open the project
	app.openProject( "~TestProject" );

    return app.exec();
}<commit_msg>Modified: default composer locale<commit_after>/**************************************************************************

 The MIT License (MIT)

 Copyright (c) 2015 Dmitry Sovetov

 https://github.com/dmsovetov

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

 **************************************************************************/

#include "Composer.h"

#include "FileSystem.h"

#include "Widgets/Menu.h"
#include "Widgets/MainWindow.h"
#include "Widgets/AssetTree.h"

#include "Project/Project.h"

DC_BEGIN_COMPOSER

namespace Editors {

// --------------------------------------------------------------- SceneEditorInternal -------------------------------------------------------------- //

// ** SceneEditorInternal::SceneEditorInternal
SceneEditorInternal::SceneEditorInternal( Scene::SceneObjectWPtr parent, u8 flags ) : m_parent( parent ), m_flags( flags )
{

}

// ** SceneEditorInternal::parent
Scene::SceneObjectWPtr SceneEditorInternal::parent( void ) const
{
	return m_parent;
}

// ** SceneEditorInternal::isPrivate
bool SceneEditorInternal::isPrivate( void ) const
{
	return m_flags.is( Private );
}

// ** SceneEditorInternal::isHighlighted
bool SceneEditorInternal::isHighlighted( void ) const
{
	return m_flags.is( Highlighted );
}

// ** SceneEditorInternal::setHighlighted
void SceneEditorInternal::setHighlighted( bool value )
{
	m_flags.set( Highlighted, value );
}

// ** SceneEditorInternal::isSelected
bool SceneEditorInternal::isSelected( void ) const
{
	return m_flags.is( Selected );
}

// ** SceneEditorInternal::setSelected
void SceneEditorInternal::setSelected( bool value )
{
	m_flags.set( Selected, value );
}

} // namespace Editors

// -------------------------------------------------------------------- Composer -------------------------------------------------------------------- //

// ** Composer::kAssetMime
const String Composer::kAssetMime = "text/uri-list";

// ** Composer::Composer
Composer::Composer( int argc, char ** argv ) : QApplication( argc, argv ), m_project( NULL )
{
    // Setup default logger
    Logger::setStandardLogger();

    // Set application name
    setApplicationName( "Dreemchest Composer" );

    // Create the main window
    m_mainWindow = new Ui::MainWindow( applicationName() );

    // Create the file system
	m_fileSystem = new FileSystem( this );

    // Setup default log handlers
	Logger::setStandardLogger();
}

// ** Composer::project
ProjectQPtr Composer::project( void ) const
{
	return m_project;
}

// ** Composer::window
Ui::MainWindowQPtr Composer::window( void ) const
{
	return m_mainWindow;
}

// ** Composer::fileSystem
FileSystemQPtr Composer::fileSystem( void ) const
{
	return m_fileSystem;
}

// ** Composer::initialize
bool Composer::initialize( void )
{
	// Initialize the main window
	if( !m_mainWindow->initialize( this ) ) {
		return false;
	}

	// Add default menues
	m_menues[FileMenu] = m_mainWindow->addMenu( "&File" );
	m_menues[EditMenu] = m_mainWindow->addMenu( "&Edit" );

	// Add actions
	Ui::ActionQPtr create	= m_menues[FileMenu]->addAction( "&Create Project", BindAction( Composer::menuCreateProject ), "Ctrl+N", ":Common/Common/new.png" );
	Ui::ActionQPtr open	= m_menues[FileMenu]->addAction( "&Open Project", BindAction( Composer::menuOpenProject ), "Ctrl+O", ":Common/Common/open.png" );
	Ui::ActionQPtr save	= m_menues[FileMenu]->addAction( "&Save Project", BindAction( Composer::menuSaveProject ), "Ctrl+S", ":Common/Common/save.png" );

	// Add actions
	Ui::ActionQPtr undo	= m_menues[EditMenu]->addAction( "&Undo", BindAction( Composer::menuUndo ), "Ctrl+Z", ":Common/Common/undo.png" );
	Ui::ActionQPtr redo	= m_menues[EditMenu]->addAction( "&Redo", BindAction( Composer::menuRedo ), "Ctrl+Y", ":Common/Common/redo.png" );

	// Create tool bars
	Ui::ToolBarQPtr tools = m_mainWindow->addToolBar();
	tools->addAction( create );
	tools->addAction( open );
	tools->addAction( save );
	tools->addSeparator();
	tools->addAction( undo );
	tools->addAction( redo );

	return true;
}

// ** Composer::menuCreateProject
void Composer::menuCreateProject( Ui::ActionQPtr action )
{
	// Select the directory
	String path = m_fileSystem->selectExistingDirectory( "Create Project" );

	if( path == "" ) {
		return;
	}

	createProject( path );
}

// ** Composer::menuOpenProject
void Composer::menuOpenProject( Ui::ActionQPtr action )
{
	// Select the directory
	String path = m_fileSystem->selectExistingDirectory( "Open Project" );

	if( path == "" ) {
		return;
	}

	openProject( path );
}

// ** Composer::menuSaveProject
void Composer::menuSaveProject( Ui::ActionQPtr action )
{
	if( Ui::DocumentQPtr document = m_mainWindow->activeDocument() ) {
        document->assetEditor()->save();
    }
}

// ** Composer::menuUndo
void Composer::menuUndo( Ui::ActionQPtr action )
{
	m_mainWindow->message( "Not implemented yet.", Ui::MessageWarning );
}

// ** Composer::menuRedo
void Composer::menuRedo( Ui::ActionQPtr action )
{
	m_mainWindow->message( "Not implemented yet.", Ui::MessageWarning );
}

// ** Composer::createProject
void Composer::createProject( const String& path )
{
    // Close active project
    closeProject();

	// Create project instance
	m_project = new Project( this, path );

	// Create all project folders
	for( s32 i = 0; i < Project::TotalPaths; i++ ) {
		m_fileSystem->createDirectory( m_project->absolutePath( i ) );
	}

	// Emit the signal
    emit projectCreated( m_project );

	// Open created project
	openProject( path );
}

// ** Composer::closeProject
void Composer::closeProject( void )
{
    // No project opened
    if( !m_project ) {
        return;
    }

    // Emit the signal
    emit projectClosed( m_project );

    // Destroy project
    delete m_project;
    m_project = NULL;
}

// ** Composer::assetFromMime
Assets::Handle Composer::assetFromMime( MimeDataQPtr mime ) const
{
	Assets::AssetSet assets = assetsFromMime( mime );

	if( assets.empty() ) {
		return Assets::Handle();
	}

	return *assets.begin();
}

// ** Composer::assetsFromMime
Assets::AssetSet Composer::assetsFromMime( MimeDataQPtr mime ) const
{
	// Resulting asset set
	Assets::AssetSet result;

	// Get an array of attached assets
	QList<QUrl> assets = mime->urls();

	// Add assets to scene
	foreach( QUrl url, assets ) {
		// Read an attached meta data
		Archive meta = m_project->assetFileSystem()->metaData( url.toLocalFile().toStdString() );

        if( !meta.isValid() ) {
			continue;	// Unsupported asset type or just a folder
		}

        DC_ABORT_IF( !meta.type()->is<KeyValue>(), "asset meta data expected to be a KeyValue type" );

		// Find asset by UUID.
        String uuid = meta.as<KeyValue>().get<String>( "uuid" );

		Assets::Handle asset = m_project->assets().findAsset( uuid );
		DC_BREAK_IF( !asset.isValid() );

		// Add to set.
		result.insert( asset );
	}

	return result;
}

// ** Composer::openProject
void Composer::openProject( const String& path )
{
    // Close active project
    closeProject();

	// Create project instance
	m_project = new Project( this, path );

	// Emit the signal
    emit projectOpened( m_project );

	// Setup menues
	//m_menues[EditMenu]	 = m_mainWindow->addMenu( "&Edit" );
	m_menues[ViewMenu]	 = m_mainWindow->addMenu( "&View" );
	m_menues[AssetsMenu] = m_mainWindow->addMenu( "&Assets" );

	// Fill assets menu
	m_project->fillAssetMenu( m_menues[AssetsMenu] );
}

DC_END_COMPOSER

// ** main
int main(int argc, char *argv[])
{
	QCoreApplication::setLibraryPaths( QCoreApplication::libraryPaths() << "." << "imageformats" << "platforms" );
    QLocale::setDefault( QLocale::c() );

    Composer app( argc, argv );

    if( !app.initialize() ) {
        return -1;
    }

    // Open the project
	app.openProject( "~TestProject" );

    return app.exec();
}<|endoftext|>


<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

#include "condor_common.h"
#include "condor_daemon_core.h"

extern bool operator==(const struct in_addr a, const struct in_addr b);

template class HashTable<pid_t, DaemonCore::PidEntry*>;
template class HashTable<struct in_addr, int>;
<commit_msg>instantiate an ExtArray of type SockEnt, so our socket table grows dynamically<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

#include "condor_common.h"
#include "condor_daemon_core.h"

extern bool operator==(const struct in_addr a, const struct in_addr b);

template class HashTable<pid_t, DaemonCore::PidEntry*>;
template class HashTable<struct in_addr, int>;
template class ExtArray<DaemonCore::SockEnt>;
<|endoftext|>


<commit_before>#include "condor_common.h"
#include "condor_sockfunc.h"

// condor_sockfunc_ex is used by syscall_lib that has minimal
// dependency on condor libs.
//
// make sure that any function included here should not call to
// param(). ipv6_interface.cpp and ipv6_hostname.cpp do call to
// param() thus never include any function using them.
//
// alternative to condor_sockfunc_ex is to  special_stubs.cpp
// it includes simpler version of syscall functions.
// if you do need separate implementation for normal condor code and
// standard universe code, you might want to use special_stubs.cpp

int condor_getsockname(int sockfd, condor_sockaddr& addr)
{
	sockaddr_storage ss;
	socklen_t socklen = sizeof(ss);
	int ret = getsockname(sockfd, (sockaddr*)&ss, &socklen);
	if (ret == 0) {
		addr = condor_sockaddr((sockaddr*)&ss);
	}
	return ret;
}

int condor_getpeername(int sockfd, condor_sockaddr& addr)
{
	sockaddr_storage ss;
	socklen_t socklen = sizeof(ss);
	int ret = getpeername(sockfd, (sockaddr*)&ss, &socklen);
	if (ret == 0) {
		addr = condor_sockaddr((sockaddr*)&ss);
	}
	return ret;
}

<commit_msg>(#4713)  Don't return random garbage off the stack from condor_getsockname() and condor_getpeername().<commit_after>#include "condor_common.h"
#include "condor_sockfunc.h"

// condor_sockfunc_ex is used by syscall_lib that has minimal
// dependency on condor libs.
//
// make sure that any function included here should not call to
// param(). ipv6_interface.cpp and ipv6_hostname.cpp do call to
// param() thus never include any function using them.
//
// alternative to condor_sockfunc_ex is to  special_stubs.cpp
// it includes simpler version of syscall functions.
// if you do need separate implementation for normal condor code and
// standard universe code, you might want to use special_stubs.cpp

int condor_getsockname(int sockfd, condor_sockaddr& addr)
{
	sockaddr_storage ss;
	socklen_t socklen = sizeof(ss);
	memset( & ss, 0, socklen );
	int ret = getsockname(sockfd, (sockaddr*)&ss, &socklen);
	if (ret == 0) {
		addr = condor_sockaddr((sockaddr*)&ss);
	}
	return ret;
}

int condor_getpeername(int sockfd, condor_sockaddr& addr)
{
	sockaddr_storage ss;
	socklen_t socklen = sizeof(ss);
	memset( & ss, 0, socklen );
	int ret = getpeername(sockfd, (sockaddr*)&ss, &socklen);
	if (ret == 0) {
		addr = condor_sockaddr((sockaddr*)&ss);
	}
	return ret;
}

<|endoftext|>


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

#include "event/ManageListener.h"
#include "base/globalsdef.h"

BEGIN_NAMESPACE

//------------------------------------------------------------- Local declarations

class DestroyManageListener{
public:
    DestroyManageListener() {           };
    ~DestroyManageListener(){ ManageListener::releaseAllListeners(); }
};

DestroyManageListener destroyManageListener;

/**
 * ArrayElement container for the Listeners. It does not clone the inner
 * Listener pointer, nor deletes it. Cloning the element does not clone
 * the Listener, which is managed by ManageListener.
 * The only method which deletes the Listener is set(), to replace it
 * with the new one.
 */
class ListenerElement: public ArrayElement {

  public:

    ListenerElement(Listener *_l) : l(_l) {} ;
    ListenerElement(ListenerElement &other) : l(other.l) {} ;

    ~ListenerElement() {}

    void set(Listener *_l) { delete l; l = _l; };
    Listener* get() { return l; };

    ArrayElement* clone() {return new ListenerElement(*this);};

  private:

    Listener *l;
};

/* Static Variables */

ManageListener * ManageListener::instance = 0;

/* Release all the listeners for the given list */
void releaseListeners(ArrayList &list) {
    ListenerElement *l=NULL;

    for(l = (ListenerElement*)list.front(); l; l = (ListenerElement*)list.next()) {
        l->set(NULL);
    }
    list.clear();
}

//-------------------------------- Private Methods ------------------------------

/* Release all the listeners on all the lists */
ManageListener::~ManageListener() {
    releaseListeners(synclisteners);
    releaseListeners(transportlisteners);
    releaseListeners(syncstatuslisteners);
    releaseListeners(syncitemlisteners);
    releaseListeners(syncsourcelisteners);
}

/*
 * Search for the given listener in list.
 *
 * @return the pointer to the element with the same name,
 *         or NULL otherwise.
 */
Listener *ManageListener::lookupListener(const char* name, ArrayList &list) {
    ListenerElement *l=NULL;

    for(l = (ListenerElement*)list.front(); l; l = (ListenerElement*)list.next()) {
        if (l->get()->getName() == name) {
            return l->get();
        }
    }
    return NULL;
}

/* Set a new listener, replacing an existen one or adding it to the list. */
bool ManageListener::setListener(Listener* listener, ArrayList &list) {
    ListenerElement *l=NULL;

    for(l = (ListenerElement*)list.front(); l; l = (ListenerElement*)list.next()) {
        if (l->get()->getName() == listener->getName()) {
            l->set(listener);
            return false;       // Element already in the list, just change it
        }
    }

    // Not found, add it to the list
    ListenerElement newElement(listener);
    list.add(newElement);
    return true;
}

/* Unset a listener, referenced by name. If the listener with that name is
 * not found, it does nothing. */
void ManageListener::unsetListener(const char* name, ArrayList &list) {
    for(int i=0; i<list.size(); i++) {
        ListenerElement *l = dynamic_cast<ListenerElement*>(list[i]);
        if (l->get()->getName() == name) {
            l->set(NULL);
            list.removeElementAt(i);
        }
    }
}

//--------------------------------- Public Methods ------------------------------

/*
 * Get, or create, ManageListener instance
 */
ManageListener& ManageListener::getInstance() {
    if(instance == NULL) {
        instance = new ManageListener();
    }
    return *instance;
}

/*
 * Release all the listeners and the singleton instance.
 */
void ManageListener::releaseAllListeners() {
    if (instance) {
        delete instance;
        instance = NULL;
    }
}

//
// Get listeners (return internal pointer):
//
SyncListener* ManageListener::getSyncListener(const char *name) {
    return dynamic_cast<SyncListener*>(lookupListener(name, synclisteners));
}
TransportListener* ManageListener::getTransportListener(const char *name) {
    return dynamic_cast<TransportListener*>(lookupListener(name, transportlisteners));
}
SyncSourceListener* ManageListener::getSyncSourceListener(const char *name) {
    return dynamic_cast<SyncSourceListener*>(lookupListener(name, syncsourcelisteners));
}
SyncItemListener* ManageListener::getSyncItemListener(const char *name) {
    return dynamic_cast<SyncItemListener*>(lookupListener(name, syncitemlisteners));
}
SyncStatusListener* ManageListener::getSyncStatusListener(const char *name) {
    return dynamic_cast<SyncStatusListener*>(lookupListener(name, syncstatuslisteners));
}

// Get listeners by position.
SyncListener* ManageListener::getSyncListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(synclisteners[pos]);
    return static_cast<SyncListener*>(le->get());
}
TransportListener* ManageListener::getTransportListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(transportlisteners[pos]);
    return static_cast<TransportListener*>(le->get());
}
SyncSourceListener* ManageListener::getSyncSourceListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(syncsourcelisteners[pos]);
    return static_cast<SyncSourceListener*>(le->get());
}
SyncItemListener* ManageListener::getSyncItemListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(syncitemlisteners[pos]);
    return static_cast<SyncItemListener*>(le->get());
}
SyncStatusListener* ManageListener::getSyncStatusListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(syncstatuslisteners[pos]);
    return static_cast<SyncStatusListener*>(le->get());
}

//
// Set listeners:
//
void ManageListener::setSyncListener(SyncListener* listener) {
    setListener(listener, synclisteners);
}

void ManageListener::setTransportListener(TransportListener* listener) {
    setListener(listener, transportlisteners);
}

void ManageListener::setSyncSourceListener(SyncSourceListener* listener) {
    setListener(listener, syncsourcelisteners);
}

void ManageListener::setSyncItemListener(SyncItemListener* listener) {
    setListener(listener, syncitemlisteners);
}

void ManageListener::setSyncStatusListener(SyncStatusListener* listener) {
    setListener(listener, syncstatuslisteners);
}

//
// Unset listeners:
//
void ManageListener::unsetSyncListener(const char *name) {
    unsetListener(name, synclisteners);
}

void ManageListener::unsetTransportListener(const char *name) {
    unsetListener(name, transportlisteners);
}

void ManageListener::unsetSyncSourceListener(const char *name) {
    unsetListener(name, syncsourcelisteners);
}

void ManageListener::unsetSyncItemListener(const char *name) {
    unsetListener(name, syncitemlisteners);
}

void ManageListener::unsetSyncStatusListener(const char *name) {
    unsetListener(name, syncstatuslisteners);
}

END_NAMESPACE

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

#include "event/ManageListener.h"
#include "base/globalsdef.h"

BEGIN_NAMESPACE

//------------------------------------------------------------- Local declarations

class DestroyManageListener{
public:
    DestroyManageListener() {           };
    ~DestroyManageListener(){ ManageListener::releaseAllListeners(); }
};

DestroyManageListener destroyManageListener;

/**
 * ArrayElement container for the Listeners. It does not clone the inner
 * Listener pointer, nor deletes it. Cloning the element does not clone
 * the Listener, which is managed by ManageListener.
 * The only method which deletes the Listener is set(), to replace it
 * with the new one.
 */
class ListenerElement: public ArrayElement {

  public:

    ListenerElement(Listener *_l) : l(_l) {} ;
    ListenerElement(ListenerElement &other) : l(other.l) {} ;

    ~ListenerElement() {}

    void set(Listener *_l) { delete l; l = _l; };
    Listener* get() { return l; };

    ArrayElement* clone() {return new ListenerElement(*this);};

  private:

    Listener *l;
};

/* Static Variables */

ManageListener * ManageListener::instance = 0;

/* Release all the listeners for the given list */
void releaseListeners(ArrayList &list) {
    ListenerElement *l=NULL;

    for(l = (ListenerElement*)list.front(); l; l = (ListenerElement*)list.next()) {
        l->set(NULL);
    }
    list.clear();
}

//-------------------------------- Private Methods ------------------------------

/* Release all the listeners on all the lists */
ManageListener::~ManageListener() {
    releaseListeners(synclisteners);
    releaseListeners(transportlisteners);
    releaseListeners(syncstatuslisteners);
    releaseListeners(syncitemlisteners);
    releaseListeners(syncsourcelisteners);
}

/*
 * Search for the given listener in list.
 *
 * @return the pointer to the element with the same name,
 *         or NULL otherwise.
 */
Listener *ManageListener::lookupListener(const char* name, ArrayList &list) {
    ListenerElement *l=NULL;

    for(l = (ListenerElement*)list.front(); l; l = (ListenerElement*)list.next()) {
        if (l->get()->getName() == name) {
            return l->get();
        }
    }
    return NULL;
}

/* Set a new listener, replacing an existen one or adding it to the list. */
bool ManageListener::setListener(Listener* listener, ArrayList &list) {
    ListenerElement *l=NULL;

    for(l = (ListenerElement*)list.front(); l; l = (ListenerElement*)list.next()) {
        if (l->get()->getName() == listener->getName()) {
            l->set(listener);
            return false;       // Element already in the list, just change it
        }
    }

    // Not found, add it to the list
    ListenerElement newElement(listener);
    list.add(newElement);
    return true;
}

/* Unset a listener, referenced by name. If the listener with that name is
 * not found, it does nothing. */
void ManageListener::unsetListener(const char* name, ArrayList &list) {
    for(int i=0; i<list.size(); i++) {
        ListenerElement *l = static_cast<ListenerElement*>(list[i]);
        if (l->get()->getName() == name) {
            l->set(NULL);
            list.removeElementAt(i);
        }
    }
}

//--------------------------------- Public Methods ------------------------------

/*
 * Get, or create, ManageListener instance
 */
ManageListener& ManageListener::getInstance() {
    if(instance == NULL) {
        instance = new ManageListener();
    }
    return *instance;
}

/*
 * Release all the listeners and the singleton instance.
 */
void ManageListener::releaseAllListeners() {
    if (instance) {
        delete instance;
        instance = NULL;
    }
}

//
// Get listeners (return internal pointer):
//
SyncListener* ManageListener::getSyncListener(const char *name) {
    return static_cast<SyncListener*>(lookupListener(name, synclisteners));
}
TransportListener* ManageListener::getTransportListener(const char *name) {
    return static_cast<TransportListener*>(lookupListener(name, transportlisteners));
}
SyncSourceListener* ManageListener::getSyncSourceListener(const char *name) {
    return static_cast<SyncSourceListener*>(lookupListener(name, syncsourcelisteners));
}
SyncItemListener* ManageListener::getSyncItemListener(const char *name) {
    return static_cast<SyncItemListener*>(lookupListener(name, syncitemlisteners));
}
SyncStatusListener* ManageListener::getSyncStatusListener(const char *name) {
    return static_cast<SyncStatusListener*>(lookupListener(name, syncstatuslisteners));
}

// Get listeners by position.
SyncListener* ManageListener::getSyncListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(synclisteners[pos]);
    return static_cast<SyncListener*>(le->get());
}
TransportListener* ManageListener::getTransportListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(transportlisteners[pos]);
    return static_cast<TransportListener*>(le->get());
}
SyncSourceListener* ManageListener::getSyncSourceListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(syncsourcelisteners[pos]);
    return static_cast<SyncSourceListener*>(le->get());
}
SyncItemListener* ManageListener::getSyncItemListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(syncitemlisteners[pos]);
    return static_cast<SyncItemListener*>(le->get());
}
SyncStatusListener* ManageListener::getSyncStatusListener(int pos) {
    ListenerElement* le = static_cast<ListenerElement*>(syncstatuslisteners[pos]);
    return static_cast<SyncStatusListener*>(le->get());
}

//
// Set listeners:
//
void ManageListener::setSyncListener(SyncListener* listener) {
    setListener(listener, synclisteners);
}

void ManageListener::setTransportListener(TransportListener* listener) {
    setListener(listener, transportlisteners);
}

void ManageListener::setSyncSourceListener(SyncSourceListener* listener) {
    setListener(listener, syncsourcelisteners);
}

void ManageListener::setSyncItemListener(SyncItemListener* listener) {
    setListener(listener, syncitemlisteners);
}

void ManageListener::setSyncStatusListener(SyncStatusListener* listener) {
    setListener(listener, syncstatuslisteners);
}

//
// Unset listeners:
//
void ManageListener::unsetSyncListener(const char *name) {
    unsetListener(name, synclisteners);
}

void ManageListener::unsetTransportListener(const char *name) {
    unsetListener(name, transportlisteners);
}

void ManageListener::unsetSyncSourceListener(const char *name) {
    unsetListener(name, syncsourcelisteners);
}

void ManageListener::unsetSyncItemListener(const char *name) {
    unsetListener(name, syncitemlisteners);
}

void ManageListener::unsetSyncStatusListener(const char *name) {
    unsetListener(name, syncstatuslisteners);
}

END_NAMESPACE

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 MIPS Technologies, 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 the copyright holders 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.
 *
 * Authors: Korey Sewell
 *
 */

#ifndef __CPU_INORDER_CACHE_UNIT_HH__
#define __CPU_INORDER_CACHE_UNIT_HH__

#include <list>
#include <string>
#include <vector>

#include "arch/predecoder.hh"
#include "arch/tlb.hh"
#include "config/the_isa.hh"
#include "cpu/inorder/inorder_dyn_inst.hh"
#include "cpu/inorder/pipeline_traits.hh"
#include "cpu/inorder/resource.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
#include "mem/port.hh"
#include "params/InOrderCPU.hh"
#include "sim/sim_object.hh"

class CacheRequest;
typedef CacheRequest* CacheReqPtr;

class CacheReqPacket;
typedef CacheReqPacket* CacheReqPktPtr;

class CacheUnit : public Resource
{
  public:
    typedef ThePipeline::DynInstPtr DynInstPtr;

  public:
    CacheUnit(std::string res_name, int res_id, int res_width,
              int res_latency, InOrderCPU *_cpu, ThePipeline::Params *params);

    enum Command {
        InitiateReadData,
        CompleteReadData,
        InitiateWriteData,
        CompleteWriteData,
        InitSecondSplitRead,
        InitSecondSplitWrite,
        CompleteSecondSplitRead,
        CompleteSecondSplitWrite
    };

  public:
    /** CachePort class for the Cache Unit.  Handles doing the
     * communication with the cache/memory.
     */
    class CachePort : public Port
    {
      protected:
        /** Pointer to cache port unit */
        CacheUnit *cachePortUnit;

      public:
        /** Default constructor. */
        CachePort(CacheUnit *_cachePortUnit)
          : Port(_cachePortUnit->name() + "-cache-port",
                 (MemObject*)_cachePortUnit->cpu),
            cachePortUnit(_cachePortUnit), snoopRangeSent(false)
        { }

        bool snoopRangeSent;

        void setPeer(Port *port);

      protected:
        /** Atomic version of receive.  Panics. */
        Tick recvAtomic(PacketPtr pkt);

        /** Functional version of receive.*/
        void recvFunctional(PacketPtr pkt);

        /** Receives status change.  Other than range changing, panics. */
        void recvStatusChange(Status status);

        /** Returns the address ranges of this device. */
        void getDeviceAddressRanges(AddrRangeList &resp,
                                    bool &snoop)
        {  resp.clear(); snoop = true; }

        /** Timing version of receive */
        bool recvTiming(PacketPtr pkt);

        /** Handles doing a retry of a failed fetch. */
        void recvRetry();
    };

    void init();

    ResourceRequest* getRequest(DynInstPtr _inst, int stage_num,
                                int res_idx, int slot_num,
                                unsigned cmd);

    ResReqPtr findRequest(DynInstPtr inst);
    ResReqPtr findRequest(DynInstPtr inst, int idx);

    void requestAgain(DynInstPtr inst, bool &try_request);

    virtual int getSlot(DynInstPtr inst);

    /** Executes one of the commands from the "Command" enum */
    virtual void execute(int slot_num);

    virtual void squash(DynInstPtr inst, int stage_num,
                InstSeqNum squash_seq_num, ThreadID tid);

    void squashDueToMemStall(DynInstPtr inst, int stage_num,
                             InstSeqNum squash_seq_num, ThreadID tid);

    virtual void squashCacheRequest(CacheReqPtr req_ptr);

    /** After memory request is completedd in the cache, then do final
        processing to complete the request in the CPU.
    */
    virtual void processCacheCompletion(PacketPtr pkt);

    /** Create request that will interface w/TLB and Memory objects */
    virtual void setupMemRequest(DynInstPtr inst, CacheReqPtr cache_req,
                                 int acc_size, int flags);

    void finishCacheUnitReq(DynInstPtr inst, CacheRequest *cache_req);

    void buildDataPacket(CacheRequest *cache_req);

    bool processSquash(CacheReqPacket *cache_pkt);

#if !FULL_SYSTEM
    void trap(Fault fault, ThreadID tid, DynInstPtr inst);
#endif
    void recvRetry();

    /** Returns a specific port. */
    Port *getPort(const std::string &if_name, int idx);

    Fault read(DynInstPtr inst, Addr addr,
               uint8_t *data, unsigned size, unsigned flags);

    Fault write(DynInstPtr inst, uint8_t *data, unsigned size,
                Addr addr, unsigned flags, uint64_t *res);

    void doTLBAccess(DynInstPtr inst, CacheReqPtr cache_req, int acc_size,
                      int flags,  TheISA::TLB::Mode tlb_mode);

    /** Read/Write on behalf of an instruction.
     *  curResSlot needs to be a valid value in instruction.
     */
    void doCacheAccess(DynInstPtr inst, uint64_t *write_result=NULL,
                        CacheReqPtr split_req=NULL);

    uint64_t getMemData(Packet *packet);

    void setAddrDependency(DynInstPtr inst);
    virtual void removeAddrDependency(DynInstPtr inst);

  protected:
    /** Cache interface. */
    CachePort *cachePort;

    bool cachePortBlocked;

    std::list<Addr> addrList[ThePipeline::MaxThreads];

    m5::hash_map<Addr, InstSeqNum> addrMap[ThePipeline::MaxThreads];

  public:
    int cacheBlkSize;

    int cacheBlkMask;

    /** Align a PC to the start of the Cache block. */
    Addr cacheBlockAlign(Addr addr)
    {
        return (addr & ~(cacheBlkMask));
    }

    bool tlbBlocked[ThePipeline::MaxThreads];
    InstSeqNum tlbBlockSeqNum[ThePipeline::MaxThreads];

    TheISA::TLB* tlb();
    TheISA::TLB *_tlb;
};

class CacheUnitEvent : public ResourceEvent {
  public:
    const std::string name() const
    {
        return "CacheUnitEvent";
    }

    /** Constructs a resource event. */
    CacheUnitEvent();
    virtual ~CacheUnitEvent() {}

    /** Processes a resource event. */
    void process();
};

//@todo: Move into CacheUnit Class for private access to "valid" field
class CacheRequest : public ResourceRequest
{
  public:
    CacheRequest(CacheUnit *cres)
        :  ResourceRequest(cres), memReq(NULL), reqData(NULL),
           dataPkt(NULL), memAccComplete(false),
           memAccPending(false), tlbStall(false), splitAccess(false),
           splitAccessNum(-1), split2ndAccess(false),
           fetchBufferFill(false)
    { }

    virtual ~CacheRequest()
    {
        if (reqData && !splitAccess)
            delete [] reqData;
    }

    void setRequest(DynInstPtr _inst, int stage_num, int res_idx, int slot_num,
                    unsigned _cmd, MemCmd::Command pkt_cmd, int idx)
    {
        pktCmd = pkt_cmd;
        instIdx = idx;

        ResourceRequest::setRequest(_inst, stage_num, res_idx, slot_num, _cmd);
    }

    void clearRequest();

    virtual PacketDataPtr getData()
    { return reqData; }

    void
    setMemAccCompleted(bool completed = true)
    {
        memAccComplete = completed;
    }

    bool is2ndSplit()
    {
        return split2ndAccess;
    }

    bool isMemAccComplete() { return memAccComplete; }

    void setMemAccPending(bool pending = true) { memAccPending = pending; }
    bool isMemAccPending() { return memAccPending; }

    //Make this data private/protected!
    MemCmd::Command pktCmd;
    RequestPtr memReq;
    PacketDataPtr reqData;
    CacheReqPacket *dataPkt;

    bool memAccComplete;
    bool memAccPending;
    bool tlbStall;

    bool splitAccess;
    int splitAccessNum;
    bool split2ndAccess;
    int instIdx;

    /** Should we expect block from cache access or fetch buffer? */
    bool fetchBufferFill;
};

class CacheReqPacket : public Packet
{
  public:
    CacheReqPacket(CacheRequest *_req,
                   Command _cmd, short _dest, int _idx = 0)
        : Packet(&(*_req->memReq), _cmd, _dest), cacheReq(_req),
          instIdx(_idx), hasSlot(false), reqData(NULL), memReq(NULL)
    {

    }

    CacheRequest *cacheReq;
    int instIdx;
    bool hasSlot;
    PacketDataPtr reqData;
    RequestPtr memReq;
};

#endif //__CPU_CACHE_UNIT_HH__
<commit_msg>InOrder: Make cache_unit.hh include hashmap.hh explicitly, not transitively.<commit_after>/*
 * Copyright (c) 2007 MIPS Technologies, 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 the copyright holders 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.
 *
 * Authors: Korey Sewell
 *
 */

#ifndef __CPU_INORDER_CACHE_UNIT_HH__
#define __CPU_INORDER_CACHE_UNIT_HH__

#include <list>
#include <string>
#include <vector>

#include "arch/predecoder.hh"
#include "arch/tlb.hh"
#include "base/hashmap.hh"
#include "config/the_isa.hh"
#include "cpu/inorder/inorder_dyn_inst.hh"
#include "cpu/inorder/pipeline_traits.hh"
#include "cpu/inorder/resource.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
#include "mem/port.hh"
#include "params/InOrderCPU.hh"
#include "sim/sim_object.hh"

class CacheRequest;
typedef CacheRequest* CacheReqPtr;

class CacheReqPacket;
typedef CacheReqPacket* CacheReqPktPtr;

class CacheUnit : public Resource
{
  public:
    typedef ThePipeline::DynInstPtr DynInstPtr;

  public:
    CacheUnit(std::string res_name, int res_id, int res_width,
              int res_latency, InOrderCPU *_cpu, ThePipeline::Params *params);

    enum Command {
        InitiateReadData,
        CompleteReadData,
        InitiateWriteData,
        CompleteWriteData,
        InitSecondSplitRead,
        InitSecondSplitWrite,
        CompleteSecondSplitRead,
        CompleteSecondSplitWrite
    };

  public:
    /** CachePort class for the Cache Unit.  Handles doing the
     * communication with the cache/memory.
     */
    class CachePort : public Port
    {
      protected:
        /** Pointer to cache port unit */
        CacheUnit *cachePortUnit;

      public:
        /** Default constructor. */
        CachePort(CacheUnit *_cachePortUnit)
          : Port(_cachePortUnit->name() + "-cache-port",
                 (MemObject*)_cachePortUnit->cpu),
            cachePortUnit(_cachePortUnit), snoopRangeSent(false)
        { }

        bool snoopRangeSent;

        void setPeer(Port *port);

      protected:
        /** Atomic version of receive.  Panics. */
        Tick recvAtomic(PacketPtr pkt);

        /** Functional version of receive.*/
        void recvFunctional(PacketPtr pkt);

        /** Receives status change.  Other than range changing, panics. */
        void recvStatusChange(Status status);

        /** Returns the address ranges of this device. */
        void getDeviceAddressRanges(AddrRangeList &resp,
                                    bool &snoop)
        {  resp.clear(); snoop = true; }

        /** Timing version of receive */
        bool recvTiming(PacketPtr pkt);

        /** Handles doing a retry of a failed fetch. */
        void recvRetry();
    };

    void init();

    ResourceRequest* getRequest(DynInstPtr _inst, int stage_num,
                                int res_idx, int slot_num,
                                unsigned cmd);

    ResReqPtr findRequest(DynInstPtr inst);
    ResReqPtr findRequest(DynInstPtr inst, int idx);

    void requestAgain(DynInstPtr inst, bool &try_request);

    virtual int getSlot(DynInstPtr inst);

    /** Executes one of the commands from the "Command" enum */
    virtual void execute(int slot_num);

    virtual void squash(DynInstPtr inst, int stage_num,
                InstSeqNum squash_seq_num, ThreadID tid);

    void squashDueToMemStall(DynInstPtr inst, int stage_num,
                             InstSeqNum squash_seq_num, ThreadID tid);

    virtual void squashCacheRequest(CacheReqPtr req_ptr);

    /** After memory request is completedd in the cache, then do final
        processing to complete the request in the CPU.
    */
    virtual void processCacheCompletion(PacketPtr pkt);

    /** Create request that will interface w/TLB and Memory objects */
    virtual void setupMemRequest(DynInstPtr inst, CacheReqPtr cache_req,
                                 int acc_size, int flags);

    void finishCacheUnitReq(DynInstPtr inst, CacheRequest *cache_req);

    void buildDataPacket(CacheRequest *cache_req);

    bool processSquash(CacheReqPacket *cache_pkt);

#if !FULL_SYSTEM
    void trap(Fault fault, ThreadID tid, DynInstPtr inst);
#endif
    void recvRetry();

    /** Returns a specific port. */
    Port *getPort(const std::string &if_name, int idx);

    Fault read(DynInstPtr inst, Addr addr,
               uint8_t *data, unsigned size, unsigned flags);

    Fault write(DynInstPtr inst, uint8_t *data, unsigned size,
                Addr addr, unsigned flags, uint64_t *res);

    void doTLBAccess(DynInstPtr inst, CacheReqPtr cache_req, int acc_size,
                      int flags,  TheISA::TLB::Mode tlb_mode);

    /** Read/Write on behalf of an instruction.
     *  curResSlot needs to be a valid value in instruction.
     */
    void doCacheAccess(DynInstPtr inst, uint64_t *write_result=NULL,
                        CacheReqPtr split_req=NULL);

    uint64_t getMemData(Packet *packet);

    void setAddrDependency(DynInstPtr inst);
    virtual void removeAddrDependency(DynInstPtr inst);

  protected:
    /** Cache interface. */
    CachePort *cachePort;

    bool cachePortBlocked;

    std::list<Addr> addrList[ThePipeline::MaxThreads];

    m5::hash_map<Addr, InstSeqNum> addrMap[ThePipeline::MaxThreads];

  public:
    int cacheBlkSize;

    int cacheBlkMask;

    /** Align a PC to the start of the Cache block. */
    Addr cacheBlockAlign(Addr addr)
    {
        return (addr & ~(cacheBlkMask));
    }

    bool tlbBlocked[ThePipeline::MaxThreads];
    InstSeqNum tlbBlockSeqNum[ThePipeline::MaxThreads];

    TheISA::TLB* tlb();
    TheISA::TLB *_tlb;
};

class CacheUnitEvent : public ResourceEvent {
  public:
    const std::string name() const
    {
        return "CacheUnitEvent";
    }

    /** Constructs a resource event. */
    CacheUnitEvent();
    virtual ~CacheUnitEvent() {}

    /** Processes a resource event. */
    void process();
};

//@todo: Move into CacheUnit Class for private access to "valid" field
class CacheRequest : public ResourceRequest
{
  public:
    CacheRequest(CacheUnit *cres)
        :  ResourceRequest(cres), memReq(NULL), reqData(NULL),
           dataPkt(NULL), memAccComplete(false),
           memAccPending(false), tlbStall(false), splitAccess(false),
           splitAccessNum(-1), split2ndAccess(false),
           fetchBufferFill(false)
    { }

    virtual ~CacheRequest()
    {
        if (reqData && !splitAccess)
            delete [] reqData;
    }

    void setRequest(DynInstPtr _inst, int stage_num, int res_idx, int slot_num,
                    unsigned _cmd, MemCmd::Command pkt_cmd, int idx)
    {
        pktCmd = pkt_cmd;
        instIdx = idx;

        ResourceRequest::setRequest(_inst, stage_num, res_idx, slot_num, _cmd);
    }

    void clearRequest();

    virtual PacketDataPtr getData()
    { return reqData; }

    void
    setMemAccCompleted(bool completed = true)
    {
        memAccComplete = completed;
    }

    bool is2ndSplit()
    {
        return split2ndAccess;
    }

    bool isMemAccComplete() { return memAccComplete; }

    void setMemAccPending(bool pending = true) { memAccPending = pending; }
    bool isMemAccPending() { return memAccPending; }

    //Make this data private/protected!
    MemCmd::Command pktCmd;
    RequestPtr memReq;
    PacketDataPtr reqData;
    CacheReqPacket *dataPkt;

    bool memAccComplete;
    bool memAccPending;
    bool tlbStall;

    bool splitAccess;
    int splitAccessNum;
    bool split2ndAccess;
    int instIdx;

    /** Should we expect block from cache access or fetch buffer? */
    bool fetchBufferFill;
};

class CacheReqPacket : public Packet
{
  public:
    CacheReqPacket(CacheRequest *_req,
                   Command _cmd, short _dest, int _idx = 0)
        : Packet(&(*_req->memReq), _cmd, _dest), cacheReq(_req),
          instIdx(_idx), hasSlot(false), reqData(NULL), memReq(NULL)
    {

    }

    CacheRequest *cacheReq;
    int instIdx;
    bool hasSlot;
    PacketDataPtr reqData;
    RequestPtr memReq;
};

#endif //__CPU_CACHE_UNIT_HH__
<|endoftext|>