<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
// Class header file
#include "KeyTable.hpp"

#include <memory>

#include <XalanDOM/XalanElement.hpp>
#include <XalanDOM/XalanNamedNodeMap.hpp>
#include <XalanDOM/XalanNode.hpp>
#include <XalanDOM/XalanNodeList.hpp>

#include <XPath/XPath.hpp>
#include <XPath/XPathExecutionContext.hpp>

#include "KeyDeclaration.hpp"

const MutableNodeRefList	KeyTable::s_dummyList;

KeyTable::KeyTable(
			XalanNode*							doc,
			XalanNode*							startNode,
			const PrefixResolver&				resolver,
			const XalanDOMString&				name,
			const KeyDeclarationVectorType&		keyDeclarations,
			XPathExecutionContext&				executionContext) :
	m_docKey(doc),
	m_keys()
{
    XalanNode*	pos = startNode;

	bool		fDone = false;

    // Do a non-recursive pre-walk over the tree.
    while(0 != pos && fDone == false)
    {
		const KeyDeclarationVectorType::size_type	nDeclarations =
			keyDeclarations.size();

		// We're going to have to walk the attribute list
		// if it's an element, so get the attributes.
		const XalanNamedNodeMap*	attrs = 0;

		int							nNodes = 0;

		if(XalanNode::ELEMENT_NODE == pos->getNodeType())
		{
			attrs = static_cast<const XalanElement*>(pos)->getAttributes();

			nNodes = attrs->getLength();

			if(0 == nNodes)
			{
				attrs = 0;
			}
		}

		// Walk the primary node, and each of the attributes.
		// This loop is a little strange... it is meant to always
		// execute once, then execute for each of the attributes.
		XalanNode*	testNode = pos;

		for(int nodeIndex = -1; nodeIndex < nNodes && fDone == false;)
		{
			// Walk through each of the declarations made with xsl:key
			for(unsigned int i = 0; i < nDeclarations && fDone == false; i++)
			{
				const KeyDeclaration&	kd = keyDeclarations[i];

				if (equals(kd.getName(), name))
				{
					if (kd.getInConstruction() == true)
					{
						fDone = true;
					}
					else
					{
						kd.beginConstruction();

						// See if our node matches the given key declaration according to
						// the match attribute on xsl:key.
						const double	score = kd.getMatchPattern().getMatchScore(testNode,
																				   resolver,
																				   executionContext);

						if(score == kd.getMatchPattern().s_MatchScoreNone)
						{
							kd.endConstruction();
						}
						else
						{
							// Query from the node, according the the select pattern in the
							// use attribute in xsl:key.
							const XObject* const	xuse =
								kd.getUse().execute(testNode, resolver, NodeRefList(), executionContext);

							const NodeRefListBase*	nl = 0;
							unsigned int nUseValues;
							XalanDOMString		exprResult;
							if(xuse->getType() != xuse->eTypeNodeSet)
							{
								nUseValues = 1;
								exprResult = xuse->str();
							}
							else
							{
								nl = &xuse->nodeset();
								// Use each node in the node list as a key value that we'll be
								// able to use to look up the given node.
								nUseValues = nl->getLength();
							}
							// Use each node in the node list as a key value that we'll be
							// able to use to look up the given node.
							for(unsigned int k = 0; k < nUseValues; k++)
							{

								// Use getExpr to get the string value of the given node. I hope
								// the string assumption is the right thing... I can't see how
								// it could work any other way.
								if(0 != nl)
								{
									XalanNode* const	useNode = nl->item(k);
									assert(useNode != 0);

									exprResult = executionContext.getNodeData(*useNode);
								}

								MutableNodeRefList&		keyNodes =
										m_keys[kd.getName()][exprResult];

								// See if the matched node is already in the
								// table set.  If it is there, we're done, otherwise
								// add it.
								bool foundit = false;

								const unsigned int	nKeyNodes = keyNodes.getLength(); //size();

								for(unsigned int j = 0; j < nKeyNodes; j++)
								{
									if(testNode == keyNodes.item(j))
									{
										foundit = true;
										break;
									}
								} // end for j

								if(foundit == false)
								{
									keyNodes.addNode(testNode);
								}
							} // end for(int k = 0; k < nUseValues; k++)

							kd.endConstruction();
						} // if(score != kd.getMatchPattern().s_MatchScoreNone)
					} // if (kd.getInConstruction() == true)
				} // if (equals(kd.getName(), name)
			} // end for(int i = 0; i < nDeclarations; i++)

			if (fDone == false)
			{
				nodeIndex++;

				if(0 != attrs)
				{
					testNode = attrs->item(nodeIndex);
				}
			}
		} // for(int nodeIndex = -1; nodeIndex < nNodes;)

		if (fDone == false)
		{
			// The rest of this is getting the next prewalk position in
			// the tree.

			XalanNode*	nextNode = pos->getFirstChild();

			while(0 == nextNode)
			{
				if(startNode == pos)
				{
					break;
				}
				else
				{
					nextNode = pos->getNextSibling();

					if(0 == nextNode)
					{
						pos = pos->getParentNode();

						if((startNode == pos) || (0 == pos))
						{
							nextNode = 0;
							break;
						}
					}
				}
			}

			pos = nextNode;
		} // if (fDone == false)
    } // while(0 != pos)
} // end buildKeysTable method

KeyTable::~KeyTable()
{
}

const NodeRefListBase*
KeyTable::getNodeSetByKey(
					  const XalanDOMString&		name,
					  const XalanDOMString&		ref) const
{
	// It makes things much easier if we always return
	// a list of nodes.  So this is just an empty one
	// to return when the ref is not found.
    const MutableNodeRefList*			nl = &s_dummyList;

	const KeysMapType::const_iterator	i = m_keys.find(name);

	if (i != m_keys.end())
	{
		const NodeListMapType&					theMap = (*i).second;

		const NodeListMapType::const_iterator	j = theMap.find(ref);

		if (j != theMap.end())
		{
			nl = &(*j).second;
		}
	}

	return nl;
}

<commit_msg>Removed invariant from within while loop.  Simplified comparison.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
// Class header file
#include "KeyTable.hpp"

#include <memory>

#include <XalanDOM/XalanElement.hpp>
#include <XalanDOM/XalanNamedNodeMap.hpp>
#include <XalanDOM/XalanNode.hpp>
#include <XalanDOM/XalanNodeList.hpp>

#include <XPath/XPath.hpp>
#include <XPath/XPathExecutionContext.hpp>

#include "KeyDeclaration.hpp"

const MutableNodeRefList	KeyTable::s_dummyList;

KeyTable::KeyTable(
			XalanNode*							doc,
			XalanNode*							startNode,
			const PrefixResolver&				resolver,
			const XalanDOMString&				name,
			const KeyDeclarationVectorType&		keyDeclarations,
			XPathExecutionContext&				executionContext) :
	m_docKey(doc),
	m_keys()
{
    XalanNode*	pos = startNode;

	bool		fDone = false;

	const KeyDeclarationVectorType::size_type	nDeclarations =
			keyDeclarations.size();

    // Do a non-recursive pre-walk over the tree.
    while(0 != pos && fDone == false)
    {
		// We're going to have to walk the attribute list
		// if it's an element, so get the attributes.
		const XalanNamedNodeMap*	attrs = 0;

		int							nNodes = 0;

		if(XalanNode::ELEMENT_NODE == pos->getNodeType())
		{
			attrs = static_cast<const XalanElement*>(pos)->getAttributes();

			nNodes = attrs->getLength();

			if(0 == nNodes)
			{
				attrs = 0;
			}
		}

		// Walk the primary node, and each of the attributes.
		// This loop is a little strange... it is meant to always
		// execute once, then execute for each of the attributes.
		XalanNode*	testNode = pos;

		for(int nodeIndex = -1; nodeIndex < nNodes && fDone == false;)
		{
			// Walk through each of the declarations made with xsl:key
			for(unsigned int i = 0; i < nDeclarations && fDone == false; i++)
			{
				const KeyDeclaration&	kd = keyDeclarations[i];

				if (equals(kd.getName(), name))
				{
					if (kd.getInConstruction() == true)
					{
						fDone = true;
					}
					else
					{
						kd.beginConstruction();

						// See if our node matches the given key declaration according to
						// the match attribute on xsl:key.
						const double	score = kd.getMatchPattern().getMatchScore(testNode,
																				   resolver,
																				   executionContext);

						if(score == XPath::s_MatchScoreNone)
						{
							kd.endConstruction();
						}
						else
						{
							// Query from the node, according the the select pattern in the
							// use attribute in xsl:key.
							const XObject* const	xuse =
								kd.getUse().execute(testNode, resolver, NodeRefList(), executionContext);

							const NodeRefListBase*	nl = 0;
							unsigned int nUseValues;
							XalanDOMString		exprResult;
							if(xuse->getType() != xuse->eTypeNodeSet)
							{
								nUseValues = 1;
								exprResult = xuse->str();
							}
							else
							{
								nl = &xuse->nodeset();
								// Use each node in the node list as a key value that we'll be
								// able to use to look up the given node.
								nUseValues = nl->getLength();
							}
							// Use each node in the node list as a key value that we'll be
							// able to use to look up the given node.
							for(unsigned int k = 0; k < nUseValues; k++)
							{

								// Use getExpr to get the string value of the given node. I hope
								// the string assumption is the right thing... I can't see how
								// it could work any other way.
								if(0 != nl)
								{
									XalanNode* const	useNode = nl->item(k);
									assert(useNode != 0);

									exprResult = executionContext.getNodeData(*useNode);
								}

								MutableNodeRefList&		keyNodes =
										m_keys[kd.getName()][exprResult];

								// See if the matched node is already in the
								// table set.  If it is there, we're done, otherwise
								// add it.
								bool foundit = false;

								const unsigned int	nKeyNodes = keyNodes.getLength(); //size();

								for(unsigned int j = 0; j < nKeyNodes; j++)
								{
									if(testNode == keyNodes.item(j))
									{
										foundit = true;
										break;
									}
								} // end for j

								if(foundit == false)
								{
									keyNodes.addNode(testNode);
								}
							} // end for(int k = 0; k < nUseValues; k++)

							kd.endConstruction();
						} // if(score != kd.getMatchPattern().s_MatchScoreNone)
					} // if (kd.getInConstruction() == true)
				} // if (equals(kd.getName(), name)
			} // end for(int i = 0; i < nDeclarations; i++)

			if (fDone == false)
			{
				nodeIndex++;

				if(0 != attrs)
				{
					testNode = attrs->item(nodeIndex);
				}
			}
		} // for(int nodeIndex = -1; nodeIndex < nNodes;)

		if (fDone == false)
		{
			// The rest of this is getting the next prewalk position in
			// the tree.

			XalanNode*	nextNode = pos->getFirstChild();

			while(0 == nextNode)
			{
				if(startNode == pos)
				{
					break;
				}
				else
				{
					nextNode = pos->getNextSibling();

					if(0 == nextNode)
					{
						pos = pos->getParentNode();

						if((startNode == pos) || (0 == pos))
						{
							nextNode = 0;
							break;
						}
					}
				}
			}

			pos = nextNode;
		} // if (fDone == false)
    } // while(0 != pos)
} // end buildKeysTable method

KeyTable::~KeyTable()
{
}

const NodeRefListBase*
KeyTable::getNodeSetByKey(
					  const XalanDOMString&		name,
					  const XalanDOMString&		ref) const
{
	// It makes things much easier if we always return
	// a list of nodes.  So this is just an empty one
	// to return when the ref is not found.
    const MutableNodeRefList*			nl = &s_dummyList;

	const KeysMapType::const_iterator	i = m_keys.find(name);

	if (i != m_keys.end())
	{
		const NodeListMapType&					theMap = (*i).second;

		const NodeListMapType::const_iterator	j = theMap.find(ref);

		if (j != theMap.end())
		{
			nl = &(*j).second;
		}
	}

	return nl;
}

<|endoftext|>


<commit_before>#ifndef MANIFOLDS_FUNCTION_INTERFACE_HH
#define MANIFOLDS_FUNCTION_INTERFACE_HH

#include <utility>

namespace manifolds {

  //Tag
  struct Function
  {
    static const bool stateless = false;
    //Means you can change the order of
    //Multiplications, ie A*B == B*A
    static const bool abelian_arithmetic = true;
  };

  //Tag
  struct MultiFunction : Function
  {
  };

  template <class T>
  struct is_stateless
  {
    static const bool value = T::stateless;
    typedef std::integral_constant<
      bool, value> type;
  };

  template <class T>
  struct has_abelian_arithmetic
  {
    static const bool value = T::abelian_arithmetic;
    typedef std::integral_constant<
      bool, value> type;
  };

  template <class...Args>
  struct and_;

  template <class Arg, class ... Args>
  struct and_<Arg,Args...> : std::conditional<
    Arg::value, and_<Args...>, std::false_type>::type{};

  template <class Arg>
  struct and_<Arg> : std::conditional<
    Arg::value, std::true_type, std::false_type>::type{};

  template <>
  struct and_<> : std::true_type{};

  template <int N>
  using int_ = std::integral_constant<int, N>;

  template <bool B>
  using bool_ = std::integral_constant<bool, B>;
}
#endif
<commit_msg>Added dimensionality metadata, removed MultiFunction class and moved template mate-functions to tmp_util.hh<commit_after>#ifndef MANIFOLDS_FUNCTION_INTERFACE_HH
#define MANIFOLDS_FUNCTION_INTERFACE_HH

#include <utility>
#include "tmp_utils.hh"

namespace manifolds {

  //Tag
  template <int INPUT_DIM, int OUTPUT_DIM>
  struct Function
  {
    static const bool stateless = false;
    static const int input_dim = INPUT_DIM;
    static const int output_dim = OUTPUT_DIM;
    //Means you can change the order of
    //Multiplications, ie A*B == B*A
    static const bool abelian_arithmetic = true;
  };

}
#endif
<|endoftext|>


<commit_before>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2014
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <boost/test/unit_test.hpp>

#include <stdio.h>
#include <time.h>

#include <round/common/Message.h>

using namespace std;
using namespace Round;

#define FRACTAL_MESSAGE_BASIC_TEST_COUNT 10

BOOST_AUTO_TEST_CASE(RoundMessageManagerTest) {
  MessageManager msgMgr;

  char key[32], value[32];
  for (int n = 0; n < FRACTAL_MESSAGE_BASIC_TEST_COUNT; n++) {
    snprintf(key, sizeof(key), "key%d", n);
    snprintf(value, sizeof(value), "%d", n);
    Message *msg = new Message();
    msg->set(key, value);
    BOOST_CHECK(msgMgr.pushMessage(msg));
  }

  for (int n = 0; n < FRACTAL_MESSAGE_BASIC_TEST_COUNT; n++) {
    snprintf(key, sizeof(key), "key%d", n);
    snprintf(value, sizeof(value), "%d", n);
    const Message *msg;
    BOOST_CHECK(msgMgr.waitMessage(&msg));
    string value;
    BOOST_CHECK(msg->get(key, &value));
    BOOST_CHECK_EQUAL(value.compare(value), 0);
    delete msg;
  }
}
<commit_msg>* Added RoundMessageManagerThreadTest.<commit_after>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2014
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <boost/test/unit_test.hpp>

#include <stdio.h>
#include <time.h>

#include <round/common/Message.h>
#include <round/common/Thread.h>

using namespace std;
using namespace Round;

#define ROUND_MSGMRG_TEST_COUNT 10

BOOST_AUTO_TEST_CASE(RoundMessageManagerTest) {
  MessageManager msgMgr;

  char key[32], value[32];
  for (int n = 0; n < ROUND_MSGMRG_TEST_COUNT; n++) {
    snprintf(key, sizeof(key), "key%d", n);
    snprintf(value, sizeof(value), "%d", n);
    Message *msg = new Message();
    msg->set(key, value);
    BOOST_CHECK(msgMgr.pushMessage(msg));
  }

  for (int n = 0; n < ROUND_MSGMRG_TEST_COUNT; n++) {
    snprintf(key, sizeof(key), "key%d", n);
    snprintf(value, sizeof(value), "%d", n);
    const Message *msg;
    BOOST_CHECK(msgMgr.waitMessage(&msg));
    string value;
    BOOST_CHECK(msg->get(key, &value));
    BOOST_CHECK_EQUAL(value.compare(value), 0);
    delete msg;
  }
}

class MsgPushThread : public Thread<MessageManager> {
public:

  MsgPushThread() {
  }

  void run() {
    MessageManager *msgMgr = getObject();
    char key[32], value[32];
    for (int n = 0; n < ROUND_MSGMRG_TEST_COUNT; n++) {
      snprintf(key, sizeof(key), "key%d", n);
      snprintf(value, sizeof(value), "%d", n);
      Message *msg = new Message();
      msg->set(key, value);
      sleep(1000);
      BOOST_CHECK(msgMgr->pushMessage(msg));
    }
  }
};

BOOST_AUTO_TEST_CASE(RoundMessageManagerThreadTest) {
  MessageManager msgMgr;

  MsgPushThread msgPushThread;
  msgPushThread.setObject(&msgMgr);
  BOOST_CHECK(msgPushThread.start());

  char key[32], value[32];
  for (int n = 0; n < ROUND_MSGMRG_TEST_COUNT; n++) {
    snprintf(key, sizeof(key), "key%d", n);
    snprintf(value, sizeof(value), "%d", n);
    const Message *msg;
    BOOST_CHECK(msgMgr.waitMessage(&msg));
    string value;
    BOOST_CHECK(msg->get(key, &value));
    BOOST_CHECK_EQUAL(value.compare(value), 0);
    delete msg;
  }

  BOOST_CHECK(msgPushThread.stop());
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// device_test.cpp
//
// Identification: tests/logging/device_test.cpp
//
// Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"

#include <iostream>
#include <fcntl.h>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstring>
#include <cassert>
#include <getopt.h>
#include <cstdint>
#include <string>
#include <vector>

#include "backend/common/timer.h"
#include "backend/common/types.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Device Test
//===--------------------------------------------------------------------===//

class DeviceTest : public PelotonTest {};

#define DATA_FILE_LEN 1024 * 1024 * UINT64_C(512)  // 512 MB
#define DATA_FILE_NAME "peloton.pmem"

TEST_F(DeviceTest, BenchmarkTest) {

  std::vector<std::string> data_file_dirs = {NVM_DIR, HDD_DIR};
  int data_fd;
  size_t data_file_len = DATA_FILE_LEN;
  oid_t num_trials = 3;
  std::size_t begin_chunk_size = 9, end_chunk_size = 21; // lg base 2

  // Go over all the dirs
  for(auto data_file_dir : data_file_dirs){

    // Create a data file
    std::string data_file_name = data_file_dir + DATA_FILE_NAME;
    std::cout << "Data File Name : " << data_file_name << "\n";

    if ((data_fd = open(data_file_name.c_str(), O_CREAT | O_RDWR | O_DIRECT | O_SYNC, 0666)) < 0) {
      perror(data_file_name.c_str());
      exit(EXIT_FAILURE);
    }

    // Allocate the data file
    if ((errno = posix_fallocate(data_fd, 0, data_file_len)) != 0) {
      perror("posix_fallocate");
      exit(EXIT_FAILURE);
    }

    // Go over all the chunk sizes
    for(oid_t chunk_size_itr = begin_chunk_size;
        chunk_size_itr <= end_chunk_size;
        chunk_size_itr++){

      // READS
      for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {

      }

      // WRITES
      for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {

      }

    }

    // Close the pmem file
    close(data_fd);
  }

}

}  // End test namespace
}  // End peloton namespace

<commit_msg>Fixed device test<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// device_test.cpp
//
// Identification: tests/logging/device_test.cpp
//
// Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"

#include <iostream>
#include <fcntl.h>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstring>
#include <cassert>
#include <getopt.h>
#include <cstdint>
#include <string>
#include <vector>

#include "backend/common/timer.h"
#include "backend/common/types.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Device Test
//===--------------------------------------------------------------------===//

class DeviceTest : public PelotonTest {};

#define DATA_FILE_LEN 1024 * 1024 * UINT64_C(512)  // 512 MB
#define DATA_FILE_NAME "peloton.pmem"

TEST_F(DeviceTest, BenchmarkTest) {

  std::vector<std::string> data_file_dirs = {NVM_DIR, HDD_DIR};
  int data_fd;
  size_t data_file_len = DATA_FILE_LEN;
  oid_t num_trials = 3;
  std::size_t begin_chunk_size = 9, end_chunk_size = 21; // lg base 2

  // Go over all the dirs
  for(auto data_file_dir : data_file_dirs){

    // Create a data file
    std::string data_file_name = data_file_dir + DATA_FILE_NAME;
    std::cout << "Data File Name : " << data_file_name << "\n";

    if ((data_fd = open(data_file_name.c_str(), O_CREAT | O_RDWR | O_DIRECT | O_SYNC, 0666)) < 0) {
      LOG_ERROR("%s: No such file or directory", data_file_name.c_str());
      return;
    }

    // Allocate the data file
    if ((errno = posix_fallocate(data_fd, 0, data_file_len)) != 0) {
      LOG_ERROR("%s: posix_fallocate", data_file_name.c_str());
      return;
    }

    // Go over all the chunk sizes
    for(oid_t chunk_size_itr = begin_chunk_size;
        chunk_size_itr <= end_chunk_size;
        chunk_size_itr++){

      // READS
      for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {

      }

      // WRITES
      for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {

      }

    }

    // Close the pmem file
    close(data_fd);
  }

}

}  // End test namespace
}  // End peloton namespace

<|endoftext|>


<commit_before>/*

MIT License

Copyright (c) 2016 Mark Allender

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.

*/

// Emulator.cpp : Defines the entry point for the console application.
//
#include <algorithm>
#include <string>
#include <stdlib.h>

#include "6502/cpu.h"
#include "6502/assemble.h"
#include "6502/video.h"
#include "6502/disk.h"
#include "6502/keyboard.h"
#include "6502/speaker.h"
#include "debugger/debugger.h"
#include "utils/path_utils.h"

#include "SDL.h"

#if defined(_MSC_VER)
#pragma warning(disable:4996)   // disable the deprecated warnings for fopen
#endif

INITIALIZE_EASYLOGGINGPP

#define MEMORY_SIZE (64 * 1024 * 1024)
int8_t memory_buffer[MEMORY_SIZE];

static void configure_logging()
{
	el::Configurations conf;

	conf.setToDefault();
	conf.set(el::Level::Global, el::ConfigurationType::Enabled, "true");
	conf.set(el::Level::Global, el::ConfigurationType::LogFileTruncate, "true");
	conf.set(el::Level::Global, el::ConfigurationType::ToStandardOutput, "false");
	conf.set(el::Level::Global, el::ConfigurationType::Format, "%msg");
	el::Loggers::reconfigureLogger("default", conf);

	// set some options on the logger
	el::Loggers::addFlag(el::LoggingFlag::ImmediateFlush);
	el::Loggers::addFlag(el::LoggingFlag::NewLineForContainer);
	el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput);
}

static char *get_cmdline_option(char **start, char **end, const std::string &short_option, const std::string &long_option = "")
{
	char **iter = std::find(start, end, short_option);
	if (iter == end) {
		iter = std::find(start, end, long_option);
	}
	if ((iter != end) && (iter++ != end) ) {
		return *iter;
	}

	return nullptr;
}

static bool cmdline_option_exists(char **start, char **end, const std::string &short_option, const std::string &long_option = "")
{
	char **iter = std::find(start, end, short_option);
	if (iter == end) {
		iter = std::find(start, end, long_option);
	}
	if (iter == end) {
		return false;
	}
	return true;
}

bool dissemble_6502(const char *filename)
{
	return true;
}

int main(int argc, char* argv[])
{
	// configure logging before anything else
	configure_logging();

	memory mem(MEMORY_SIZE, memory_buffer);
	cpu_6502 cpu(mem);
	cpu.init();

	debugger_init();
	disk_init(mem);

	//// get command line options
	//const char *assembly_file = nullptr;
	//const char *dissembly_file = nullptr;
	//assembly_file = get_cmdline_option(argv, argv+argc, "-a", "--assemble");

	//// let's test assembler
	//if (assembly_file != nullptr) {
	//	assemble_6502(assembly_file);
	//	return 0;
	//}

	//dissembly_file = get_cmdline_option(argv, argv+argc, "-d", "--disassemble");
	//if (dissembly_file != nullptr) {
	//	dissemble_6502(dissembly_file);
	//}

	//FILE *fp = fopen("test.bin", "rb");
	//fseek(fp, 0, SEEK_END);
	//uint32_t buffer_size = ftell(fp);
	//fseek(fp, 0, SEEK_SET);

	//// allocate the memory buffer
	//uint8_t *buffer = new uint8_t[buffer_size];
	//if (buffer == nullptr) {
	//	printf("Unable to allocate %d bytes for source code file buffer\n", buffer_size);
	//	fclose(fp);
	//	exit(-1);
	//}
	//fread(buffer, 1, buffer_size, fp);
	//fclose(fp);

	uint16_t prog_start = 0x600;
	uint16_t load_addr = 0x0;

	const char *prog_start_string = get_cmdline_option(argv, argv+argc, "-p", "--pc");
	if (prog_start_string != nullptr) {
		prog_start = (uint16_t)strtol(prog_start_string, nullptr, 16);
	}

	const char *load_addr_string = get_cmdline_option(argv, argv+argc, "-b", "--base");
	if (load_addr_string != nullptr) {
		load_addr = (uint16_t)strtol(load_addr_string, nullptr, 16);
	}

	const char *binary_file = nullptr;
	binary_file = get_cmdline_option(argv, argv+argc, "-b", "--binary");
	if (binary_file != nullptr) {
		FILE *fp = fopen(binary_file, "rb");
		if (fp == nullptr) {
			printf("Unable to open %s for reading: %d\n", binary_file, errno);
			exit(-1);
		}
		fseek(fp, 0, SEEK_END);
		uint32_t buffer_size = ftell(fp);
		fseek(fp, 0, SEEK_SET);

		// allocate the memory buffer
		uint8_t *buffer = new uint8_t[buffer_size];
		if (buffer == nullptr) {
			printf("Unable to allocate %d bytes for source code file buffer\n", buffer_size);
			fclose(fp);
			exit(-1);
		}
		fread(buffer, 1, buffer_size, fp);
		fclose(fp);
		mem.load_memory(buffer, buffer_size, load_addr);
		cpu.set_pc(prog_start);

	// load up the ROMs
	} else {
		cpu.set_pc(mem[0xfffc] | mem[0xfffd] << 8);

		// see if there is disk imace
		const char *disk_image_filename = get_cmdline_option(argv, argv+argc, "-d", "--disk");  // will always go to drive one for now
		if (disk_image_filename != nullptr) {
			disk_insert(disk_image_filename, 1);
		}
	}
#if !defined(USE_SDL)
	init_text_screen();
	clear_screen();
	set_raw(true);
#else
	video_init(mem);
	speaker_init(mem);
	keyboard_init();
#endif

	//cpu.load_program(0x600, buffer, buffer_size);
	bool quit = false;
	uint32_t total_cycles = 0;

	while (!quit) {
		SDL_Event evt;

		while (SDL_PollEvent(&evt)) {
			switch (evt.type) {
			case SDL_KEYDOWN:
			case SDL_KEYUP:
				keyboard_handle_event(evt);
				break;

			case SDL_WINDOWEVENT:
				if (evt.window.event == SDL_WINDOWEVENT_CLOSE) {
					quit = true;
				}
				break;

			}
		}

		// process debugger (before opcode processing so that we can break on
		// specific addresses properly
		debugger_process(cpu, mem);

		// process the next opcode
		uint32_t cycles = cpu.process_opcode();
		total_cycles += cycles;

		if (total_cycles > 17030) {
#if defined(USE_SDL)
			video_render_frame(mem);
#endif // if defined(USE_SDL)
			total_cycles -= 17030;
		}

	}

#if defined(USE_SDL)
	video_shutdown();
	keyboard_shutdown();
#endif

	return 0;
}

<commit_msg>Render at 30fps<commit_after>/*

MIT License

Copyright (c) 2016 Mark Allender

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.

*/

// Emulator.cpp : Defines the entry point for the console application.
//
#include <algorithm>
#include <string>
#include <stdlib.h>

#include "6502/cpu.h"
#include "6502/assemble.h"
#include "6502/video.h"
#include "6502/disk.h"
#include "6502/keyboard.h"
#include "6502/speaker.h"
#include "debugger/debugger.h"
#include "utils/path_utils.h"

#include "SDL.h"

#if defined(_MSC_VER)
#pragma warning(disable:4996)   // disable the deprecated warnings for fopen
#endif

INITIALIZE_EASYLOGGINGPP

#define MEMORY_SIZE (64 * 1024 * 1024)
int8_t memory_buffer[MEMORY_SIZE];

static const double Render_time = 33;   // roughly 30 fps

static void configure_logging()
{
	el::Configurations conf;

	conf.setToDefault();
	conf.set(el::Level::Global, el::ConfigurationType::Enabled, "true");
	conf.set(el::Level::Global, el::ConfigurationType::LogFileTruncate, "true");
	conf.set(el::Level::Global, el::ConfigurationType::ToStandardOutput, "false");
	conf.set(el::Level::Global, el::ConfigurationType::Format, "%msg");
	el::Loggers::reconfigureLogger("default", conf);

	// set some options on the logger
	el::Loggers::addFlag(el::LoggingFlag::ImmediateFlush);
	el::Loggers::addFlag(el::LoggingFlag::NewLineForContainer);
	el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput);
}

static char *get_cmdline_option(char **start, char **end, const std::string &short_option, const std::string &long_option = "")
{
	char **iter = std::find(start, end, short_option);
	if (iter == end) {
		iter = std::find(start, end, long_option);
	}
	if ((iter != end) && (iter++ != end) ) {
		return *iter;
	}

	return nullptr;
}

static bool cmdline_option_exists(char **start, char **end, const std::string &short_option, const std::string &long_option = "")
{
	char **iter = std::find(start, end, short_option);
	if (iter == end) {
		iter = std::find(start, end, long_option);
	}
	if (iter == end) {
		return false;
	}
	return true;
}

bool dissemble_6502(const char *filename)
{
	return true;
}

int main(int argc, char* argv[])
{
	// configure logging before anything else
	configure_logging();

	memory mem(MEMORY_SIZE, memory_buffer);
	cpu_6502 cpu(mem);
	cpu.init();

	debugger_init();
	disk_init(mem);

	//// get command line options
	//const char *assembly_file = nullptr;
	//const char *dissembly_file = nullptr;
	//assembly_file = get_cmdline_option(argv, argv+argc, "-a", "--assemble");

	//// let's test assembler
	//if (assembly_file != nullptr) {
	//	assemble_6502(assembly_file);
	//	return 0;
	//}

	//dissembly_file = get_cmdline_option(argv, argv+argc, "-d", "--disassemble");
	//if (dissembly_file != nullptr) {
	//	dissemble_6502(dissembly_file);
	//}

	//FILE *fp = fopen("test.bin", "rb");
	//fseek(fp, 0, SEEK_END);
	//uint32_t buffer_size = ftell(fp);
	//fseek(fp, 0, SEEK_SET);

	//// allocate the memory buffer
	//uint8_t *buffer = new uint8_t[buffer_size];
	//if (buffer == nullptr) {
	//	printf("Unable to allocate %d bytes for source code file buffer\n", buffer_size);
	//	fclose(fp);
	//	exit(-1);
	//}
	//fread(buffer, 1, buffer_size, fp);
	//fclose(fp);

	uint16_t prog_start = 0x600;
	uint16_t load_addr = 0x0;

	const char *prog_start_string = get_cmdline_option(argv, argv+argc, "-p", "--pc");
	if (prog_start_string != nullptr) {
		prog_start = (uint16_t)strtol(prog_start_string, nullptr, 16);
	}

	const char *load_addr_string = get_cmdline_option(argv, argv+argc, "-b", "--base");
	if (load_addr_string != nullptr) {
		load_addr = (uint16_t)strtol(load_addr_string, nullptr, 16);
	}

	const char *binary_file = nullptr;
	binary_file = get_cmdline_option(argv, argv+argc, "-b", "--binary");
	if (binary_file != nullptr) {
		FILE *fp = fopen(binary_file, "rb");
		if (fp == nullptr) {
			printf("Unable to open %s for reading: %d\n", binary_file, errno);
			exit(-1);
		}
		fseek(fp, 0, SEEK_END);
		uint32_t buffer_size = ftell(fp);
		fseek(fp, 0, SEEK_SET);

		// allocate the memory buffer
		uint8_t *buffer = new uint8_t[buffer_size];
		if (buffer == nullptr) {
			printf("Unable to allocate %d bytes for source code file buffer\n", buffer_size);
			fclose(fp);
			exit(-1);
		}
		fread(buffer, 1, buffer_size, fp);
		fclose(fp);
		mem.load_memory(buffer, buffer_size, load_addr);
		cpu.set_pc(prog_start);

	// load up the ROMs
	} else {
		cpu.set_pc(mem[0xfffc] | mem[0xfffd] << 8);

		// see if there is disk imace
		const char *disk_image_filename = get_cmdline_option(argv, argv+argc, "-d", "--disk");  // will always go to drive one for now
		if (disk_image_filename != nullptr) {
			disk_insert(disk_image_filename, 1);
		}
	}
	video_init(mem);
	speaker_init(mem);
	keyboard_init();

	bool quit = false;
	uint32_t total_cycles = 0;
	double last_time = SDL_GetTicks();
	double processed_time = 0;

	while (!quit) {
		SDL_Event evt;

		while (SDL_PollEvent(&evt)) {
			switch (evt.type) {
			case SDL_KEYDOWN:
			case SDL_KEYUP:
				keyboard_handle_event(evt);
				break;

			case SDL_WINDOWEVENT:
				if (evt.window.event == SDL_WINDOWEVENT_CLOSE) {
					quit = true;
				}
				break;
			}
		}

		// process debugger (before opcode processing so that we can break on
		// specific addresses properly
		debugger_process(cpu, mem);

		// process the next opcode
		uint32_t cycles = cpu.process_opcode();
		total_cycles += cycles;

		if (total_cycles > 17030) {
			//video_render_frame(mem);
			total_cycles -= 17030;
		}

		// determine whether to render or not.  Calculate diff
		// between last frame.
		double cur_time = SDL_GetTicks();
		double diff_time = cur_time - last_time;
		last_time = cur_time;

		bool should_render = false;
		processed_time += diff_time;
		while (processed_time > Render_time) {
			should_render = true;
			processed_time -= Render_time;
		}

		if (should_render == true) {
			video_render_frame(mem);
		}

	}

#if defined(USE_SDL)
	video_shutdown();
	keyboard_shutdown();
#endif

	return 0;
}

<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2022
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1232927 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/02/01 03:00:11<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2023
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2115
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1269123 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/05/16 03:00:13<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2116
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2648
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1551541 by johtaylo@johtaylo-jtincrementor2-increment on 2018/05/08 03:00:14<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2649
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2193
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1302360 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/08/12 03:00:08<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2194
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1994-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

// Methods for the class DAS - a class used to parse the dataset attribute
// structure.
//
// jhrg 7/25/94

#include "config.h"

static char rcsid[] not_used ={"$Id$"};

#include <stdio.h>
#ifdef WIN32
#include <io.h>
#else
#include <unistd.h>
#endif

#include <iostream>
#include <string>

#include "DAS.h"		// follows pragma since DAS.h is interface
#include "Error.h"
#include "InternalErr.h"
#include "parser.h"
#include "escaping.h"
#include "debug.h"

using std::cerr;
using std::endl;

// Glue routines declared in das.lex
extern void das_switch_to_buffer(void *new_buffer);
extern void das_delete_buffer(void * buffer);
extern void *das_buffer(FILE *fp);

extern void dasrestart(FILE *yyin);
extern int dasparse(void *arg); // defined in das.tab.c

AttrTable *
DAS::das_find(string name)
{
    return find_container(name); // Only containers at the top level.
}

/** Create a DAS from a single attribute table.

    \note In an older version of this class, <tt>dflt</tt> and <tt>sz</tt>
    initialized a hash table. That is no longer used and these
    params should no longer matter. Note that this constructor is
    effectively the empty constructor. 11/23/98 jhrg

    @param dflt A pointer to a valid attribute table.
    @param sz The number of entries in the table. This is unused. It
    was part of the ctor when DAS used the old GNU VHMap class. I
    switched from that to a SLList of struct toplevel_entry objects
    because the VHMap class had bugs I didn't want to fix. 11/23/98
    jhrg  */
DAS::DAS(AttrTable *, unsigned int)
{
}

/** Create a DAS object with one attribute table. Use <tt>append_attr()</tt>
    to add additional attributes.

    @see append_attr()
    @param attr The initial AttrTable.
    @param name The name of the DAS parent structure.
*/

DAS::DAS(AttrTable *attr, string name)
{
    append_container(attr, www2id(name));
}

// The class DASVHMap knows that it contains pointers to things and correctly
// makes copies of those things when its copy ctor is called, so DAS can do a
// simple member-wise copy. Similarly, we don't need to define our own op=.

// This deletes the pointers to AttrTables allocated during the parse (and at
// other times). jhrg 7/29/94

DAS::~DAS()
{
}

AttrTable::Attr_iter
DAS::var_begin()
{
    return AttrTable::attr_begin() ;
}

AttrTable::Attr_iter
DAS::var_end()
{
    return AttrTable::attr_end() ;
}

string
DAS::get_name(Attr_iter &i)
{
    return AttrTable::get_name(i);
}

/** @brief Returns the attribute table with the given name string. */
AttrTable *
DAS::get_table(Attr_iter &i)
{
    return AttrTable::get_attr_table(i);
}

/** @brief Returns the attribute table with the given name.

    This function is necessary because (char *) arguments will be
    converted to Pixs (and not strings). Without this member
    function get_table(name) needs a cast, and it seems tough to
    believe folks will always remember that.
*/
AttrTable *
DAS::get_table(const string &name)
{
    return AttrTable::get_attr_table(name);
}

#if character
AttrTable *
DAS::get_table(const char *name)
{
    return get_table((string)name);
}
#endif
//@}

/** @brief Adds an attribute table to the DAS.
    @name add_table()
*/
  //@{

/** @brief Adds an attribute table to the DAS. */
AttrTable *
DAS::add_table(const string &name, AttrTable *at)
{
    DBG(cerr << "Adding table: " << name << "(" << at << ")" << endl);
    return AttrTable::append_container(at, name);
}

#if character
/** @brief Adds an attribute table to the DAS. */
AttrTable *
DAS::add_table(const char *name, AttrTable *at)
{
    return add_table((string)name, at);
}
#endif
//@}

/** @brief Reads a DAS in from an external source.

    @name parse()
*/
    //@{

/** @brief Reads a DAS from the named file.

    Read attributes from a file. Returns false if unable to open
    the file, otherwise returns the result of the mfunc parse. */
void
DAS::parse(string fname)
{
    FILE *in = fopen(fname.c_str(), "r");

    if (!in) {
      throw Error(can_not_read_file, "Could not open: " + fname);
    }

    parse(in);

    int res = fclose(in);
    if( res ) {
	DBG(cerr << "DAS::parse - Failed to close file " << (void *)in << endl ;) ;
    }
}

/** @brief Read attributes from a file descriptor.

    If the file descriptor cannot be fdopen'd, return false, otherwise
    return the status of the mfunc parse.

    \note Added call to dup() within fdopen so that once the FILE * is
    closed the decriptor fd will not also be closed (instead the
    duplicate descriptor will be closed). Thus further information can
    be read from the descriptor fd.
*/
void
DAS::parse(int fd)
{
#ifdef WIN32
    FILE *in = fdopen(_dup(fd), "r");
#else
    FILE *in = fdopen(dup(fd), "r");
#endif

    if (!in) {
	throw InternalErr(__FILE__, __LINE__, "Could not access file.");
    }

    parse(in);

    int res = fclose(in);
    if( res ) {
	DBG(cerr << "DAS::parse(fd) - Failed to close " << (void *)in << endl ;) ;
    }
}

/** @brief Reads a DAS from an open file descriptor.

    Read attributes from in (which defaults to stdin). If
    dasrestart() fails, return false, otherwise return the status
    of dasparse().
*/
void
DAS::parse(FILE *in)
{
    if (!in) {
	throw InternalErr(__FILE__, __LINE__, "Null input stream.");
    }

    void *buffer = das_buffer(in);
    das_switch_to_buffer(buffer);

    parser_arg arg(this);

    bool status = dasparse((void *)&arg) == 0;

    das_delete_buffer(buffer);

    //  STATUS is the result of the parser function; if a recoverable error
    //  was found it will be true but arg.status() will be false.
    if (!status || !arg.status()) {// Check parse result
	if (arg.error())
	  throw *arg.error();
    }
}

//@}

/** Creates an ASCII representation of a DAS on the given output
    stream.

    When an identifier contains a character that contains
    characters that cannot be present in a URL (e.g., a space)
    AttrTable::print replaces those characters with WWW
    escape codes. 7/13/2001 jhrg

    @param out output FILE on which to print the DAS
    @param dereference If true, follow aliases. Default is false.
*/

void
DAS::print(FILE *out, bool dereference)
{
    fprintf( out, "Attributes {\n" ) ;

    AttrTable::print(out, "    ", dereference);

    fprintf( out, "}\n" ) ;
}
<commit_msg>DAS.cc: REmoved the 'char*' versions of the methods. These have not  been needed since we stopped using the GNU String class.<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1994-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

// Methods for the class DAS - a class used to parse the dataset attribute
// structure.
//
// jhrg 7/25/94

#include "config.h"

static char rcsid[] not_used ={"$Id$"};

#include <stdio.h>
#ifdef WIN32
#include <io.h>
#else
#include <unistd.h>
#endif

#include <iostream>
#include <string>

#include "DAS.h"		// follows pragma since DAS.h is interface
#include "Error.h"
#include "InternalErr.h"
#include "parser.h"
#include "escaping.h"
#include "debug.h"

using std::cerr;
using std::endl;

// Glue routines declared in das.lex
extern void das_switch_to_buffer(void *new_buffer);
extern void das_delete_buffer(void * buffer);
extern void *das_buffer(FILE *fp);

extern void dasrestart(FILE *yyin);
extern int dasparse(void *arg); // defined in das.tab.c

AttrTable *
DAS::das_find(string name)
{
    return find_container(name); // Only containers at the top level.
}

/** Create a DAS from a single attribute table.

    \note In an older version of this class, <tt>dflt</tt> and <tt>sz</tt>
    initialized a hash table. That is no longer used and these
    params should no longer matter. Note that this constructor is
    effectively the empty constructor. 11/23/98 jhrg

    @param dflt A pointer to a valid attribute table.
    @param sz The number of entries in the table. This is unused. It
    was part of the ctor when DAS used the old GNU VHMap class. I
    switched from that to a SLList of struct toplevel_entry objects
    because the VHMap class had bugs I didn't want to fix. 11/23/98
    jhrg  */
DAS::DAS(AttrTable *, unsigned int)
{
}

/** Create a DAS object with one attribute table. Use <tt>append_attr()</tt>
    to add additional attributes.

    @see append_attr()
    @param attr The initial AttrTable.
    @param name The name of the DAS parent structure.
*/

DAS::DAS(AttrTable *attr, string name)
{
    append_container(attr, www2id(name));
}

// The class DASVHMap knows that it contains pointers to things and correctly
// makes copies of those things when its copy ctor is called, so DAS can do a
// simple member-wise copy. Similarly, we don't need to define our own op=.

// This deletes the pointers to AttrTables allocated during the parse (and at
// other times). jhrg 7/29/94

DAS::~DAS()
{
}

AttrTable::Attr_iter
DAS::var_begin()
{
    return AttrTable::attr_begin() ;
}

AttrTable::Attr_iter
DAS::var_end()
{
    return AttrTable::attr_end() ;
}

string
DAS::get_name(Attr_iter &i)
{
    return AttrTable::get_name(i);
}

/** @brief Returns the attribute table. */
AttrTable *
DAS::get_table(Attr_iter &i)
{
    return AttrTable::get_attr_table(i);
}

/** @brief Returns the attribute table with the given name.
*/
AttrTable *
DAS::get_table(const string &name)
{
    return AttrTable::get_attr_table(name);
}

//@}

/** @brief Adds an attribute table to the DAS.
    @name add_table()
*/
  //@{

/** @brief Adds an attribute table to the DAS. */
AttrTable *
DAS::add_table(const string &name, AttrTable *at)
{
    DBG(cerr << "Adding table: " << name << "(" << at << ")" << endl);
    return AttrTable::append_container(at, name);
}

//@}

/** @brief Reads a DAS in from an external source.

    @name parse()
*/
    //@{

/** @brief Reads a DAS from the named file.

    Read attributes from a file. Returns false if unable to open
    the file, otherwise returns the result of the mfunc parse. */
void
DAS::parse(string fname)
{
    FILE *in = fopen(fname.c_str(), "r");

    if (!in) {
      throw Error(can_not_read_file, "Could not open: " + fname);
    }

    parse(in);

    int res = fclose(in);
    if( res ) {
	DBG(cerr << "DAS::parse - Failed to close file " << (void *)in << endl ;) ;
    }
}

/** @brief Read attributes from a file descriptor.

    If the file descriptor cannot be fdopen'd, return false, otherwise
    return the status of the mfunc parse.

    \note Added call to dup() within fdopen so that once the FILE * is
    closed the decriptor fd will not also be closed (instead the
    duplicate descriptor will be closed). Thus further information can
    be read from the descriptor fd.
*/
void
DAS::parse(int fd)
{
#ifdef WIN32
    FILE *in = fdopen(_dup(fd), "r");
#else
    FILE *in = fdopen(dup(fd), "r");
#endif

    if (!in) {
	throw InternalErr(__FILE__, __LINE__, "Could not access file.");
    }

    parse(in);

    int res = fclose(in);
    if( res ) {
	DBG(cerr << "DAS::parse(fd) - Failed to close " << (void *)in << endl ;) ;
    }
}

/** @brief Reads a DAS from an open file descriptor.

    Read attributes from in (which defaults to stdin). If
    dasrestart() fails, return false, otherwise return the status
    of dasparse().
*/
void
DAS::parse(FILE *in)
{
    if (!in) {
	throw InternalErr(__FILE__, __LINE__, "Null input stream.");
    }

    void *buffer = das_buffer(in);
    das_switch_to_buffer(buffer);

    parser_arg arg(this);

    bool status = dasparse((void *)&arg) == 0;

    das_delete_buffer(buffer);

    //  STATUS is the result of the parser function; if a recoverable error
    //  was found it will be true but arg.status() will be false.
    if (!status || !arg.status()) {// Check parse result
	if (arg.error())
	  throw *arg.error();
    }
}

//@}

/** Creates an ASCII representation of a DAS on the given output
    stream.

    When an identifier contains a character that contains
    characters that cannot be present in a URL (e.g., a space)
    AttrTable::print replaces those characters with WWW
    escape codes. 7/13/2001 jhrg

    @param out output FILE on which to print the DAS
    @param dereference If true, follow aliases. Default is false.
*/

void
DAS::print(FILE *out, bool dereference)
{
    fprintf( out, "Attributes {\n" ) ;

    AttrTable::print(out, "    ", dereference);

    fprintf( out, "}\n" ) ;
}
<|endoftext|>


<commit_before>#ifndef _UTILITIES_CPP
#define _UTILITIES_CPP

class utilities {
  public:
    //Default constructor
    utilities(void) {}

    //Function for getting specific bits in register
    //this function will only read bit range from msb to lsb, the returned value will be zero-padded
    uint8_t getRegValue(uint8_t deviceAddress, uint8_t reg, uint8_t msb = 7, uint8_t lsb = 0) {
      if((msb > 7) || (lsb > 7) || (lsb > msb)) {
        return 0xFF;
      }

      uint8_t rawValue = readRegister(deviceAddress, reg);
      uint8_t maskedValue = rawValue & ((0b11111111 << lsb) | (0b11111111 >> (7 - msb)));

      return(maskedValue);
    }

    //Function for setting specific bits in register
    //this function will only change bit range from msb to lsb
    uint8_t setRegValue(uint8_t deviceAddress, uint8_t reg, uint8_t value, uint8_t msb = 7, uint8_t lsb = 0) {
      if((msb > 7) || (lsb > 7) || (lsb > msb)) {
        return 0xFF;
      }

      uint8_t currentValue = readRegister(deviceAddress, reg);
      uint8_t newValue = currentValue & ((0b11111111 << (msb + 1)) | (0b11111111 >> (8 - lsb)));

      writeRegister(deviceAddress, reg, newValue | value);
    }

    //Function for reading from several consecutive registers
    uint8_t* readRegisterBurst(uint8_t deviceAddress, uint8_t reg, uint8_t len) {
      uint8_t* inBytes = new uint8_t[len];

      Wire.beginTransmission(deviceAddress);
      Wire.write(reg);
      Wire.endTransmission(false);

      Wire.requestFrom(deviceAddress, len);

      uint8_t i;
      while(Wire.available()) {
        inBytes[i++] = Wire.read();
      }

      return inBytes;
    }

    //Function for writing to several consecutive registers
    void writeRegisterBurst(uint8_t deviceAddress, uint8_t reg, uint8_t data, uint8_t len) {
      Wire.beginTransmission(deviceAddress);
      Wire.write(reg);
      Wire.write(data, len);
      Wire.endTransmission(true);
    }

    //Function for reading from a single register
    //this is a low-level function, use getRegValue instead!
    uint8_t readRegister(uint8_t deviceAddress, uint8_t reg) {
      uint8_t inByte;

      Wire.beginTransmission(deviceAddress);
      Wire.write(reg);
      Wire.endTransmission(false);

      Wire.requestFrom(deviceAddress, (uint8_t)1);
      inByte = Wire.read();

      return(inByte);
    }

    //Function for writing to a single register
    //this is a low-level function, use setRegValue instead!
    void writeRegister(uint8_t deviceAddress, uint8_t reg, uint8_t data) {
      Wire.beginTransmission(deviceAddress);
      Wire.write(reg);
      Wire.write(data);
      Wire.endTransmission(true);
    }
};

#endif
<commit_msg>Removed unused writeRegisterBurst function<commit_after>#ifndef _UTILITIES_CPP
#define _UTILITIES_CPP

class utilities {
  public:
    //Default constructor
    utilities(void) {}

    //Function for getting specific bits in register
    //this function will only read bit range from msb to lsb, the returned value will be zero-padded
    uint8_t getRegValue(uint8_t deviceAddress, uint8_t reg, uint8_t msb = 7, uint8_t lsb = 0) {
      if((msb > 7) || (lsb > 7) || (lsb > msb)) {
        return 0xFF;
      }

      uint8_t rawValue = readRegister(deviceAddress, reg);
      uint8_t maskedValue = rawValue & ((0b11111111 << lsb) | (0b11111111 >> (7 - msb)));

      return(maskedValue);
    }

    //Function for setting specific bits in register
    //this function will only change bit range from msb to lsb
    uint8_t setRegValue(uint8_t deviceAddress, uint8_t reg, uint8_t value, uint8_t msb = 7, uint8_t lsb = 0) {
      if((msb > 7) || (lsb > 7) || (lsb > msb)) {
        return 0xFF;
      }

      uint8_t currentValue = readRegister(deviceAddress, reg);
      uint8_t newValue = currentValue & ((0b11111111 << (msb + 1)) | (0b11111111 >> (8 - lsb)));

      writeRegister(deviceAddress, reg, newValue | value);
    }

    //Function for reading from several consecutive registers
    uint8_t* readRegisterBurst(uint8_t deviceAddress, uint8_t reg, uint8_t len) {
      uint8_t* inBytes = new uint8_t[len];

      Wire.beginTransmission(deviceAddress);
      Wire.write(reg);
      Wire.endTransmission(false);

      Wire.requestFrom(deviceAddress, len);

      uint8_t i;
      while(Wire.available()) {
        inBytes[i++] = Wire.read();
      }

      return inBytes;
    }

    //Function for reading from a single register
    //this is a low-level function, use getRegValue instead!
    uint8_t readRegister(uint8_t deviceAddress, uint8_t reg) {
      uint8_t inByte;

      Wire.beginTransmission(deviceAddress);
      Wire.write(reg);
      Wire.endTransmission(false);

      Wire.requestFrom(deviceAddress, (uint8_t)1);
      inByte = Wire.read();

      return(inByte);
    }

    //Function for writing to a single register
    //this is a low-level function, use setRegValue instead!
    void writeRegister(uint8_t deviceAddress, uint8_t reg, uint8_t data) {
      Wire.beginTransmission(deviceAddress);
      Wire.write(reg);
      Wire.write(data);
      Wire.endTransmission(true);
    }
};

#endif
<|endoftext|>


<commit_before><commit_msg>Fix Editor::HasSelectedObject<commit_after><|endoftext|>


<commit_before>/*
The MIT License

Copyright (c) 2012 by Jorrit Tyberghein

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 <crystalspace.h>
#include "apparesed.h"
#include "ui/uimanager.h"
#include "config.h"

#include <wx/wx.h>

//---------------------------------------------------------------------------

AresConfig::AresConfig (AppAresEditWX* app) :
  scfImplementationType (this), app (app)
{
}

bool AresConfig::ParsePlugins (iDocumentNode* pluginsNode)
{
  csRef<iDocumentNodeIterator> it = pluginsNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "plugin")
    {
      PluginConfig mc;
      mc.plugin = child->GetAttributeValue ("plugin");
      mc.tooltip = child->GetAttributeValue ("tooltip");
      mc.mainMode = child->GetAttributeValueAsBool ("main");
      csRef<iDocumentNodeIterator> childit = child->GetNodes ();
      while (childit->HasNext ())
      {
	csRef<iDocumentNode> resourceChild = childit->Next ();
	if (resourceChild->GetType () != CS_NODE_ELEMENT) continue;
        csString resourceValue = resourceChild->GetValue ();
        if (resourceValue == "resource")
	{
	  csString file = resourceChild->GetAttributeValue ("file");
	  mc.resources.Push (file);
	}
        else
        {
          return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", resourceValue.GetData ());
        }
      }
      plugins.Push (mc);
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

bool AresConfig::ParseWizard (iDocumentNode* node, Wizard* wizard)
{
  wizard->name = node->GetAttributeValue ("name");
  wizard->description = node->GetAttributeValue ("description");
  wizard->node = node;

  csRef<iDocumentNodeIterator> it = node->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "ask")
    {
      WizardParameter par;
      par.name = child->GetAttributeValue ("name");
      par.type = child->GetAttributeValue ("type");
      par.defaultValue = child->GetAttributeValue ("default");
      par.description = child->GetAttributeValue ("description");
      wizard->parameters.Push (par);
    }
  }

  return true;
}

bool AresConfig::ParseWizards (iDocumentNode* wizardsNode)
{
  csRef<iDocumentNodeIterator> it = wizardsNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "template")
    {
      Wizard* wizard = new Wizard ();;
      if (!ParseWizard (child, wizard))
	return false;
      templateWizards.Push (wizard);
    }
    else if (value == "quest")
    {
      Wizard* wizard = new Wizard ();;
      if (!ParseWizard (child, wizard))
	return false;
      questWizards.Push (wizard);
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

Wizard* AresConfig::FindTemplateWizard (const char* name) const
{
  for (size_t i = 0 ; i < templateWizards.GetSize () ; i++)
    if (templateWizards.Get (i)->name == name)
      return templateWizards.Get (i);
  return 0;
}

Wizard* AresConfig::FindQuestWizard (const char* name) const
{
  for (size_t i = 0 ; i < questWizards.GetSize () ; i++)
    if (questWizards.Get (i)->name == name)
      return questWizards.Get (i);
  return 0;
}

bool AresConfig::ParseKnownMessages (iDocumentNode* knownmessagesNode)
{
  csRef<iDocumentNodeIterator> it = knownmessagesNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "message")
    {
      KnownMessage msg;
      msg.name = child->GetAttributeValue ("name");
      msg.description = child->GetAttributeValue ("description");
      csRef<iDocumentNodeIterator> parit = child->GetNodes ();
      while (parit->HasNext ())
      {
        csRef<iDocumentNode> parNode = parit->Next ();
        if (parNode->GetType () != CS_NODE_ELEMENT) continue;
        csString parValue = parNode->GetValue ();
	if (parValue == "par")
	{
	  KnownParameter par;
	  par.name = parNode->GetAttributeValue ("name");
	  par.value = parNode->GetAttributeValue ("value");
	  csString typeS = parNode->GetAttributeValue ("type");
	  celDataType type;
	  if (typeS == "string") type = CEL_DATA_STRING;
	  else if (typeS == "long") type = CEL_DATA_LONG;
	  else if (typeS == "bool") type = CEL_DATA_BOOL;
	  else if (typeS == "float") type = CEL_DATA_FLOAT;
	  else if (typeS == "vector2") type = CEL_DATA_VECTOR2;
	  else if (typeS == "vector3") type = CEL_DATA_VECTOR3;
	  else if (typeS == "vector4") type = CEL_DATA_VECTOR4;
	  else if (typeS == "color") type = CEL_DATA_COLOR;
	  else if (typeS == "color4") type = CEL_DATA_COLOR4;
	  else type = CEL_DATA_NONE;
	  par.type = type;
	  msg.parameters.Push (par);
	}
	else
	{
          return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", parValue.GetData ());
	}
      }
      messages.Push (msg);
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

csRef<iDocument> AresConfig::ReadConfigDocument ()
{
  if (doc) return doc;
  csRef<iVFS> vfs = csQueryRegistry<iVFS> (app->GetObjectRegistry ());
  csRef<iDocumentSystem> docsys;
  docsys = csQueryRegistry<iDocumentSystem> (app->GetObjectRegistry ());
  if (!docsys)
    docsys.AttachNew (new csTinyDocumentSystem ());

  doc = docsys->CreateDocument ();
  csRef<iDataBuffer> buf = vfs->ReadFile ("/appdata/aresedconfig.xml");
  if (!buf)
  {
    app->ReportError ("Could not open config file '/appdata/aresedconfig.xml'!");
    return 0;
  }
  const char* error = doc->Parse (buf->GetData ());
  if (error)
  {
    app->ReportError ("Error parsing 'aresedconfig.xml': %s!", error);
    return 0;
  }
  return doc;
}

bool AresConfig::ReadConfig ()
{
  ReadConfigDocument ();
  if (!doc) return false;
  csRef<iDocumentNode> root = doc->GetRoot ();
  csRef<iDocumentNode> configNode = root->GetNode ("config");
  if (!configNode)
    return app->ReportError ("Error 'aresedconfig.xml' is missing a 'config' node!");
  csRef<iDocumentNode> knownmessagesNode = configNode->GetNode ("knownmessages");
  if (knownmessagesNode)
  {
    if (!ParseKnownMessages (knownmessagesNode))
      return false;
  }
  csRef<iDocumentNode> pluginsNode = configNode->GetNode ("plugins");
  if (pluginsNode)
  {
    if (!ParsePlugins (pluginsNode))
      return false;
  }
  csRef<iDocumentNode> wizardsNode = configNode->GetNode ("wizards");
  if (wizardsNode)
  {
    if (!ParseWizards (wizardsNode))
      return false;
  }
  return true;
}

const KnownMessage* AresConfig::GetKnownMessage (const char* name) const
{
  for (size_t i = 0 ; i < messages.GetSize () ; i++)
  {
    if (messages.Get (i).name == name)
      return &messages.Get (i);
  }
  return 0;
}

static int StringToId (csString s)
{
  s.Downcase ();
  if (s == "new") return wxID_NEW;
  if (s == "copy") return wxID_COPY;
  if (s == "quit") return wxID_EXIT;
  if (s == "open") return wxID_OPEN;
  if (s == "save") return wxID_SAVE;
  if (s == "saveas") return wxID_SAVEAS;
  if (s == "paste") return wxID_PASTE;
  if (s == "delete") return wxID_DELETE;
  if (s == "preview") return wxID_PREVIEW;
  if (s == "find") return wxID_FIND;
  if (s == "help") return wxID_HELP_INDEX;
  if (s == "about") return wxID_ABOUT;
  return wxID_ANY;
}

bool AresConfig::ParseMenuItems (wxMenu* menu, iDocumentNode* itemsNode)
{
  csRef<iDocumentNodeIterator> it = itemsNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "item")
    {
      csString name = child->GetAttributeValue ("name");
      csString idString = child->GetAttributeValue ("id");
      csString target = child->GetAttributeValue ("target");
      csString command = child->GetAttributeValue ("command");
      csString help = child->GetAttributeValue ("help");
      csString args = child->GetAttributeValue ("args");
      int id = StringToId (idString);
      if (id == wxID_ANY)
	id = app->GetUIManager ()->AllocContextMenuID ();
      app->AllocateMenuCommand (id, name, target, command, args, help);
      app->AppendMenuItem (menu, id, name, help);
    }
    else if (value == "sep")
    {
      menu->AppendSeparator ();
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

bool AresConfig::ParseMenus (wxMenuBar* menuBar, iDocumentNode* menusNode)
{
  csRef<iDocumentNodeIterator> it = menusNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "menu")
    {
      csString name = child->GetAttributeValue ("name");
      wxMenu* menu = new wxMenu ();
      if (!ParseMenuItems (menu, child))
      {
	delete menu;
	return false;
      }
      menuBar->Append (menu, wxString::FromUTF8 (name));
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

wxMenuBar* AresConfig::BuildMenuBar ()
{
  ReadConfigDocument ();
  if (!doc) return 0;
  csRef<iDocumentNode> root = doc->GetRoot ();
  csRef<iDocumentNode> configNode = root->GetNode ("config");
  if (!configNode)
  {
    app->ReportError ("Error 'aresedconfig.xml' is missing a 'config' node!");
    return 0;
  }
  csRef<iDocumentNode> menusNode = configNode->GetNode ("menus");
  if (menusNode)
  {
    wxMenuBar* menuBar = new wxMenuBar ();
    if (!ParseMenus (menuBar, menusNode))
    {
      delete menuBar;
      return 0;
    }
    return menuBar;
  }
  return 0;
}

bool AresConfig::ParseToolbarItems (wxToolBar* toolbar, iDocumentNode* sectionNode)
{
  csRef<iDataBuffer> buf = app->GetVFS ()->GetRealPath ("/ares/data/icons/toolbar/32x32");
  csString path (buf->GetData ());
  path += CS_PATH_SEPARATOR;
  wxImage image (32, 32);

  csRef<iDocumentNodeIterator> it = sectionNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "item")
    {
      csString name = child->GetAttributeValue ("name");
      csString idString = child->GetAttributeValue ("id");
      csString target = child->GetAttributeValue ("target");
      csString imageFile = child->GetAttributeValue ("image");
      csString command = child->GetAttributeValue ("command");
      csString help = child->GetAttributeValue ("help");
      csString args = child->GetAttributeValue ("args");
      bool toggle = child->GetAttributeValueAsBool ("toggle");
      int id = StringToId (idString);
      if (id == wxID_ANY)
	id = app->GetUIManager ()->AllocContextMenuID ();
      app->AllocateMenuCommand (id, name, target, command, args, help);
      image.LoadFile (wxString::FromUTF8 (path + imageFile));
      toolbar->AddTool (id, wxString::FromUTF8 (name), wxBitmap (image), wxString::FromUTF8 (help),
	  toggle ? wxITEM_CHECK : wxITEM_NORMAL);
    }
    else if (value == "sep")
    {
      toolbar->AddSeparator ();
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

bool AresConfig::ParseToolbar (wxToolBar* toolbar, iDocumentNode* toolbarNode)
{
  bool first = true;
  csRef<iDocumentNodeIterator> it = toolbarNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "section")
    {
      csString name = child->GetAttributeValue ("name");
      if (first)
      {
	toolbar->AddSeparator ();
	first = false;
      }
      if (!ParseToolbarItems (toolbar, child))
      {
	return false;
      }
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

bool AresConfig::BuildToolBar (wxToolBar* toolbar)
{
  ReadConfigDocument ();
  if (!doc) return 0;
  csRef<iDocumentNode> root = doc->GetRoot ();
  csRef<iDocumentNode> configNode = root->GetNode ("config");
  if (!configNode)
  {
    app->ReportError ("Error 'aresedconfig.xml' is missing a 'config' node!");
    return false;
  }
  csRef<iDocumentNode> toolbarNode = configNode->GetNode ("toolbar");
  if (toolbarNode)
  {
    if (!ParseToolbar (toolbar, toolbarNode))
      return false;
    return true;
  }
  return true;
}

<commit_msg>aresed: Support a 'key' attribute in menu items, use it to compose entry text<commit_after>/*
The MIT License

Copyright (c) 2012 by Jorrit Tyberghein

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 <crystalspace.h>
#include "apparesed.h"
#include "ui/uimanager.h"
#include "config.h"

#include <wx/wx.h>

//---------------------------------------------------------------------------

AresConfig::AresConfig (AppAresEditWX* app) :
  scfImplementationType (this), app (app)
{
}

bool AresConfig::ParsePlugins (iDocumentNode* pluginsNode)
{
  csRef<iDocumentNodeIterator> it = pluginsNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "plugin")
    {
      PluginConfig mc;
      mc.plugin = child->GetAttributeValue ("plugin");
      mc.tooltip = child->GetAttributeValue ("tooltip");
      mc.mainMode = child->GetAttributeValueAsBool ("main");
      csRef<iDocumentNodeIterator> childit = child->GetNodes ();
      while (childit->HasNext ())
      {
	csRef<iDocumentNode> resourceChild = childit->Next ();
	if (resourceChild->GetType () != CS_NODE_ELEMENT) continue;
        csString resourceValue = resourceChild->GetValue ();
        if (resourceValue == "resource")
	{
	  csString file = resourceChild->GetAttributeValue ("file");
	  mc.resources.Push (file);
	}
        else
        {
          return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", resourceValue.GetData ());
        }
      }
      plugins.Push (mc);
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

bool AresConfig::ParseWizard (iDocumentNode* node, Wizard* wizard)
{
  wizard->name = node->GetAttributeValue ("name");
  wizard->description = node->GetAttributeValue ("description");
  wizard->node = node;

  csRef<iDocumentNodeIterator> it = node->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "ask")
    {
      WizardParameter par;
      par.name = child->GetAttributeValue ("name");
      par.type = child->GetAttributeValue ("type");
      par.defaultValue = child->GetAttributeValue ("default");
      par.description = child->GetAttributeValue ("description");
      wizard->parameters.Push (par);
    }
  }

  return true;
}

bool AresConfig::ParseWizards (iDocumentNode* wizardsNode)
{
  csRef<iDocumentNodeIterator> it = wizardsNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "template")
    {
      Wizard* wizard = new Wizard ();;
      if (!ParseWizard (child, wizard))
	return false;
      templateWizards.Push (wizard);
    }
    else if (value == "quest")
    {
      Wizard* wizard = new Wizard ();;
      if (!ParseWizard (child, wizard))
	return false;
      questWizards.Push (wizard);
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

Wizard* AresConfig::FindTemplateWizard (const char* name) const
{
  for (size_t i = 0 ; i < templateWizards.GetSize () ; i++)
    if (templateWizards.Get (i)->name == name)
      return templateWizards.Get (i);
  return 0;
}

Wizard* AresConfig::FindQuestWizard (const char* name) const
{
  for (size_t i = 0 ; i < questWizards.GetSize () ; i++)
    if (questWizards.Get (i)->name == name)
      return questWizards.Get (i);
  return 0;
}

bool AresConfig::ParseKnownMessages (iDocumentNode* knownmessagesNode)
{
  csRef<iDocumentNodeIterator> it = knownmessagesNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "message")
    {
      KnownMessage msg;
      msg.name = child->GetAttributeValue ("name");
      msg.description = child->GetAttributeValue ("description");
      csRef<iDocumentNodeIterator> parit = child->GetNodes ();
      while (parit->HasNext ())
      {
        csRef<iDocumentNode> parNode = parit->Next ();
        if (parNode->GetType () != CS_NODE_ELEMENT) continue;
        csString parValue = parNode->GetValue ();
	if (parValue == "par")
	{
	  KnownParameter par;
	  par.name = parNode->GetAttributeValue ("name");
	  par.value = parNode->GetAttributeValue ("value");
	  csString typeS = parNode->GetAttributeValue ("type");
	  celDataType type;
	  if (typeS == "string") type = CEL_DATA_STRING;
	  else if (typeS == "long") type = CEL_DATA_LONG;
	  else if (typeS == "bool") type = CEL_DATA_BOOL;
	  else if (typeS == "float") type = CEL_DATA_FLOAT;
	  else if (typeS == "vector2") type = CEL_DATA_VECTOR2;
	  else if (typeS == "vector3") type = CEL_DATA_VECTOR3;
	  else if (typeS == "vector4") type = CEL_DATA_VECTOR4;
	  else if (typeS == "color") type = CEL_DATA_COLOR;
	  else if (typeS == "color4") type = CEL_DATA_COLOR4;
	  else type = CEL_DATA_NONE;
	  par.type = type;
	  msg.parameters.Push (par);
	}
	else
	{
          return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", parValue.GetData ());
	}
      }
      messages.Push (msg);
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

csRef<iDocument> AresConfig::ReadConfigDocument ()
{
  if (doc) return doc;
  csRef<iVFS> vfs = csQueryRegistry<iVFS> (app->GetObjectRegistry ());
  csRef<iDocumentSystem> docsys;
  docsys = csQueryRegistry<iDocumentSystem> (app->GetObjectRegistry ());
  if (!docsys)
    docsys.AttachNew (new csTinyDocumentSystem ());

  doc = docsys->CreateDocument ();
  csRef<iDataBuffer> buf = vfs->ReadFile ("/appdata/aresedconfig.xml");
  if (!buf)
  {
    app->ReportError ("Could not open config file '/appdata/aresedconfig.xml'!");
    return 0;
  }
  const char* error = doc->Parse (buf->GetData ());
  if (error)
  {
    app->ReportError ("Error parsing 'aresedconfig.xml': %s!", error);
    return 0;
  }
  return doc;
}

bool AresConfig::ReadConfig ()
{
  ReadConfigDocument ();
  if (!doc) return false;
  csRef<iDocumentNode> root = doc->GetRoot ();
  csRef<iDocumentNode> configNode = root->GetNode ("config");
  if (!configNode)
    return app->ReportError ("Error 'aresedconfig.xml' is missing a 'config' node!");
  csRef<iDocumentNode> knownmessagesNode = configNode->GetNode ("knownmessages");
  if (knownmessagesNode)
  {
    if (!ParseKnownMessages (knownmessagesNode))
      return false;
  }
  csRef<iDocumentNode> pluginsNode = configNode->GetNode ("plugins");
  if (pluginsNode)
  {
    if (!ParsePlugins (pluginsNode))
      return false;
  }
  csRef<iDocumentNode> wizardsNode = configNode->GetNode ("wizards");
  if (wizardsNode)
  {
    if (!ParseWizards (wizardsNode))
      return false;
  }
  return true;
}

const KnownMessage* AresConfig::GetKnownMessage (const char* name) const
{
  for (size_t i = 0 ; i < messages.GetSize () ; i++)
  {
    if (messages.Get (i).name == name)
      return &messages.Get (i);
  }
  return 0;
}

static int StringToId (csString s)
{
  s.Downcase ();
  if (s == "new") return wxID_NEW;
  if (s == "copy") return wxID_COPY;
  if (s == "quit") return wxID_EXIT;
  if (s == "open") return wxID_OPEN;
  if (s == "save") return wxID_SAVE;
  if (s == "saveas") return wxID_SAVEAS;
  if (s == "paste") return wxID_PASTE;
  if (s == "delete") return wxID_DELETE;
  if (s == "preview") return wxID_PREVIEW;
  if (s == "find") return wxID_FIND;
  if (s == "help") return wxID_HELP_INDEX;
  if (s == "about") return wxID_ABOUT;
  return wxID_ANY;
}

bool AresConfig::ParseMenuItems (wxMenu* menu, iDocumentNode* itemsNode)
{
  csRef<iDocumentNodeIterator> it = itemsNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "item")
    {
      csString name = child->GetAttributeValue ("name");
      csString hotkey = child->GetAttributeValue ("key");
      csString idString = child->GetAttributeValue ("id");
      csString target = child->GetAttributeValue ("target");
      csString command = child->GetAttributeValue ("command");
      csString help = child->GetAttributeValue ("help");
      csString args = child->GetAttributeValue ("args");
      int id = StringToId (idString);
      if (id == wxID_ANY)
	id = app->GetUIManager ()->AllocContextMenuID ();
      if (!hotkey.IsEmpty())
      {
        name.SetCapacity (name.Length() + 1 + hotkey.Length());
        name.Append ("\t");
        name.Append (hotkey);
      }
      app->AllocateMenuCommand (id, name, target, command, args, help);
      app->AppendMenuItem (menu, id, name, help);
    }
    else if (value == "sep")
    {
      menu->AppendSeparator ();
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

bool AresConfig::ParseMenus (wxMenuBar* menuBar, iDocumentNode* menusNode)
{
  csRef<iDocumentNodeIterator> it = menusNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "menu")
    {
      csString name = child->GetAttributeValue ("name");
      wxMenu* menu = new wxMenu ();
      if (!ParseMenuItems (menu, child))
      {
	delete menu;
	return false;
      }
      menuBar->Append (menu, wxString::FromUTF8 (name));
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

wxMenuBar* AresConfig::BuildMenuBar ()
{
  ReadConfigDocument ();
  if (!doc) return 0;
  csRef<iDocumentNode> root = doc->GetRoot ();
  csRef<iDocumentNode> configNode = root->GetNode ("config");
  if (!configNode)
  {
    app->ReportError ("Error 'aresedconfig.xml' is missing a 'config' node!");
    return 0;
  }
  csRef<iDocumentNode> menusNode = configNode->GetNode ("menus");
  if (menusNode)
  {
    wxMenuBar* menuBar = new wxMenuBar ();
    if (!ParseMenus (menuBar, menusNode))
    {
      delete menuBar;
      return 0;
    }
    return menuBar;
  }
  return 0;
}

bool AresConfig::ParseToolbarItems (wxToolBar* toolbar, iDocumentNode* sectionNode)
{
  csRef<iDataBuffer> buf = app->GetVFS ()->GetRealPath ("/ares/data/icons/toolbar/32x32");
  csString path (buf->GetData ());
  path += CS_PATH_SEPARATOR;
  wxImage image (32, 32);

  csRef<iDocumentNodeIterator> it = sectionNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "item")
    {
      csString name = child->GetAttributeValue ("name");
      csString idString = child->GetAttributeValue ("id");
      csString target = child->GetAttributeValue ("target");
      csString imageFile = child->GetAttributeValue ("image");
      csString command = child->GetAttributeValue ("command");
      csString help = child->GetAttributeValue ("help");
      csString args = child->GetAttributeValue ("args");
      bool toggle = child->GetAttributeValueAsBool ("toggle");
      int id = StringToId (idString);
      if (id == wxID_ANY)
	id = app->GetUIManager ()->AllocContextMenuID ();
      app->AllocateMenuCommand (id, name, target, command, args, help);
      image.LoadFile (wxString::FromUTF8 (path + imageFile));
      toolbar->AddTool (id, wxString::FromUTF8 (name), wxBitmap (image), wxString::FromUTF8 (help),
	  toggle ? wxITEM_CHECK : wxITEM_NORMAL);
    }
    else if (value == "sep")
    {
      toolbar->AddSeparator ();
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

bool AresConfig::ParseToolbar (wxToolBar* toolbar, iDocumentNode* toolbarNode)
{
  bool first = true;
  csRef<iDocumentNodeIterator> it = toolbarNode->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    csString value = child->GetValue ();
    if (value == "section")
    {
      csString name = child->GetAttributeValue ("name");
      if (first)
      {
	toolbar->AddSeparator ();
	first = false;
      }
      if (!ParseToolbarItems (toolbar, child))
      {
	return false;
      }
    }
    else
    {
      return app->ReportError ("Error parsing 'aresedconfig.xml', unknown element '%s'!", value.GetData ());
    }
  }
  return true;
}

bool AresConfig::BuildToolBar (wxToolBar* toolbar)
{
  ReadConfigDocument ();
  if (!doc) return 0;
  csRef<iDocumentNode> root = doc->GetRoot ();
  csRef<iDocumentNode> configNode = root->GetNode ("config");
  if (!configNode)
  {
    app->ReportError ("Error 'aresedconfig.xml' is missing a 'config' node!");
    return false;
  }
  csRef<iDocumentNode> toolbarNode = configNode->GetNode ("toolbar");
  if (toolbarNode)
  {
    if (!ParseToolbar (toolbar, toolbarNode))
      return false;
    return true;
  }
  return true;
}

<|endoftext|>