<commit_before>//
//  Parser.cpp
//
//
//  Created by James Spann on 4/23/14.
//
//

#include <fstream>

#include "Parser.h"
#include "vm.h"
#include "Variable.h"

using namespace std;

int addToInt(int origi, int val);

string operand;
bool isVariable;
int currentInt;
Variable parameters[5];
SymbolTable rect;

void parse(char* fname){
    rect.initializeTable();
    char ch;
    int numParams;
    int paramPlace = 0;
    currentInt = 0;

    fstream fin(fname, fstream::in);

    while (fin >> noskipws >> ch) {
        if (isalpha(ch)) {
            operand += ch;
        }else if (isdigit(ch)) {
            int lucy = ch - '0';
            currentInt = addToInt(currentInt,lucy);

        }else{
            switch (ch) {
                case ' ':

                    break;
                case ',':

                    Variable t;
                    t.value = currentInt;

                    t.datatype = (isVariable) ? (1) : (0);

                    parameters[paramPlace] = t;
                    paramPlace++;

                    currentInt = 0;
                    isVariable = false;
                    break;
                case '$':
                    isVariable = true;
                    break;
                case '\n':

                    if (operand.compare("defi") == 0) {
                        rect.addToTable('i',currentInt);
                    }else if (operand.compare("add") == 0) {
                        int jt = 0;

                        if (paramPlace != 1 && paramPlace != 0) {

                            for (int d = 1; d < paramPlace; d++) {
                                if (parameters[d].datatype == 1){
                                    jt +=rect.returnValues(parameters[d].value);
                                }else{
                                    jt +=parameters[d].value;
                                }

                            }

                        }

                        rect.setValue(parameters[0],jt);
                    }else if (operand.compare("call") == 0) {

                    }else if (operand.compare("call") == 0) {

                    }else{
                        cout << "Unknown operand: " << operand << endl;
                        cout << "Halting" << endl;
                        exit(1);
                    }

                    currentInt=0;
                    paramPlace = 0;
                    operand = "";
                    break;
                default:
                    cout <<"Parse error";
            }
        }

    }
    rect.printTable();

}

int addToInt(int origi, int val){
    return (origi * 10)+val ;
}
<commit_msg>added new operand data<commit_after>//
//  Parser.cpp
//
//
//  Created by James Spann on 4/23/14.
//
//

#include <fstream>

#include "Parser.h"
#include "vm.h"
#include "Variable.h"

using namespace std;

int addToInt(int origi, int val);

string operand;
bool isVariable;
int currentInt;
Variable parameters[5];
SymbolTable rect;

void parse(char* fname){
    rect.initializeTable();
    char ch;
    int numParams;
    int paramPlace = 0;
    currentInt = 0;

    fstream fin(fname, fstream::in);

    while (fin >> noskipws >> ch) {
        if (isalpha(ch)) {
            operand += ch;
        }else if (isdigit(ch)) {
            int lucy = ch - '0';
            currentInt = addToInt(currentInt,lucy);

        }else{
            switch (ch) {
                case ' ':

                    break;
                case ',':

                    Variable t;
                    t.value = currentInt;

                    t.datatype = (isVariable) ? (1) : (0);

                    parameters[paramPlace] = t;
                    paramPlace++;

                    currentInt = 0;
                    isVariable = false;
                    break;
                case '$':
                    isVariable = true;
                    break;
                case '\n':

                    if (operand.compare("defi") == 0) {
                        rect.addToTable('i',currentInt);
                    }else if (operand.compare("add") == 0) {
                        int jt = 0;

                        if (paramPlace != 1 && paramPlace != 0) {

                            for (int d = 1; d < paramPlace; d++) {
                                if (parameters[d].datatype == 1){
                                    jt +=rect.returnValues(parameters[d].value);
                                }else{
                                    jt +=parameters[d].value;
                                }

                            }

                        }

                        rect.setValue(parameters[0],jt);
                    }else if (operand.compare("sub") == 0) {
                    }else if (operand.compare("call") == 0) {
                    }else{
                        cout << "Unknown operand: " << operand << endl;
                        cout << "Halting" << endl;
                        exit(1);
                    }

                    currentInt=0;
                    paramPlace = 0;
                    operand = "";
                    break;
                default:
                    cout <<"Parse error";
            }
        }

    }
    rect.printTable();

}

int addToInt(int origi, int val){
    return (origi * 10)+val ;
}
<|endoftext|>


<commit_before>// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the
// University of Virginia, University of Heidelberg, and University
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include "copasi/copasi.h"

#include "CommentHandler.h"
#include "CXMLParser.h"
#include "copasi/utilities/CCopasiMessage.h"

/**
 * Replace Comment with the name type of the handler and implement the
 * three methods below.
 */
CommentHandler::CommentHandler(CXMLParser & parser, CXMLParserData & data):
  CXMLHandler(parser, data, CXMLHandler::Comment)
{
  init();
}

// virtual
CommentHandler::~CommentHandler()
{}

// virtual
void CommentHandler::start(const XML_Char * pszName,
                           const XML_Char ** papszAttrs)
{
  processStart(pszName, papszAttrs);
  mLevel++;
}

// virtual
void CommentHandler::end(const XML_Char * pszName)
{
  mLevel--;

  if (processEnd(pszName))
    {
      mpParser->popElementHandler();
      mpParser->onEndElement(pszName);
    }
}

// virtual
CXMLHandler * CommentHandler::processStart(const XML_Char * pszName,
    const XML_Char ** papszAttrs)
{
  const XML_Char ** ppAttrs;

  if (mLevel == 0)
    {
      mXhtml.str("");
      mpParser->enableCharacterDataHandler();
      mpParser->enableSkippedEntityHandler();
      mpParser->setCharacterEncoding(CCopasiXMLInterface::character);
      mElementEmpty.push(false);
    }
  else
    {
      if (mElementEmpty.top() == true)
        {
          mXhtml << ">";
          mElementEmpty.top() = false;
        }

      mXhtml << CCopasiXMLInterface::encode(mpParser->getCharacterData());
      mXhtml << "<" << pszName;

      for (ppAttrs = papszAttrs; *ppAttrs && **ppAttrs; ppAttrs += 2)
        mXhtml << " " << *ppAttrs << "=\""
               << CCopasiXMLInterface::encode(*(ppAttrs + 1), CCopasiXMLInterface::attribute) << "\"";

      mElementEmpty.push(true);
      mpParser->enableCharacterDataHandler();
    }

  return NULL;
}

// virtual
bool CommentHandler::processEnd(const XML_Char * pszName)
{
  bool finished = false;
  std::string Xhtml;

  if (mLevel == 0)
    {
      finished = true;

      mXhtml << mpParser->getCharacterData();
      mpData->CharacterData = mXhtml.str();

      // remove leading whitepsaces
      std::string::size_type pos = mpData->CharacterData.find_first_not_of("\x0a\x0d\t ");

      if (pos != 0) mpData->CharacterData.erase(0, pos);

      // remove trailing whitepsace
      pos = mpData->CharacterData.find_last_not_of("\x0a\x0d\t ");

      if (pos < mpData->CharacterData.length())
        mpData->CharacterData = mpData->CharacterData.substr(0, pos + 1);

      mpParser->enableSkippedEntityHandler(false);
      mpParser->setCharacterEncoding(CCopasiXMLInterface::none);
      mElementEmpty.pop();
      assert(mElementEmpty.empty());
    }
  else
    {
      Xhtml = mpParser->getCharacterData();

      // Check whether and how we need to close the attribute
      if (mElementEmpty.top() == true)
        {
          if (Xhtml != "")
            {
              mElementEmpty.top() = false;
              mXhtml << ">";
            }
          else
            mXhtml << " />";
        }

      mXhtml << Xhtml;

      if (mElementEmpty.top() == false)
        mXhtml << "</" << pszName << ">";

      mElementEmpty.pop();
      mElementEmpty.top() = false;

      mpParser->enableCharacterDataHandler();
    }

  return finished;
}

// virtual
CXMLHandler::sProcessLogic * CommentHandler::getProcessLogic() const
{
  static sProcessLogic Elements[] =
  {
    {"BEFORE", BEFORE, BEFORE, {Comment, HANDLER_COUNT}},
    {"Comment", Comment, Comment, {AFTER, HANDLER_COUNT}},
    {"AFTER", AFTER, AFTER, {HANDLER_COUNT}}
  };

  return Elements;
}
<commit_msg>Bug 2952: XHTML data must not be encoded on read.<commit_after>// Copyright (C) 2019 - 2021 by Pedro Mendes, Rector and Visitors of the
// University of Virginia, University of Heidelberg, and University
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include "copasi/copasi.h"

#include "CommentHandler.h"
#include "CXMLParser.h"
#include "copasi/utilities/CCopasiMessage.h"

/**
 * Replace Comment with the name type of the handler and implement the
 * three methods below.
 */
CommentHandler::CommentHandler(CXMLParser & parser, CXMLParserData & data):
  CXMLHandler(parser, data, CXMLHandler::Comment)
{
  init();
}

// virtual
CommentHandler::~CommentHandler()
{}

// virtual
void CommentHandler::start(const XML_Char * pszName,
                           const XML_Char ** papszAttrs)
{
  processStart(pszName, papszAttrs);
  mLevel++;
}

// virtual
void CommentHandler::end(const XML_Char * pszName)
{
  mLevel--;

  if (processEnd(pszName))
    {
      mpParser->popElementHandler();
      mpParser->onEndElement(pszName);
    }
}

// virtual
CXMLHandler * CommentHandler::processStart(const XML_Char * pszName,
    const XML_Char ** papszAttrs)
{
  const XML_Char ** ppAttrs;

  if (mLevel == 0)
    {
      mXhtml.str("");
      mpParser->enableCharacterDataHandler();
      mpParser->enableSkippedEntityHandler();
      mpParser->setCharacterEncoding(CCopasiXMLInterface::character);
      mElementEmpty.push(false);
    }
  else
    {
      if (mElementEmpty.top() == true)
        {
          mXhtml << ">";
          mElementEmpty.top() = false;
        }

      mXhtml << CCopasiXMLInterface::encode(mpParser->getCharacterData(), CCopasiXMLInterface::none);
      mXhtml << "<" << pszName;

      for (ppAttrs = papszAttrs; *ppAttrs && **ppAttrs; ppAttrs += 2)
        mXhtml << " " << *ppAttrs << "=\""
               << CCopasiXMLInterface::encode(*(ppAttrs + 1), CCopasiXMLInterface::attribute) << "\"";

      mElementEmpty.push(true);
      mpParser->enableCharacterDataHandler();
    }

  return NULL;
}

// virtual
bool CommentHandler::processEnd(const XML_Char * pszName)
{
  bool finished = false;
  std::string Xhtml;

  if (mLevel == 0)
    {
      finished = true;

      mXhtml << mpParser->getCharacterData();
      mpData->CharacterData = mXhtml.str();

      // remove leading whitepsaces
      std::string::size_type pos = mpData->CharacterData.find_first_not_of("\x0a\x0d\t ");

      if (pos != 0) mpData->CharacterData.erase(0, pos);

      // remove trailing whitepsace
      pos = mpData->CharacterData.find_last_not_of("\x0a\x0d\t ");

      if (pos < mpData->CharacterData.length())
        mpData->CharacterData = mpData->CharacterData.substr(0, pos + 1);

      mpParser->enableSkippedEntityHandler(false);
      mpParser->setCharacterEncoding(CCopasiXMLInterface::none);
      mElementEmpty.pop();
      assert(mElementEmpty.empty());
    }
  else
    {
      Xhtml = mpParser->getCharacterData();

      // Check whether and how we need to close the attribute
      if (mElementEmpty.top() == true)
        {
          if (Xhtml != "")
            {
              mElementEmpty.top() = false;
              mXhtml << ">";
            }
          else
            mXhtml << " />";
        }

      mXhtml << Xhtml;

      if (mElementEmpty.top() == false)
        mXhtml << "</" << pszName << ">";

      mElementEmpty.pop();
      mElementEmpty.top() = false;

      mpParser->enableCharacterDataHandler();
    }

  return finished;
}

// virtual
CXMLHandler::sProcessLogic * CommentHandler::getProcessLogic() const
{
  static sProcessLogic Elements[] =
  {
    {"BEFORE", BEFORE, BEFORE, {Comment, HANDLER_COUNT}},
    {"Comment", Comment, Comment, {AFTER, HANDLER_COUNT}},
    {"AFTER", AFTER, AFTER, {HANDLER_COUNT}}
  };

  return Elements;
}
<|endoftext|>


<commit_before>#include "Compression.h"
#include "../Utilities/Bytes.h"

void Compression::decodeRLE(const uint8_t *src, int stopCount,
	std::vector<uint8_t> &out)
{
	// Adapted from WinArena.
	int i = 0;
	int o = 0;

	while (o < stopCount)
	{
		const uint8_t sample = src[i];
		src++;

		// Is the selected byte part of a compressed packet?
		if ((sample & 0x80) != 0)
		{
			const uint8_t value = src[i];
			src++;

			const uint32_t count = static_cast<uint32_t>(sample) - 0x7F;

			for (uint32_t j = 0; j < count; j++)
			{
				out.at(o) = value;
				o++;
			}
		}
		else
		{
			const uint32_t count = static_cast<uint32_t>(sample) + 1;

			for (uint32_t j = 0; j < count; j++)
			{
				out.at(o) = src[i];
				o++;
				i++;
			}
		}
	}
}

void Compression::decodeRLEWords(const uint8_t *src, int stopCount,
	std::vector<uint8_t> &out)
{
	int i = 0;
	int o = 0;

	while (o < (stopCount - 1))
	{
		const int16_t sample = Bytes::getLE16(src + i);
		i += 2;

		// If "sample" is positive, then "sample" literal words follow. Otherwise,
		// repeat the next word "sample" times.
		if (sample > 0)
		{
			for (int16_t j = 0; j < sample; j++)
			{
				const uint16_t value = Bytes::getLE16(src + i);
				i += 2;

				out.at(o) = value & 0xFF00;
				out.at(o + 1) = value & 0x00FF;
				o += 2;
			}
		}
		else
		{
			const uint16_t value = Bytes::getLE16(src + i);
			i += 2;

			const uint16_t count = -sample;

			for (uint16_t j = 0; j < count; j++)
			{
				out.at(o) = value & 0xFF00;
				out.at(o + 1) = value & 0x00FF;
				o += 2;
			}
		}
	}
}
<commit_msg>Fixed Compression::decodeRLEWords().<commit_after>#include "Compression.h"
#include "../Utilities/Bytes.h"

void Compression::decodeRLE(const uint8_t *src, int stopCount,
	std::vector<uint8_t> &out)
{
	// Adapted from WinArena.
	int i = 0;
	int o = 0;

	while (o < stopCount)
	{
		const uint8_t sample = src[i];
		src++;

		// Is the selected byte part of a compressed packet?
		if ((sample & 0x80) != 0)
		{
			const uint8_t value = src[i];
			src++;

			const uint32_t count = static_cast<uint32_t>(sample) - 0x7F;

			for (uint32_t j = 0; j < count; j++)
			{
				out.at(o) = value;
				o++;
			}
		}
		else
		{
			const uint32_t count = static_cast<uint32_t>(sample) + 1;

			for (uint32_t j = 0; j < count; j++)
			{
				out.at(o) = src[i];
				o++;
				i++;
			}
		}
	}
}

void Compression::decodeRLEWords(const uint8_t *src, int stopCount,
	std::vector<uint8_t> &out)
{
	int i = 0;
	int o = 0;

	while (o < stopCount)
	{
		const int16_t sample = Bytes::getLE16(src + i);
		i += 2;

		// If "sample" is positive, then "sample" literal words follow. Otherwise,
		// repeat the next word "sample" times.
		if (sample > 0)
		{
			for (int16_t j = 0; j < sample; j++)
			{
				const uint16_t value = Bytes::getLE16(src + i);
				i += 2;

				out.at(o * 2) = value & 0x00FF;
				out.at((o * 2) + 1) = (value & 0xFF00) >> 8;
				o++;
			}
		}
		else
		{
			const uint16_t value = Bytes::getLE16(src + i);
			i += 2;

			const uint16_t count = -sample;

			for (uint16_t j = 0; j < count; j++)
			{
				out.at(o * 2) = value & 0x00FF;
				out.at((o * 2) + 1) = (value & 0xFF00) >> 8;
				o++;
			}
		}
	}
}
<|endoftext|>


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

#include "chrome/browser/geolocation/access_token_store.h"

#include "chrome/browser/chrome_thread.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {
// The token store factory implementation expects to be used from any well-known
// chrome thread other than UI. We could use any arbitrary thread; IO is
// a good choice as this is the expected usage.
const ChromeThread::ID kExpectedClientThreadId = ChromeThread::IO;
const char* kRefServerUrl1 = "https://test.domain.example/foo?id=bar.bar";
const char* kRefServerUrl2 = "http://another.domain.example/foo?id=bar.bar#2";
}  // namespace

class GeolocationAccessTokenStoreTest
    : public InProcessBrowserTest,
      public AccessTokenStoreFactory::Delegate,
      public base::SupportsWeakPtr<GeolocationAccessTokenStoreTest> {
 protected:
  GeolocationAccessTokenStoreTest()
      : token_to_expect_(NULL), token_to_set_(NULL) {}

  void StartThreadAndWaitForResults(
      const char* ref_url, const string16* token_to_expect,
      const string16* token_to_set);

  // AccessTokenStoreFactory::Delegate
  virtual void OnAccessTokenStoresCreated(
        const AccessTokenStoreFactory::TokenStoreSet& access_token_store);
  GURL ref_url_;
  const string16* token_to_expect_;
  const string16* token_to_set_;
};

namespace {
// A WeakPtr may only be used on the thread in which it is created, hence we
// defer the call to delegate->AsWeakPtr() into this function rather than pass
// WeakPtr& in.
void StartTestFromClientThread(
    GeolocationAccessTokenStoreTest* delegate,
    const GURL& ref_url) {
  ASSERT_TRUE(ChromeThread::CurrentlyOn(kExpectedClientThreadId));

  scoped_refptr<AccessTokenStoreFactory> store =
      NewChromePrefsAccessTokenStoreFactory();
  store->CreateAccessTokenStores(delegate->AsWeakPtr(), ref_url);
}
}  // namespace

void GeolocationAccessTokenStoreTest::StartThreadAndWaitForResults(
    const char* ref_url, const string16* token_to_expect,
    const string16* token_to_set) {
  ref_url_ = GURL(ref_url);
  token_to_expect_ = token_to_expect;
  token_to_set_ = token_to_set;

  ChromeThread::PostTask(
      kExpectedClientThreadId, FROM_HERE, NewRunnableFunction(
          &StartTestFromClientThread, this, ref_url_));
  ui_test_utils::RunMessageLoop();
}

void GeolocationAccessTokenStoreTest::OnAccessTokenStoresCreated(
      const AccessTokenStoreFactory::TokenStoreSet& access_token_store) {
  ASSERT_TRUE(ChromeThread::CurrentlyOn(kExpectedClientThreadId))
      << "Callback from token factory should be from the same thread as the "
         "CreateAccessTokenStores request was made on";
  EXPECT_TRUE(token_to_set_ || token_to_expect_) << "No work to do?";
  DCHECK_GE(access_token_store.size(), size_t(1));

  AccessTokenStoreFactory::TokenStoreSet::const_iterator item =
      access_token_store.find(ref_url_);
  ASSERT_TRUE(item != access_token_store.end());
  scoped_refptr<AccessTokenStore> store = item->second;
  ASSERT_TRUE(NULL != store);
  string16 token;
  bool read_ok = store->GetAccessToken(&token);
  if (!token_to_expect_) {
    EXPECT_FALSE(read_ok);
    EXPECT_TRUE(token.empty());
  } else {
    ASSERT_TRUE(read_ok);
    EXPECT_EQ(*token_to_expect_, token);
  }

  if (token_to_set_) {
    store->SetAccessToken(*token_to_set_);
  }
  ChromeThread::PostTask(
      ChromeThread::UI, FROM_HERE, new MessageLoop::QuitTask);
}

#if defined(OS_LINUX)
// TODO(joth): http://crbug.com/36068 crashes on Linux.
#define MAYBE_SetAcrossInstances DISABLED_SetAcrossInstances
#else
#define MAYBE_SetAcrossInstances SetAcrossInstances
#endif

IN_PROC_BROWSER_TEST_F(GeolocationAccessTokenStoreTest, MAYBE_SetAcrossInstances) {
  const string16 ref_token1 = ASCIIToUTF16("jksdfo90,'s#\"#1*(");
  const string16 ref_token2 = ASCIIToUTF16("\1\2\3\4\5\6\7\10\11\12=023");
  ASSERT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));

  StartThreadAndWaitForResults(kRefServerUrl1, NULL, &ref_token1);
  // Check it was set, and change to new value.
  StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, &ref_token2);
  // And change back.
  StartThreadAndWaitForResults(kRefServerUrl1, &ref_token2, &ref_token1);
  StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, NULL);

  // Set a second server URL
  StartThreadAndWaitForResults(kRefServerUrl2, NULL, &ref_token2);
  StartThreadAndWaitForResults(kRefServerUrl2, &ref_token2, NULL);
  StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, NULL);
}
<commit_msg>Test SetAcrossInstances crashed on Mac also. Disabling.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/geolocation/access_token_store.h"

#include "chrome/browser/chrome_thread.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {
// The token store factory implementation expects to be used from any well-known
// chrome thread other than UI. We could use any arbitrary thread; IO is
// a good choice as this is the expected usage.
const ChromeThread::ID kExpectedClientThreadId = ChromeThread::IO;
const char* kRefServerUrl1 = "https://test.domain.example/foo?id=bar.bar";
const char* kRefServerUrl2 = "http://another.domain.example/foo?id=bar.bar#2";
}  // namespace

class GeolocationAccessTokenStoreTest
    : public InProcessBrowserTest,
      public AccessTokenStoreFactory::Delegate,
      public base::SupportsWeakPtr<GeolocationAccessTokenStoreTest> {
 protected:
  GeolocationAccessTokenStoreTest()
      : token_to_expect_(NULL), token_to_set_(NULL) {}

  void StartThreadAndWaitForResults(
      const char* ref_url, const string16* token_to_expect,
      const string16* token_to_set);

  // AccessTokenStoreFactory::Delegate
  virtual void OnAccessTokenStoresCreated(
        const AccessTokenStoreFactory::TokenStoreSet& access_token_store);
  GURL ref_url_;
  const string16* token_to_expect_;
  const string16* token_to_set_;
};

namespace {
// A WeakPtr may only be used on the thread in which it is created, hence we
// defer the call to delegate->AsWeakPtr() into this function rather than pass
// WeakPtr& in.
void StartTestFromClientThread(
    GeolocationAccessTokenStoreTest* delegate,
    const GURL& ref_url) {
  ASSERT_TRUE(ChromeThread::CurrentlyOn(kExpectedClientThreadId));

  scoped_refptr<AccessTokenStoreFactory> store =
      NewChromePrefsAccessTokenStoreFactory();
  store->CreateAccessTokenStores(delegate->AsWeakPtr(), ref_url);
}
}  // namespace

void GeolocationAccessTokenStoreTest::StartThreadAndWaitForResults(
    const char* ref_url, const string16* token_to_expect,
    const string16* token_to_set) {
  ref_url_ = GURL(ref_url);
  token_to_expect_ = token_to_expect;
  token_to_set_ = token_to_set;

  ChromeThread::PostTask(
      kExpectedClientThreadId, FROM_HERE, NewRunnableFunction(
          &StartTestFromClientThread, this, ref_url_));
  ui_test_utils::RunMessageLoop();
}

void GeolocationAccessTokenStoreTest::OnAccessTokenStoresCreated(
      const AccessTokenStoreFactory::TokenStoreSet& access_token_store) {
  ASSERT_TRUE(ChromeThread::CurrentlyOn(kExpectedClientThreadId))
      << "Callback from token factory should be from the same thread as the "
         "CreateAccessTokenStores request was made on";
  EXPECT_TRUE(token_to_set_ || token_to_expect_) << "No work to do?";
  DCHECK_GE(access_token_store.size(), size_t(1));

  AccessTokenStoreFactory::TokenStoreSet::const_iterator item =
      access_token_store.find(ref_url_);
  ASSERT_TRUE(item != access_token_store.end());
  scoped_refptr<AccessTokenStore> store = item->second;
  ASSERT_TRUE(NULL != store);
  string16 token;
  bool read_ok = store->GetAccessToken(&token);
  if (!token_to_expect_) {
    EXPECT_FALSE(read_ok);
    EXPECT_TRUE(token.empty());
  } else {
    ASSERT_TRUE(read_ok);
    EXPECT_EQ(*token_to_expect_, token);
  }

  if (token_to_set_) {
    store->SetAccessToken(*token_to_set_);
  }
  ChromeThread::PostTask(
      ChromeThread::UI, FROM_HERE, new MessageLoop::QuitTask);
}

#if !defined(OS_WIN)
// TODO(joth): Crashes on Linux and Mac. See http://crbug.com/36068.
#define MAYBE_SetAcrossInstances DISABLED_SetAcrossInstances
#else
#define MAYBE_SetAcrossInstances SetAcrossInstances
#endif

IN_PROC_BROWSER_TEST_F(GeolocationAccessTokenStoreTest, MAYBE_SetAcrossInstances) {
  const string16 ref_token1 = ASCIIToUTF16("jksdfo90,'s#\"#1*(");
  const string16 ref_token2 = ASCIIToUTF16("\1\2\3\4\5\6\7\10\11\12=023");
  ASSERT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));

  StartThreadAndWaitForResults(kRefServerUrl1, NULL, &ref_token1);
  // Check it was set, and change to new value.
  StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, &ref_token2);
  // And change back.
  StartThreadAndWaitForResults(kRefServerUrl1, &ref_token2, &ref_token1);
  StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, NULL);

  // Set a second server URL
  StartThreadAndWaitForResults(kRefServerUrl2, NULL, &ref_token2);
  StartThreadAndWaitForResults(kRefServerUrl2, &ref_token2, NULL);
  StartThreadAndWaitForResults(kRefServerUrl1, &ref_token1, NULL);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Mar 10, 2014
 */

#include <string>
#include <iosfwd>
#include <stdexcept>
#include <tuple>

#include "tpunit++.hpp"
#include "fakeit.hpp"
#include "mockutils/Formatter.hpp"

using namespace fakeit;

struct DefaultEventFormatting: tpunit::TestFixture {
	DefaultEventFormatting() :
			tpunit::TestFixture(
			//
			TEST(DefaultEventFormatting::format_UnmockedMethodCallEvent),
			TEST(DefaultEventFormatting::format_UnmatchedMethodCallEvent),
			TEST(DefaultEventFormatting::format_AnyArguments),
			TEST(DefaultEventFormatting::format_Exactly_Once),
			TEST(DefaultEventFormatting::format_Atleast_Once),
			TEST(DefaultEventFormatting::format_NoMoreInvocations_VerificationFailure),
			TEST(DefaultEventFormatting::format_UserDefinedMatcher_in_expected_pattern),
			TEST(DefaultEventFormatting::format_actual_arguments)
			) //
	{
	}

	template <typename T> std::string to_string(T& val){
		std::stringstream stream;
		stream << val;
		return stream.str();
	}

	struct SomeInterface {
		virtual int func(int) = 0;
		virtual void proc(int) = 0;

		virtual int all_types(
			char,
			bool,
			int,
			unsigned int,
			long,
			unsigned long,
			long long,
			unsigned long long,
			double,
			long double) = 0;
	};

	void format_UnmockedMethodCallEvent() {
		Mock<SomeInterface> mock;
		SomeInterface &i = mock.get();
		try {
			i.func(1);
			FAIL();
		}
		catch (UnexpectedMethodCallException& e)
		{
			std::string expectedMsg{"Unexpected method invocation: unknown()\n"};
			expectedMsg +=	"  An unmocked method was invoked. All used virtual methods must be stubbed!";
			std::string actual{to_string(e)};
			ASSERT_EQUAL(expectedMsg, actual);
		}
	}

	void format_UnmatchedMethodCallEvent() {
		Mock<SomeInterface> mock;
		Fake(Method(mock,func).Using(3));
		SomeInterface &i = mock.get();
		try {
			i.func(1);
			FAIL();
		}
		catch (UnexpectedMethodCallException& e)
		{
			std::string expectedMsg{"Unexpected method invocation: mock.func(1)\n  Could not find any recorded behavior to support this method call."};
			std::string actual{to_string(e)};
			ASSERT_EQUAL(expectedMsg, actual);
		}
	}

	void format_AnyArguments() {
		Mock<SomeInterface> mock;
		try {
			fakeit::Verify(Method(mock, func)).setFileInfo("test file",1,"test method").Exactly(Once);
		}
		catch (SequenceVerificationException& e) {
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.func( any arguments )\n";
			expectedMsg += "Expected matches: exactly 1\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";
			std::string actualMsg{to_string(e)};
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_Exactly_Once() {
		Mock<SomeInterface> mock;
		try {
			fakeit::Verify(Method(mock, func)).setFileInfo("test file",1,"test method").Exactly(Once);
		}
		catch (SequenceVerificationException& e) {
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.func( any arguments )\n";
			expectedMsg += "Expected matches: exactly 1\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";

			std::string actualMsg{to_string(e)};
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_Atleast_Once() {
		Mock<SomeInterface> mock;
		try {
			fakeit::Verify(Method(mock, func)).setFileInfo("test file",1,"test method").AtLeast(Once);
		}
		catch (SequenceVerificationException& e) {
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.func( any arguments )\n";
			expectedMsg += "Expected matches: at least 1\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";

			std::string actualMsg {to_string(e)};
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_NoMoreInvocations_VerificationFailure() {
		Mock<SomeInterface> mock;
		try {
			Fake(Method(mock, func));
			mock.get().func(1);
			mock.get().func(2);
			fakeit::Verify(Method(mock, func).Using(1)).setFileInfo("test file",1,"test method");
			fakeit::VerifyNoOtherInvocations(Method(mock, func)) //
				.setFileInfo("test file",1,"test method");
		}
		catch (NoMoreInvocationsVerificationException& e) {
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected no more invocations!! But the following unverified invocations were found:\n";
			expectedMsg += "  mock.func(2)";//

			std::string actualMsg{to_string(e)};//
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_UserDefinedMatcher_in_expected_pattern() {
		Mock<SomeInterface> mock;
		When(Method(mock, func)).Return(0);
		//SomeInterface &i = mock.get();
		try {
			fakeit::Verify(Method(mock, func).Matching([](...){return true; })) //
				.setFileInfo("test file",1,"test method").Exactly(2);
			FAIL();
		}
		catch (SequenceVerificationException& e)
		{
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.func( user defined matcher )\n";
			expectedMsg += "Expected matches: exactly 2\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";

			std::string actualMsg {to_string(e)};
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_actual_arguments() {
		Mock<SomeInterface> mock;
		When(Method(mock, all_types)).Return(0);
		//SomeInterface &i = mock.get();
		try {
			mock().all_types('a', true, 1, 1, 1, 1, 1, 1, 1, 1);
			fakeit::Verify(Method(mock, all_types)) //
				.setFileInfo("test file",1,"test method").Exactly(2);
			FAIL();
		}
		catch (SequenceVerificationException& e)
		{
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.all_types( any arguments )\n";
			expectedMsg += "Expected matches: exactly 2\n";
			expectedMsg += "Actual matches  : 1\n";
			expectedMsg += "Actual sequence : total of 1 actual invocations:\n";
			//expectedMsg += "  mock.all_types(?, true, 1, 1, 1, 1, 1, 1, 1.000000, 1.000000)";
			expectedMsg += "  mock.all_types(?, true, 1, 1, 1, 1, 1, 1, 1, 1)";

			std::string actualMsg {to_string(e)};
			std::cout << actualMsg;
			ASSERT_EQUAL(expectedMsg, actualMsg);

		}
	}

	void parse_expected_arguments() {
		Mock<SomeInterface> mock;
		When(Method(mock, all_types)).Return(0);
		//SomeInterface &i = mock.get();
		try {
			fakeit::Verify(Method(mock, all_types).Using('a', true, 1, 1, 1, 1, 1, 1, 1, 1))//
				.setFileInfo("test file", 1, "test method").Exactly(2);
			FAIL();
		}
		catch (SequenceVerificationException& e)
		{
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.all_types( 'a', true, 1, 1, 1, 1, 1, 1, 1.0, 1.0 )\n";
			expectedMsg += "Expected matches: exactly 2\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";
			std::string actual {to_string(e)};
			ASSERT_EQUAL(expectedMsg, actual);
		}
	}

} __DefaultEventFormatting;
<commit_msg>make tests pass on MinGW<commit_after>/*
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Mar 10, 2014
 */

#include <string>
#include <iosfwd>
#include <stdexcept>
#include <tuple>

#include "tpunit++.hpp"
#include "fakeit.hpp"
#include "mockutils/Formatter.hpp"

using namespace fakeit;

struct DefaultEventFormatting: tpunit::TestFixture {
	DefaultEventFormatting() :
			tpunit::TestFixture(
			//
			TEST(DefaultEventFormatting::format_UnmockedMethodCallEvent),
			TEST(DefaultEventFormatting::format_UnmatchedMethodCallEvent),
			TEST(DefaultEventFormatting::format_AnyArguments),
			TEST(DefaultEventFormatting::format_Exactly_Once),
			TEST(DefaultEventFormatting::format_Atleast_Once),
			TEST(DefaultEventFormatting::format_NoMoreInvocations_VerificationFailure),
			TEST(DefaultEventFormatting::format_UserDefinedMatcher_in_expected_pattern),
			TEST(DefaultEventFormatting::format_actual_arguments),
			TEST(DefaultEventFormatting::format_expected_arguments)
			) //
	{
	}

	template <typename T> std::string to_string(T& val){
		std::stringstream stream;
		stream << val;
		return stream.str();
	}

	struct SomeInterface {
		virtual int func(int) = 0;
		virtual void proc(int) = 0;

		virtual int all_types(
			char,
			bool,
			int,
			unsigned int,
			long,
			unsigned long,
			double
			//,
			//long long,
			//unsigned long long,
			//long double
			) = 0;
	};

	void format_UnmockedMethodCallEvent() {
		Mock<SomeInterface> mock;
		SomeInterface &i = mock.get();
		try {
			i.func(1);
			FAIL();
		}
		catch (UnexpectedMethodCallException& e)
		{
			std::string expectedMsg{"Unexpected method invocation: unknown()\n"};
			expectedMsg +=	"  An unmocked method was invoked. All used virtual methods must be stubbed!";
			std::string actual{to_string(e)};
			ASSERT_EQUAL(expectedMsg, actual);
		}
	}

	void format_UnmatchedMethodCallEvent() {
		Mock<SomeInterface> mock;
		Fake(Method(mock,func).Using(3));
		SomeInterface &i = mock.get();
		try {
			i.func(1);
			FAIL();
		}
		catch (UnexpectedMethodCallException& e)
		{
			std::string expectedMsg{"Unexpected method invocation: mock.func(1)\n  Could not find any recorded behavior to support this method call."};
			std::string actual{to_string(e)};
			ASSERT_EQUAL(expectedMsg, actual);
		}
	}

	void format_AnyArguments() {
		Mock<SomeInterface> mock;
		try {
			fakeit::Verify(Method(mock, func)).setFileInfo("test file",1,"test method").Exactly(Once);
		}
		catch (SequenceVerificationException& e) {
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.func( any arguments )\n";
			expectedMsg += "Expected matches: exactly 1\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";
			std::string actualMsg{to_string(e)};
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_Exactly_Once() {
		Mock<SomeInterface> mock;
		try {
			fakeit::Verify(Method(mock, func)).setFileInfo("test file",1,"test method").Exactly(Once);
		}
		catch (SequenceVerificationException& e) {
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.func( any arguments )\n";
			expectedMsg += "Expected matches: exactly 1\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";

			std::string actualMsg{to_string(e)};
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_Atleast_Once() {
		Mock<SomeInterface> mock;
		try {
			fakeit::Verify(Method(mock, func)).setFileInfo("test file",1,"test method").AtLeast(Once);
		}
		catch (SequenceVerificationException& e) {
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.func( any arguments )\n";
			expectedMsg += "Expected matches: at least 1\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";

			std::string actualMsg {to_string(e)};
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_NoMoreInvocations_VerificationFailure() {
		Mock<SomeInterface> mock;
		try {
			Fake(Method(mock, func));
			mock.get().func(1);
			mock.get().func(2);
			fakeit::Verify(Method(mock, func).Using(1)).setFileInfo("test file",1,"test method");
			fakeit::VerifyNoOtherInvocations(Method(mock, func)) //
				.setFileInfo("test file",1,"test method");
		}
		catch (NoMoreInvocationsVerificationException& e) {
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected no more invocations!! But the following unverified invocations were found:\n";
			expectedMsg += "  mock.func(2)";//

			std::string actualMsg{to_string(e)};//
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_UserDefinedMatcher_in_expected_pattern() {
		Mock<SomeInterface> mock;
		When(Method(mock, func)).Return(0);
		//SomeInterface &i = mock.get();
		try {
			fakeit::Verify(Method(mock, func).Matching([](...){return true; })) //
				.setFileInfo("test file",1,"test method").Exactly(2);
			FAIL();
		}
		catch (SequenceVerificationException& e)
		{
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.func( user defined matcher )\n";
			expectedMsg += "Expected matches: exactly 2\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";

			std::string actualMsg {to_string(e)};
			ASSERT_EQUAL(expectedMsg, actualMsg);
		}
	}

	void format_actual_arguments() {
		Mock<SomeInterface> mock;
		When(Method(mock, all_types)).Return(0);
		//SomeInterface &i = mock.get();
		try {
			mock().all_types('a', true, 1, 1, 1, 1, 1);
			fakeit::Verify(Method(mock, all_types)) //
				.setFileInfo("test file",1,"test method").Exactly(2);
			FAIL();
		}
		catch (SequenceVerificationException& e)
		{
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			expectedMsg += "Expected pattern: mock.all_types( any arguments )\n";
			expectedMsg += "Expected matches: exactly 2\n";
			expectedMsg += "Actual matches  : 1\n";
			expectedMsg += "Actual sequence : total of 1 actual invocations:\n";
			//expectedMsg += "  mock.all_types(?, true, 1, 1, 1, 1, 1, 1, 1.000000, 1.000000)";
			expectedMsg += "  mock.all_types(?, true, 1, 1, 1, 1, 1)";

			std::string actualMsg {to_string(e)};
			std::cout << actualMsg;
			ASSERT_EQUAL(expectedMsg, actualMsg);

		}
	}

	void format_expected_arguments() {
		Mock<SomeInterface> mock;
		When(Method(mock, all_types)).Return(0);
		//SomeInterface &i = mock.get();
		try {
			fakeit::Verify(Method(mock, all_types).Using('a', true, 1, 1, 1, 1, 1))//
				.setFileInfo("test file", 1, "test method").Exactly(2);
			FAIL();
		}
		catch (SequenceVerificationException& e)
		{
			std::string expectedMsg;
			expectedMsg += "test file:1: Verification error\n";
			//expectedMsg += "Expected pattern: mock.all_types('a', true, 1, 1, 1, 1, 1)\n";
			expectedMsg += "Expected pattern: mock.all_types(?, true, 1, 1, 1, 1, 1)\n";
			expectedMsg += "Expected matches: exactly 2\n";
			expectedMsg += "Actual matches  : 0\n";
			expectedMsg += "Actual sequence : total of 0 actual invocations.";
			std::string actual {to_string(e)};
			ASSERT_EQUAL(expectedMsg, actual);
		}
	}

} __DefaultEventFormatting;
<|endoftext|>


<commit_before>#include "Player.h"
#include "SDL.h"
#include "InputHandler.h"

Player::Player(const LoaderParams* pParams) : SDLGameObject(pParams) { }

void Player::draw()
{
	SDLGameObject::draw();	//we now use SDLGameObject
}

void Player::update()
{
	m_velocity.setX(0);
	m_velocity.setY(0);

	handleInput();	//adding our function

	m_currentFrame = int(((SDL_GetTicks() / 100) % 6));

	SDLGameObject::update();
}

void Player::clean()
{
	//blank clean() function
}

void Player::handleInput()
{
	if (TheInputHandler::Instance()->joysticksInitialised())
	{
		if ((TheInputHandler::Instance()->xvalue(0, 1) > 0) || (TheInputHandler::Instance()->xvalue(0, 1) < 0))
		{
			m_velocity.setX(1 * TheInputHandler::Instance()->xvalue(0, 1));
		}

		if ((TheInputHandler::Instance()->yvalue(0, 1) > 0) || (TheInputHandler::Instance()->yvalue(0, 1) < 0))
		{
			m_velocity.setY(1 * TheInputHandler::Instance()->yvalue(0, 1));
		}

		if ((TheInputHandler::Instance()->xvalue(0, 2) > 0) || (TheInputHandler::Instance()->xvalue(0, 2) < 0))
		{
			m_velocity.setX(1 * TheInputHandler::Instance()->xvalue(0, 2));
		}

		if ((TheInputHandler::Instance()->yvalue(0, 2) > 0) || (TheInputHandler::Instance()->yvalue(0, 2) < 0))
		{
			m_velocity.setY(1 * TheInputHandler::Instance()->yvalue(0, 2));
		}
	}
}<commit_msg>Fixed compiler's conversion warnings<commit_after>#include "Player.h"
#include "SDL.h"
#include "InputHandler.h"

Player::Player(const LoaderParams* pParams) : SDLGameObject(pParams) { }

void Player::draw()
{
	SDLGameObject::draw();	//we now use SDLGameObject
}

void Player::update()
{
	m_velocity.setX(0);
	m_velocity.setY(0);

	handleInput();	//adding our function

	m_currentFrame = int(((SDL_GetTicks() / 100) % 6));

	SDLGameObject::update();
}

void Player::clean()
{
	//blank clean() function
}

void Player::handleInput()
{
	if (TheInputHandler::Instance()->joysticksInitialised())
	{
		if ((TheInputHandler::Instance()->xvalue(0, 1) > 0) || (TheInputHandler::Instance()->xvalue(0, 1) < 0))
		{
			m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 1));
		}

		if ((TheInputHandler::Instance()->yvalue(0, 1) > 0) || (TheInputHandler::Instance()->yvalue(0, 1) < 0))
		{
			m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 1));
		}

		if ((TheInputHandler::Instance()->xvalue(0, 2) > 0) || (TheInputHandler::Instance()->xvalue(0, 2) < 0))
		{
			m_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 2));
		}

		if ((TheInputHandler::Instance()->yvalue(0, 2) > 0) || (TheInputHandler::Instance()->yvalue(0, 2) < 0))
		{
			m_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 2));
		}
	}
}<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include "graphs/edge_types.hpp"
#include "graphs/graph.hpp"
#include "graphs/topological_sort.hpp"

namespace gt = testing;

namespace pk
{
namespace graphs
{
namespace testing
{

struct topological_sort_tester : public gt::Test
{
    static const int V = 9;
    static const int E = 9;

    typedef edge edge_type;
    typedef graph_factory<V, E, edge_type> graph_factory_type;
    typedef graph_factory_type::graph_type graph_type;

    graph_factory_type gf;
};

TEST_F(topological_sort_tester, tests_sorting_two_not_connected_vertices)
{
    // given
    const int num_of_vertices = 2;
    const graph_type& g = gf.create(num_of_vertices);

    // when
    int order[num_of_vertices];
    topological_sort::run(g, order);

    // then
    EXPECT_EQ(0, order[0]);
    EXPECT_EQ(1, order[1]);
}

TEST_F(topological_sort_tester, tests_sorting_two_connected_vertices)
{
    // given
    const int num_of_vertices = 2;

    gf.add_directed_edge(edge_type(1/*from*/, 0/*to*/));

    const graph_type& g = gf.create(num_of_vertices);

    // when
    int order[num_of_vertices];
    topological_sort::run(g, order);

    // then
    EXPECT_EQ(1, order[0]);
    EXPECT_EQ(0, order[1]);
}

/**
 * Tested graph:
 * (0)    (3)
 *
 * (1)<---(2)
 */
TEST_F(topological_sort_tester, tests_lexicographical_order_of_sorted_vertices)
{
    // given
    const int num_of_vertices = 4;

    gf.add_directed_edge(edge_type(2/*from*/, 1/*to*/));

    const graph_type& g = gf.create(num_of_vertices);

    // when
    int order[num_of_vertices];
    topological_sort::run(g, order);

    // then
    EXPECT_EQ(0, order[0]);
    EXPECT_EQ(2, order[1]);
    EXPECT_EQ(1, order[2]);
    EXPECT_EQ(3, order[3]);
}

/**
 * Tested graph:
 *        (0)           (8)--->(7)
 *         ^             |      |
 *         |             |      |
 *         |\____        |      |
 *         |     \       V      V
 * (1)<---(4)--->(3)<---(5)--->(6)
 */
TEST_F(topological_sort_tester, tests_sorting_bigger_graph)
{
    // given
    const int num_of_vertices = 9;

    gf.add_directed_edge(edge_type(3/*from*/, 0/*to*/));
    gf.add_directed_edge(edge_type(4, 0));
    gf.add_directed_edge(edge_type(4, 1));
    gf.add_directed_edge(edge_type(4, 3));
    gf.add_directed_edge(edge_type(5, 3));
    gf.add_directed_edge(edge_type(5, 6));
    gf.add_directed_edge(edge_type(7, 6));
    gf.add_directed_edge(edge_type(8, 5));
    gf.add_directed_edge(edge_type(8, 7));

    const graph_type& g = gf.create(num_of_vertices);

    // when
    int order[num_of_vertices];
    topological_sort::run(g, order);

    // then
    EXPECT_EQ(2, order[0]);
    EXPECT_EQ(4, order[1]);
    EXPECT_EQ(1, order[2]);
    EXPECT_EQ(8, order[3]);
    EXPECT_EQ(5, order[4]);
    EXPECT_EQ(3, order[5]);
    EXPECT_EQ(0, order[6]);
    EXPECT_EQ(7, order[7]);
    EXPECT_EQ(6, order[8]);
}

} // namespace testing
} // namespace graphs
} // namespace pk
<commit_msg>Minor refactoring<commit_after>#include <gtest/gtest.h>

#include "graphs/edge_types.hpp"
#include "graphs/graph.hpp"
#include "graphs/topological_sort.hpp"

namespace gt = testing;

namespace pk
{
namespace graphs
{
namespace testing
{

struct topological_sort_tester : public gt::Test
{
    static const int V = 9;
    static const int E = 9;

    typedef edge edge_type;
    typedef graph_factory<V, E, edge_type> graph_factory_type;
    typedef graph_factory_type::graph_type graph_type;

    graph_factory_type gf;
};

TEST_F(topological_sort_tester, tests_sorting_two_not_connected_vertices)
{
    // given
    const int num_of_vertices = 2;
    const graph_type& g = gf.create(num_of_vertices);

    // when
    int order[num_of_vertices];
    topological_sort::run(g, order);

    // then
    EXPECT_EQ(0, order[0]);
    EXPECT_EQ(1, order[1]);
}

TEST_F(topological_sort_tester, tests_sorting_two_connected_vertices)
{
    // given
    const int num_of_vertices = 2;

    gf.add_directed_edge(edge_type(1/*from*/, 0/*to*/));

    const graph_type& g = gf.create(num_of_vertices);

    // when
    int order[num_of_vertices];
    topological_sort::run(g, order);

    // then
    EXPECT_EQ(1, order[0]);
    EXPECT_EQ(0, order[1]);
}

/**
 * Tested graph:
 * (0)    (3)
 *
 * (1)<---(2)
 */
TEST_F(topological_sort_tester, tests_lexicographical_order_of_sorted_vertices)
{
    // given
    const int num_of_vertices = 4;

    gf.add_directed_edge(edge_type(2/*from*/, 1/*to*/));

    const graph_type& g = gf.create(num_of_vertices);

    // when
    int order[num_of_vertices];
    topological_sort::run(g, order);

    // then
    EXPECT_EQ(0, order[0]);
    EXPECT_EQ(2, order[1]);
    EXPECT_EQ(1, order[2]);
    EXPECT_EQ(3, order[3]);
}

/**
 * Tested graph:
 *        (0)           (8)--->(7)
 *         ^             |      |
 *  (2)    |             |      |
 *         |\____        |      |
 *         |     \       V      V
 * (1)<---(4)--->(3)<---(5)--->(6)
 */
TEST_F(topological_sort_tester, tests_sorting_bigger_graph)
{
    // given
    const int num_of_vertices = 9;

    gf.add_directed_edge(edge_type(3/*from*/, 0/*to*/));
    gf.add_directed_edge(edge_type(4, 0));
    gf.add_directed_edge(edge_type(4, 1));
    gf.add_directed_edge(edge_type(4, 3));
    gf.add_directed_edge(edge_type(5, 3));
    gf.add_directed_edge(edge_type(5, 6));
    gf.add_directed_edge(edge_type(7, 6));
    gf.add_directed_edge(edge_type(8, 5));
    gf.add_directed_edge(edge_type(8, 7));

    const graph_type& g = gf.create(num_of_vertices);

    // when
    int order[num_of_vertices];
    topological_sort::run(g, order);

    // then
    EXPECT_EQ(2, order[0]);
    EXPECT_EQ(4, order[1]);
    EXPECT_EQ(1, order[2]);
    EXPECT_EQ(8, order[3]);
    EXPECT_EQ(5, order[4]);
    EXPECT_EQ(3, order[5]);
    EXPECT_EQ(0, order[6]);
    EXPECT_EQ(7, order[7]);
    EXPECT_EQ(6, order[8]);
}

} // namespace testing
} // namespace graphs
} // namespace pk
<|endoftext|>


<commit_before>/*
 * GPII Node.js GSettings Bridge
 *
 * Copyright 2012 Steven Githens
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The research leading to these results has received funding from the European Union's
 * Seventh Framework Programme (FP7/2007-2013)
 * under grant agreement no. 289016.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 *
 */

/*
 * For changes done after initial fork from
 * https://github.com/GPII/linux
 * based on commit b28e99212e4c7cc803f210c066e0124d72c8b72d.
 *
 * Copyright 2015 Leopold Burdyl
 */

// #include <stdio.h>
#include <node.h>
#include <v8.h>

#include <gio/gio.h>

using namespace v8;

// in globals
const GVariantType* X_G_VARIANT_TYPE_STRING_TUPLE_ARRAY = g_variant_type_new("a(ss)");

/* Takes schemaId string */
Handle<Value> get_gsetting_keys(const Arguments& args) {
	HandleScope scope;
	GSettings *settings;
	gchar ** keys;
	gint i;
	gint size = 0;

	// write schema string to variable
	Local<String> schema_string_obj = args[0]->ToString();
	int schema_string_length = schema_string_obj->Utf8Length();
	char *schema = (char*) g_malloc(schema_string_length + 1);
	schema_string_obj->WriteUtf8(schema);

	settings = g_settings_new(schema);
	keys = g_settings_list_keys(settings);
	for (i = 0; keys[i]; i++) {
		size++; // Figure out how to do this in 1 loop
	}
	Handle<Array> togo;
	togo = Array::New(size);
	for (i = 0; keys[i]; i++) {
		togo->Set(i,String::New(keys[i]));
	}
	return scope.Close(togo);
}

/* Helper function - because we do this A LOT */
char * v8_value_to_utf8_string(const Local<Value> value_obj) {
	Local<String>  string_obj                = value_obj->ToString();
	int            utf8_string_length        = string_obj->Utf8Length();
	char          *utf8_string               = (char*) g_malloc(utf8_string_length + 1);

	string_obj->WriteUtf8(utf8_string);

	return utf8_string;
}

/* Takes schemaId and key */
Handle<Value> get_gsetting(const Arguments& args) {
	HandleScope         scope;
	GSettings          *settings;
	GVariant           *variant;
	const GVariantType *type;
	const char         *schema;
	const char         *key;

	schema   = v8_value_to_utf8_string(args[0]);
	key      = v8_value_to_utf8_string(args[1]);

	settings = g_settings_new(schema);
	variant  = g_settings_get_value(settings,key);
	type     = g_variant_get_type(variant);

	if (g_variant_type_equal(type,G_VARIANT_TYPE_DOUBLE)) {
		return scope.Close(Number::New(g_variant_get_double(variant)));
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_INT32)) {
		return scope.Close(Int32::New(g_variant_get_int32(variant)));
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_UINT32)) {
		return scope.Close(Uint32::New(g_variant_get_uint32(variant)));
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_STRING)) {
		return scope.Close(String::New(g_variant_get_string(variant,NULL)));
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_STRING_ARRAY)) {
		gsize length;
		const gchar **elems = g_variant_get_strv(variant,&length);

		HandleScope scope;
		Local<Array> nodes = Array::New();

		for (unsigned int i = 0; i < length; ++i) {
			nodes->Set(i, String::New(elems[i]));
		}

		return scope.Close(nodes);
	}
	else if (g_variant_type_equal(type, X_G_VARIANT_TYPE_STRING_TUPLE_ARRAY)) {
		Local<Array> tuple_array = Array::New();

		GVariantIter *iter;
		gchar *str1;
		gchar *str2;
		unsigned int i = 0;

		g_variant_get (variant, "a(ss)", &iter);
		while (g_variant_iter_loop (iter, "(ss)", &str1, &str2)) {
			Local<Array> tuple = Array::New();
			tuple->Set(0, String::New(str1));
			tuple->Set(1, String::New(str2));
			tuple_array->Set(i, tuple);
			i++;
		}
		g_variant_iter_free (iter);

		return scope.Close(tuple_array);
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_BOOLEAN)) {
		return scope.Close(Boolean::New(g_variant_get_boolean(variant)));
	}
	else {
		g_print("The type is %s\n", g_variant_type_peek_string(type));
		ThrowException(Exception::Error(String::New("Need to implement reading that value type")));
		return scope.Close(Undefined());
	}
}

/* Takes schemaId string */
Handle<Value> schema_exists(const Arguments& args) {
	HandleScope            scope;
	char                  *schema_id     = v8_value_to_utf8_string(args[0]);
	GSettingsSchemaSource *schema_source = g_settings_schema_source_get_default();

	if ( ! schema_source ) {
		ThrowException(Exception::Error(String::New("No schema sources available!")));
		return scope.Close(Undefined());
	}

	GSettingsSchema * schema =
		g_settings_schema_source_lookup (schema_source,
		                                 schema_id,
		                                 FALSE);

	if ( ! schema ) {
		return scope.Close(Boolean::New(FALSE));
	}

	return scope.Close(Boolean::New(TRUE));
}

/* Takes schemaId, key, and value */
Handle<Value> set_gsetting(const Arguments& args) {
	HandleScope         scope;
	Local<Value>        value_obj = args[2];
	GSettings          *settings;
	GVariant           *variant;
	const GVariantType *type;
	bool                success = false;
	const char         *schema;
	const char         *key;

	schema   = v8_value_to_utf8_string(args[0]);
	key      = v8_value_to_utf8_string(args[1]);

	settings = g_settings_new(schema);
	variant  = g_settings_get_value(settings,key);
	type     = g_variant_get_type(variant);

	if ( g_variant_type_equal(type,G_VARIANT_TYPE_BOOLEAN) ) {
		if ( value_obj->IsBoolean() ) {
			success = g_settings_set_boolean(settings,key,value_obj->BooleanValue());
		} else {
			ThrowException(Exception::Error(String::New("Key requires boolean value!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type,G_VARIANT_TYPE_STRING) ) {
		if ( value_obj->IsString() ) {
			char *val = v8_value_to_utf8_string(value_obj);

			success = g_settings_set_string(settings,key,val);
		} else {
			ThrowException(Exception::Error(String::New("Key requires string value!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type, G_VARIANT_TYPE_DOUBLE) ) {
		if ( value_obj->IsNumber() ) {
			success = g_settings_set_double(settings,key,value_obj->ToNumber()->Value());
		} else {
			ThrowException(Exception::Error(String::New("Key requires a number!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type, G_VARIANT_TYPE_INT32) ) {
		if ( value_obj->IsInt32() || value_obj->IsUint32() ) {
			success = g_settings_set_int(settings,key,value_obj->ToInt32()->Value());
		} else {
			ThrowException(Exception::Error(String::New("Key requires a integer number!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type, G_VARIANT_TYPE_UINT32) ) {
		if ( value_obj->IsUint32() ) {
			success = g_settings_set_uint(settings,key,value_obj->ToUint32()->Value());
		} else {
			ThrowException(Exception::Error(String::New("Key requires a unsigned integer number!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type, G_VARIANT_TYPE_STRING_ARRAY) ) {
		if ( value_obj->IsArray() ) {
			GVariantBuilder  builder;
			GVariant        *string_array_varient;
			uint             i;
			uint             length;
			Local<Object>    obj = value_obj->ToObject();

			// get the array length
			length = obj->Get(String::New("length"))->ToObject()->Uint32Value();

			g_variant_builder_init (&builder, G_VARIANT_TYPE_STRING_ARRAY);

			for(i = 0; i < length; i++)
			{
				Local<Value> element = obj->Get(i);

				if ( element->IsString() ) {
					char *val                = v8_value_to_utf8_string(element);
					GVariant *string_variant = g_variant_new_string ((const gchar *) val);

					g_variant_builder_add_value (&builder, string_variant);
				}
				else {
					ThrowException(Exception::Error(String::New("Invalid Array format!")));
					return scope.Close(Undefined());
				}
			}

			string_array_varient = g_variant_builder_end (&builder);

			success = g_settings_set_value(settings, key, string_array_varient);
		} else {
			ThrowException(Exception::Error(String::New("Key requires an array of strings!")));
			return scope.Close(Undefined());
		}
	}
	else {
		ThrowException(Exception::Error(String::New("We haven't implemented this type yet!")));
	}

	g_settings_sync();

	if ( ! success ) {
		ThrowException(Exception::Error(String::New("Failed to set gsetting!")));
	}

	return scope.Close(Undefined());
}

/* in addon initialization function */
void init(Handle<Object> target) {
	target->Set(String::NewSymbol("set_gsetting"),
	            FunctionTemplate::New(set_gsetting)->GetFunction());
	target->Set(String::NewSymbol("get_gsetting"),
	            FunctionTemplate::New(get_gsetting)->GetFunction());
	target->Set(String::NewSymbol("get_gsetting_keys"),
	            FunctionTemplate::New(get_gsetting_keys)->GetFunction());
	target->Set(String::NewSymbol("schema_exists"),
	            FunctionTemplate::New(schema_exists)->GetFunction());
}

NODE_MODULE(nodegsettings, init)<commit_msg>Improve binding.<commit_after>/*
 * GPII Node.js GSettings Bridge
 *
 * Copyright 2012 Steven Githens
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The research leading to these results has received funding from the European Union's
 * Seventh Framework Programme (FP7/2007-2013)
 * under grant agreement no. 289016.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 *
 */

/*
 * For changes done after initial fork from
 * https://github.com/GPII/linux
 * based on commit b28e99212e4c7cc803f210c066e0124d72c8b72d.
 *
 * Copyright 2015 Leopold Burdyl
 */

#include <node.h>
#include <v8.h>
#include <gio/gio.h>

using namespace v8;

// in globals
const GVariantType* X_G_VARIANT_TYPE_STRING_TUPLE_ARRAY = g_variant_type_new("a(ss)");

/* Helper function - because we do this A LOT */
char * v8_value_to_utf8_string(const Local<Value> value_obj) {
	Local<String>  string_obj                = value_obj->ToString();
	int            utf8_string_length        = string_obj->Utf8Length();
	char          *utf8_string               = (char*) g_malloc(utf8_string_length + 1);

	string_obj->WriteUtf8(utf8_string);

	return utf8_string;
}

/* Takes schemaId string */
Handle<Value> get_gsetting_keys(const Arguments& args) {
	HandleScope scope;
	GSettings *settings;
	gchar ** keys;
	gint i;
	gint size = 0;

	char *schema = v8_value_to_utf8_string(args[0]);

	settings = g_settings_new(schema);
	keys = g_settings_list_keys(settings);
	for (i = 0; keys[i]; i++) {
		size++; // Figure out how to do this in 1 loop
	}
	Handle<Array> togo;
	togo = Array::New(size);
	for (i = 0; keys[i]; i++) {
		togo->Set(i,String::New(keys[i]));
	}
	return scope.Close(togo);
}

/* Takes schemaId and key */
Handle<Value> get_gsetting(const Arguments& args) {
	HandleScope         scope;
	GSettings          *settings;
	GVariant           *variant;
	const GVariantType *type;
	const char         *schema;
	const char         *key;

	schema   = v8_value_to_utf8_string(args[0]);
	key      = v8_value_to_utf8_string(args[1]);

	settings = g_settings_new(schema);
	variant  = g_settings_get_value(settings,key);
	type     = g_variant_get_type(variant);

	if (g_variant_type_equal(type,G_VARIANT_TYPE_DOUBLE)) {
		return scope.Close(Number::New(g_variant_get_double(variant)));
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_INT32)) {
		return scope.Close(Int32::New(g_variant_get_int32(variant)));
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_UINT32)) {
		return scope.Close(Uint32::New(g_variant_get_uint32(variant)));
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_STRING)) {
		return scope.Close(String::New(g_variant_get_string(variant,NULL)));
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_STRING_ARRAY)) {
		gsize length;
		const gchar **elems = g_variant_get_strv(variant,&length);

		HandleScope scope;
		Local<Array> nodes = Array::New();

		for (unsigned int i = 0; i < length; ++i) {
			nodes->Set(i, String::New(elems[i]));
		}

		return scope.Close(nodes);
	}
	else if (g_variant_type_equal(type, X_G_VARIANT_TYPE_STRING_TUPLE_ARRAY)) {
		Local<Array> tuple_array = Array::New();

		GVariantIter *iter;
		gchar *str1;
		gchar *str2;
		unsigned int i = 0;

		g_variant_get (variant, "a(ss)", &iter);
		while (g_variant_iter_loop (iter, "(ss)", &str1, &str2)) {
			Local<Array> tuple = Array::New();
			tuple->Set(0, String::New(str1));
			tuple->Set(1, String::New(str2));
			tuple_array->Set(i, tuple);
			i++;
		}
		g_variant_iter_free (iter);

		return scope.Close(tuple_array);
	}
	else if (g_variant_type_equal(type,G_VARIANT_TYPE_BOOLEAN)) {
		return scope.Close(Boolean::New(g_variant_get_boolean(variant)));
	}
	else {
		g_print("The type is %s\n", g_variant_type_peek_string(type));
		ThrowException(Exception::Error(String::New("Need to implement reading that value type")));
		return scope.Close(Undefined());
	}
}

/* Takes schemaId string */
Handle<Value> schema_exists(const Arguments& args) {
	HandleScope            scope;
	char                  *schema_id     = v8_value_to_utf8_string(args[0]);
	GSettingsSchemaSource *schema_source = g_settings_schema_source_get_default();

	if ( ! schema_source ) {
		ThrowException(Exception::Error(String::New("No schema sources available!")));
		return scope.Close(Undefined());
	}

	GSettingsSchema * schema =
		g_settings_schema_source_lookup (schema_source,
		                                 schema_id,
		                                 FALSE);

	if ( ! schema ) {
		return scope.Close(Boolean::New(FALSE));
	}

	return scope.Close(Boolean::New(TRUE));
}

/* Takes schemaId, key, and value */
Handle<Value> set_gsetting(const Arguments& args) {
	HandleScope         scope;
	Local<Value>        value_obj = args[2];
	GSettings          *settings;
	GVariant           *variant;
	const GVariantType *type;
	bool                success = false;
	const char         *schema;
	const char         *key;

	schema   = v8_value_to_utf8_string(args[0]);
	key      = v8_value_to_utf8_string(args[1]);

	settings = g_settings_new(schema);
	variant  = g_settings_get_value(settings,key);
	type     = g_variant_get_type(variant);

	if ( g_variant_type_equal(type,G_VARIANT_TYPE_BOOLEAN) ) {
		if ( value_obj->IsBoolean() ) {
			success = g_settings_set_boolean(settings,key,value_obj->BooleanValue());
		} else {
			ThrowException(Exception::Error(String::New("Key requires boolean value!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type,G_VARIANT_TYPE_STRING) ) {
		if ( value_obj->IsString() ) {
			char *val = v8_value_to_utf8_string(value_obj);

			success = g_settings_set_string(settings,key,val);
		} else {
			ThrowException(Exception::Error(String::New("Key requires string value!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type, G_VARIANT_TYPE_DOUBLE) ) {
		if ( value_obj->IsNumber() ) {
			success = g_settings_set_double(settings,key,value_obj->ToNumber()->Value());
		} else {
			ThrowException(Exception::Error(String::New("Key requires a number!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type, G_VARIANT_TYPE_INT32) ) {
		if ( value_obj->IsInt32() || value_obj->IsUint32() ) {
			success = g_settings_set_int(settings,key,value_obj->ToInt32()->Value());
		} else {
			ThrowException(Exception::Error(String::New("Key requires a integer number!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type, G_VARIANT_TYPE_UINT32) ) {
		if ( value_obj->IsUint32() ) {
			success = g_settings_set_uint(settings,key,value_obj->ToUint32()->Value());
		} else {
			ThrowException(Exception::Error(String::New("Key requires a unsigned integer number!")));
			return scope.Close(Undefined());
		}
	}
	else if ( g_variant_type_equal(type, G_VARIANT_TYPE_STRING_ARRAY) ) {
		if ( value_obj->IsArray() ) {
			GVariantBuilder  builder;
			GVariant        *string_array_varient;
			uint             i;
			uint             length;
			Local<Object>    obj = value_obj->ToObject();

			// get the array length
			length = obj->Get(String::New("length"))->ToObject()->Uint32Value();

			g_variant_builder_init (&builder, G_VARIANT_TYPE_STRING_ARRAY);

			for(i = 0; i < length; i++)
			{
				Local<Value> element = obj->Get(i);

				if ( element->IsString() ) {
					char *val                = v8_value_to_utf8_string(element);
					GVariant *string_variant = g_variant_new_string ((const gchar *) val);

					g_variant_builder_add_value (&builder, string_variant);
				}
				else {
					ThrowException(Exception::Error(String::New("Array item have to be strings!")));
					return scope.Close(Undefined());
				}
			}

			string_array_varient = g_variant_builder_end (&builder);

			success = g_settings_set_value(settings, key, string_array_varient);
		} else {
			ThrowException(Exception::Error(String::New("Key requires an array of strings!")));
			return scope.Close(Undefined());
		}
	}
	else {
		ThrowException(Exception::Error(String::New("We haven't implemented this type yet!")));
	}

	g_settings_sync();

	if ( ! success ) {
		ThrowException(Exception::Error(String::New("Failed to set gsetting!")));
	}

	return scope.Close(Undefined());
}

/* in addon initialization function */
void init(Handle<Object> target) {
	target->Set(String::NewSymbol("set_gsetting"),
	            FunctionTemplate::New(set_gsetting)->GetFunction());
	target->Set(String::NewSymbol("get_gsetting"),
	            FunctionTemplate::New(get_gsetting)->GetFunction());
	target->Set(String::NewSymbol("get_gsetting_keys"),
	            FunctionTemplate::New(get_gsetting_keys)->GetFunction());
	target->Set(String::NewSymbol("schema_exists"),
	            FunctionTemplate::New(schema_exists)->GetFunction());
}

NODE_MODULE(nodegsettings, init)<|endoftext|>


<commit_before>/***************************************************************************//**
 * FILE : scenepicker.hpp
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is libZinc.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef __ZN_SCENE_PICKER_HPP__
#define __ZN_SCENE_PICKER_HPP__

#include "zinc/element.hpp"
#include "zinc/graphic.hpp"
#include "zinc/graphicsfilter.hpp"
#include "zinc/fieldtypesgroup.hpp"
#include "zinc/node.hpp"
#include "zinc/scene.hpp"
#include "zinc/scenepicker.h"
#include "zinc/sceneviewer.hpp"

namespace zinc
{

class ScenePicker
{
protected:
	Cmiss_scene_picker_id id;

public:

	ScenePicker() : id(0)
	{  }

	// takes ownership of C handle, responsibility for destroying it
	explicit ScenePicker(Cmiss_scene_picker_id in_scene_picker_id) :
		id(in_scene_picker_id)
	{  }

	ScenePicker(const ScenePicker& scene_picker) :
		id(Cmiss_scene_picker_access(scene_picker.id))
	{  }

	ScenePicker& operator=(const ScenePicker& scene_picker)
	{
		Cmiss_scene_picker_id temp_id = Cmiss_scene_picker_access(scene_picker.id);
		if (0 != id)
		{
			Cmiss_scene_picker_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~ScenePicker()
	{
		if (0 != id)
		{
			Cmiss_scene_picker_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_scene_picker_id getId()
	{
		return id;
	}

	int setSceneViewerRectangle(SceneViewer& sceneViewer, Graphic::CoordinateSystem coordinateSystem, double x1,
		double y1, double x2, double y2)
	{
		return Cmiss_scene_picker_set_scene_viewer_rectangle(
			id , sceneViewer.getId(),
			static_cast<Cmiss_graphics_coordinate_system>(coordinateSystem),
			x1, y1, x2, y2);
	}

	Element getNearestElement()
	{
		return Element(Cmiss_scene_picker_get_nearest_element(id));
	}

	Node getNearestNode()
	{
		return Node(Cmiss_scene_picker_get_nearest_node(id));
	}

	Graphic getNearestElementGraphic()
	{
		return Graphic(Cmiss_scene_picker_get_nearest_element_graphic(id));
	}

	Graphic getNearestNodeGraphic()
	{
		return Graphic(Cmiss_scene_picker_get_nearest_node_graphic(id));
	}

	Graphic getNearestGraphic()
	{
		return Graphic(Cmiss_scene_picker_get_nearest_graphic(id));
	}

	int addPickedElementsToGroup(FieldGroup& fieldGroup)
	{
		return Cmiss_scene_picker_add_picked_elements_to_group(id,
			(reinterpret_cast<Cmiss_field_group_id>(fieldGroup.getId())));
	}

	int addPickedNodesToGroup(FieldGroup& fieldGroup)
	{
		return Cmiss_scene_picker_add_picked_nodes_to_group(id,
			(reinterpret_cast<Cmiss_field_group_id>(fieldGroup.getId())));
	}

	Scene getScene()
	{
		return Scene(Cmiss_scene_picker_get_scene(id));
	}

	int setScene(Scene& scene)
	{
		return Cmiss_scene_picker_set_scene(id, scene.getId());
	}

	GraphicsFilter getGraphicsFilter()
	{
		return GraphicFilter(Cmiss_scene_picker_get_graphics_filter(id));
	}

	int setGraphicsFilter(GraphicsFilter& filter)
	{
		return Cmiss_scene_picker_set_graphics_filter(id, filter.getId());
	}

};

inline ScenePicker Scene::createPicker()
{
	return ScenePicker(Cmiss_scene_create_picker(id));
}

}  // namespace zinc

#endif /* __ZN_SCENE_HPP__ */
<commit_msg>Fixed a typo in scenepicker.hpp. Whereas GraphicFilter should be GraphicsFilter instead. https://tracker.physiomeproject.org/show_bug.cgi?id=3550<commit_after>/***************************************************************************//**
 * FILE : scenepicker.hpp
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is libZinc.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef __ZN_SCENE_PICKER_HPP__
#define __ZN_SCENE_PICKER_HPP__

#include "zinc/element.hpp"
#include "zinc/graphic.hpp"
#include "zinc/graphicsfilter.hpp"
#include "zinc/fieldtypesgroup.hpp"
#include "zinc/node.hpp"
#include "zinc/scene.hpp"
#include "zinc/scenepicker.h"
#include "zinc/sceneviewer.hpp"

namespace zinc
{

class ScenePicker
{
protected:
	Cmiss_scene_picker_id id;

public:

	ScenePicker() : id(0)
	{  }

	// takes ownership of C handle, responsibility for destroying it
	explicit ScenePicker(Cmiss_scene_picker_id in_scene_picker_id) :
		id(in_scene_picker_id)
	{  }

	ScenePicker(const ScenePicker& scene_picker) :
		id(Cmiss_scene_picker_access(scene_picker.id))
	{  }

	ScenePicker& operator=(const ScenePicker& scene_picker)
	{
		Cmiss_scene_picker_id temp_id = Cmiss_scene_picker_access(scene_picker.id);
		if (0 != id)
		{
			Cmiss_scene_picker_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~ScenePicker()
	{
		if (0 != id)
		{
			Cmiss_scene_picker_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_scene_picker_id getId()
	{
		return id;
	}

	int setSceneViewerRectangle(SceneViewer& sceneViewer, Graphic::CoordinateSystem coordinateSystem, double x1,
		double y1, double x2, double y2)
	{
		return Cmiss_scene_picker_set_scene_viewer_rectangle(
			id , sceneViewer.getId(),
			static_cast<Cmiss_graphics_coordinate_system>(coordinateSystem),
			x1, y1, x2, y2);
	}

	Element getNearestElement()
	{
		return Element(Cmiss_scene_picker_get_nearest_element(id));
	}

	Node getNearestNode()
	{
		return Node(Cmiss_scene_picker_get_nearest_node(id));
	}

	Graphic getNearestElementGraphic()
	{
		return Graphic(Cmiss_scene_picker_get_nearest_element_graphic(id));
	}

	Graphic getNearestNodeGraphic()
	{
		return Graphic(Cmiss_scene_picker_get_nearest_node_graphic(id));
	}

	Graphic getNearestGraphic()
	{
		return Graphic(Cmiss_scene_picker_get_nearest_graphic(id));
	}

	int addPickedElementsToGroup(FieldGroup& fieldGroup)
	{
		return Cmiss_scene_picker_add_picked_elements_to_group(id,
			(reinterpret_cast<Cmiss_field_group_id>(fieldGroup.getId())));
	}

	int addPickedNodesToGroup(FieldGroup& fieldGroup)
	{
		return Cmiss_scene_picker_add_picked_nodes_to_group(id,
			(reinterpret_cast<Cmiss_field_group_id>(fieldGroup.getId())));
	}

	Scene getScene()
	{
		return Scene(Cmiss_scene_picker_get_scene(id));
	}

	int setScene(Scene& scene)
	{
		return Cmiss_scene_picker_set_scene(id, scene.getId());
	}

	GraphicsFilter getGraphicsFilter()
	{
		return GraphicsFilter(Cmiss_scene_picker_get_graphics_filter(id));
	}

	int setGraphicsFilter(GraphicsFilter& filter)
	{
		return Cmiss_scene_picker_set_graphics_filter(id, filter.getId());
	}

};

inline ScenePicker Scene::createPicker()
{
	return ScenePicker(Cmiss_scene_create_picker(id));
}

}  // namespace zinc

#endif /* __ZN_SCENE_HPP__ */
<|endoftext|>


<commit_before>// SPDX-License-Identifier: MIT
/**
   Copyright (c) 2021 - 2022 Beckhoff Automation GmbH & Co. KG
 */

#include "RTimeAccess.h"
#include "Log.h"
#include <iostream>
#include <limits>

static std::ostream& operator<<(std::ostream& os, const bhf::ads::RTimeCpuLatency& info)
{
    return os << std::dec << info.current << " " << info.maximum << " " << info.limit;
}

std::ostream& operator<<(std::ostream& os, const bhf::ads::RTimeCpuSettings& info)
{
    return os << std::hex <<
           "nWinCPUs: " << info.nWinCPUs << '\n' <<
           "nNonWinCPUs: " << info.nNonWinCPUs << '\n' <<
           "dwAffinityMask: " << info.affinityMask << '\n' <<
           "nRtCpus: " << info.nRtCpus << '\n' <<
           "nCpuType: " << info.nCpuType << '\n' <<
           "nCpuFamily: " << info.nCpuFamily << '\n' <<
           "nCpuFreq: " << std::dec << info.nCpuFreq << '\n'
    ;
}

namespace bhf
{
namespace ads
{
RTimeAccess::RTimeAccess(const std::string& gw, const AmsNetId netid, const uint16_t port)
    : device(gw, netid, port ? port : 200)
{}

long RTimeAccess::ShowLatency(const uint32_t indexOffset, const uint32_t cpuId) const
{
    struct RTimeCpuLatency info;
    uint32_t bytesRead;

    const auto status = device.ReadWriteReqEx2(
        ADSSRVID_READDEVICEINFO,
        indexOffset,
        sizeof(info), &info,
        sizeof(cpuId), &cpuId,
        &bytesRead
        );

    if (ADSERR_NOERR != status) {
        LOG_ERROR(__FUNCTION__ << "(" << std::dec << cpuId << "): failed with: 0x" << std::hex << status << '\n');
        return status;
    }
    std::cout << std::dec << cpuId << ": " << info << '\n';
    return 0;
}

long RTimeAccess::ShowLatency(const uint32_t indexOffset) const
{
    struct RTimeCpuSettings info;
    uint32_t bytesRead;

    const auto status = device.ReadReqEx2(ADSSRVID_READDEVICEINFO, RTIME_CPU_SETTINGS, sizeof(info), &info, &bytesRead);
    if (ADSERR_NOERR != status) {
        LOG_ERROR(__FUNCTION__ << "(): failed with: 0x" << std::hex << status << '\n');
        return status;
    }
    std::cout << "RTimeCpuSettings:\n" << info;
    for (uint8_t cpuId = 0; cpuId < 8 * sizeof(info.affinityMask); ++cpuId) {
        static_assert((8 * sizeof(info.affinityMask) < std::numeric_limits<decltype(cpuId)>::max()),
                      "cpuId is to small for affinityMask");
        if (info.affinityMask & (1ULL << cpuId)) {
            ShowLatency(indexOffset, cpuId);
        }
    }
    return 0;
}
}
}
<commit_msg>RTimeAccess: use decimal output for plain numbers<commit_after>// SPDX-License-Identifier: MIT
/**
   Copyright (c) 2021 - 2022 Beckhoff Automation GmbH & Co. KG
 */

#include "RTimeAccess.h"
#include "Log.h"
#include <iostream>
#include <limits>

static std::ostream& operator<<(std::ostream& os, const bhf::ads::RTimeCpuLatency& info)
{
    return os << std::dec << info.current << " " << info.maximum << " " << info.limit;
}

std::ostream& operator<<(std::ostream& os, const bhf::ads::RTimeCpuSettings& info)
{
    return os << std::dec <<
           "nWinCPUs: " << info.nWinCPUs << '\n' <<
           "nNonWinCPUs: " << info.nNonWinCPUs << '\n' <<
           "dwAffinityMask: 0x" << std::hex << info.affinityMask << '\n' <<
           "nRtCpus: " << std::dec << info.nRtCpus << '\n' <<
           "nCpuType: 0x" << std::hex << info.nCpuType << '\n' <<
           "nCpuFamily: 0x" << info.nCpuFamily << '\n' <<
           "nCpuFreq: " << std::dec << info.nCpuFreq << '\n'
    ;
}

namespace bhf
{
namespace ads
{
RTimeAccess::RTimeAccess(const std::string& gw, const AmsNetId netid, const uint16_t port)
    : device(gw, netid, port ? port : 200)
{}

long RTimeAccess::ShowLatency(const uint32_t indexOffset, const uint32_t cpuId) const
{
    struct RTimeCpuLatency info;
    uint32_t bytesRead;

    const auto status = device.ReadWriteReqEx2(
        ADSSRVID_READDEVICEINFO,
        indexOffset,
        sizeof(info), &info,
        sizeof(cpuId), &cpuId,
        &bytesRead
        );

    if (ADSERR_NOERR != status) {
        LOG_ERROR(__FUNCTION__ << "(" << std::dec << cpuId << "): failed with: 0x" << std::hex << status << '\n');
        return status;
    }
    std::cout << std::dec << cpuId << ": " << info << '\n';
    return 0;
}

long RTimeAccess::ShowLatency(const uint32_t indexOffset) const
{
    struct RTimeCpuSettings info;
    uint32_t bytesRead;

    const auto status = device.ReadReqEx2(ADSSRVID_READDEVICEINFO, RTIME_CPU_SETTINGS, sizeof(info), &info, &bytesRead);
    if (ADSERR_NOERR != status) {
        LOG_ERROR(__FUNCTION__ << "(): failed with: 0x" << std::hex << status << '\n');
        return status;
    }
    std::cout << "RTimeCpuSettings:\n" << info;
    for (uint8_t cpuId = 0; cpuId < 8 * sizeof(info.affinityMask); ++cpuId) {
        static_assert((8 * sizeof(info.affinityMask) < std::numeric_limits<decltype(cpuId)>::max()),
                      "cpuId is to small for affinityMask");
        if (info.affinityMask & (1ULL << cpuId)) {
            ShowLatency(indexOffset, cpuId);
        }
    }
    return 0;
}
}
}
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is libZinc.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef __SCENE_VIEWER_HPP__
#define __SCENE_VIEWER_HPP__

#include "zinc/sceneviewer.h"
#include "zinc/sceneviewerinput.h"
#include "zinc/scene.hpp"
#include "zinc/graphicsfilter.hpp"

namespace zinc
{

class SceneViewerInput
{
protected:
	Cmiss_scene_viewer_input_id id;

public:
	enum InputEventType
	{
		INPUT_EVENT_TYPE_INVALID = CMISS_SCENE_VIEWER_INPUT_INVALID,
		INPUT_EVENT_TYPE_MOTION_NOTIFY = CMISS_SCENE_VIEWER_INPUT_MOTION_NOTIFY,
		INPUT_EVENT_TYPE_BUTTON_PRESS = CMISS_SCENE_VIEWER_INPUT_BUTTON_PRESS,
		INPUT_EVENT_TYPE_BUTTON_RELEASE = CMISS_SCENE_VIEWER_INPUT_BUTTON_RELEASE,
		INPUT_EVENT_TYPE_KEY_PRESS = CMISS_SCENE_VIEWER_INPUT_KEY_PRESS,
		INPUT_EVENT_TYPE_KEY_RELEASE = CMISS_SCENE_VIEWER_INPUT_KEY_RELEASE
	};

	enum InputButtonType
	{
		INPUT_BUTTON_INVALID = CMISS_SCENE_VIEWER_INPUT_BUTTON_INVALID,
		INPUT_BUTTON_LEFT = CMISS_SCENE_VIEWER_INPUT_BUTTON_LEFT,
		INPUT_BUTTON_MIDDLE = CMISS_SCENE_VIEWER_INPUT_BUTTON_MIDDLE,
		INPUT_BUTTON_RIGHT = CMISS_SCENE_VIEWER_INPUT_BUTTON_RIGHT,
		INPUT_BUTTON_SCROLL_DOWN = CMISS_SCENE_VIEWER_INPUT_BUTTON_SCROLL_DOWN,
		INPUT_BUTTON_SCROLL_UP = CMISS_SCENE_VIEWER_INPUT_BUTTON_SCROLL_UP
	};

	SceneViewerInput() : id(0)
	{  }

	// takes ownership of C-style region reference
	explicit SceneViewerInput(Cmiss_scene_viewer_input_id in_scene_viewer_input_id) :
		id(in_scene_viewer_input_id)
	{  }

	SceneViewerInput(const SceneViewerInput& scene_viewer_input) :
		id(Cmiss_scene_viewer_input_access(scene_viewer_input.id))
	{  }

	SceneViewerInput& operator=(const SceneViewerInput& scene_viewer_input)
	{
		Cmiss_scene_viewer_input_id temp_id = Cmiss_scene_viewer_input_access(scene_viewer_input.id);
		if (0 != id)
		{
			Cmiss_scene_viewer_input_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~SceneViewerInput()
	{
		if (0 != id)
		{
			Cmiss_scene_viewer_input_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_scene_viewer_input_id getId()
	{
		return id;
	}

	int setPosition(int x, int y)
	{
		return Cmiss_scene_viewer_input_set_position(id, x, y);
	}

	int setButtonNumber(int number)
	{
		return Cmiss_scene_viewer_input_set_button_number(id, number);
	}

	int setButton(InputButtonType button)
	{
		return Cmiss_scene_viewer_input_set_button(id, static_cast<Cmiss_scene_viewer_input_button_type>(button));
	}

	int setType(InputEventType type)
	{
		return Cmiss_scene_viewer_input_set_type(id, static_cast<Cmiss_scene_viewer_input_event_type>(type));
	}

};

class SceneViewer
{
protected:
	Cmiss_scene_viewer_id id;

public:

	enum BufferingMode
	{
		BUFFERING_MODE_ANY = CMISS_SCENE_VIEWER_BUFFERING_ANY_MODE,
		BUFFERING_MODE_SINGLE = CMISS_SCENE_VIEWER_BUFFERING_SINGLE,
		BUFFERING_MODE_DOUBLE = CMISS_SCENE_VIEWER_BUFFERING_DOUBLE,
		BUFFERING_MODE_RENDER_OFFSCREEN_AND_COPY = CMISS_SCENE_VIEWER_BUFFERING_RENDER_OFFSCREEN_AND_COPY,
		BUFFERING_MODE_RENDER_OFFSCREEN_AND_BLEND = CMISS_SCENE_VIEWER_BUFFERING_RENDER_OFFSCREEN_AND_BLEND
	};

	enum StereoMode
	{
		STEREO_MODE_ANY = CMISS_SCENE_VIEWER_STEREO_ANY_MODE,
		STEREO_MODE_MONO = CMISS_SCENE_VIEWER_STEREO_MONO,
		STEREO_MODE_STEREO = CMISS_SCENE_VIEWER_STEREO_STEREO
	};

	SceneViewer() : id(0)
	{  }

	// takes ownership of C-style region reference
	explicit SceneViewer(Cmiss_scene_viewer_id in_scene_viewer_id) :
		id(in_scene_viewer_id)
	{  }

	SceneViewer(const SceneViewer& scene_viewer_module) :
		id(Cmiss_scene_viewer_access(scene_viewer_module.id))
	{  }

	SceneViewer& operator=(const SceneViewer& scene_viewer)
	{
		Cmiss_scene_viewer_id temp_id = Cmiss_scene_viewer_access(scene_viewer.id);
		if (0 != id)
		{
			Cmiss_scene_viewer_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~SceneViewer()
	{
		if (0 != id)
		{
			Cmiss_scene_viewer_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_scene_viewer_id getId()
	{
		return id;
	}

	int renderScene()
	{
		return Cmiss_scene_viewer_render_scene(id);
	}

	int setScene(Scene scene)
	{
		return Cmiss_scene_viewer_set_scene(id, scene.getId());
	}

	Scene getScene()
	{
		return Scene(Cmiss_scene_viewer_get_scene(id));
	}

	int setFilter(GraphicsFilter graphicsFilter)
	{
		return Cmiss_scene_viewer_set_filter(id, graphicsFilter.getId());
	}

	GraphicsFilter getGraphicsFilter()
	{
		return GraphicsFilter(Cmiss_scene_viewer_get_filter(id));
	}

	int setGraphicsBufferWidth(int width)
	{
		return Cmiss_scene_viewer_set_graphics_buffer_width(id, width);
	}

	int setGraphicsBufferHeight(int height)
	{
		return Cmiss_scene_viewer_set_graphics_buffer_height(id, height);
	}

	int setViewportSize(int width, int height)
	{
		return Cmiss_scene_viewer_set_viewport_size(id, width, height);
	}

	SceneViewerInput getInput()
	{
		return SceneViewerInput(Cmiss_scene_viewer_get_input(id));
	}

	int setInput(SceneViewerInput input)
	{
		return Cmiss_scene_viewer_input_viewport_transform(id, input.getId());
	}

	int getLookatParameters(double *eyex,double *eyey,double *eyez,
		double *lookatx,double *lookaty,double *lookatz,
		double *upx,double *upy,double *upz)
	{
		return Cmiss_scene_viewer_get_lookat_parameters(id, eyex, eyey, eyez,
			lookatx, lookaty, lookatz,
			upx, upy, upz);
	}

	int getViewingVolume(double *left,double *right,double *bottom,double *top,
		double *near_plane, double *far_plane)
	{
		return Cmiss_scene_viewer_get_viewing_volume(id, left, right, bottom, top,
			near_plane, far_plane);
	}

	int setBackgroundColourRGB(double red, double green, double blue)
	{
		return Cmiss_scene_viewer_set_background_colour_r_g_b(id, red, green, blue);
	}

	int viewAll()
	{
		return Cmiss_scene_viewer_view_all(id);
	}

};

class SceneViewerModule
{
protected:
	Cmiss_scene_viewer_module_id id;

public:

	SceneViewerModule() : id(0)
	{  }

	// takes ownership of C-style region reference
	SceneViewerModule(Cmiss_scene_viewer_module_id in_scene_viewer_module_id) :
		id(in_scene_viewer_module_id)
	{  }

	SceneViewerModule(const SceneViewerModule& scene_viewer_module) :
		id(Cmiss_scene_viewer_module_access(scene_viewer_module.id))
	{  }

	SceneViewerModule& operator=(const SceneViewerModule& scene_viewer_module)
	{
		Cmiss_scene_viewer_module_id temp_id = Cmiss_scene_viewer_module_access(scene_viewer_module.id);
		if (0 != id)
		{
			Cmiss_scene_viewer_module_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~SceneViewerModule()
	{
		if (0 != id)
		{
			Cmiss_scene_viewer_module_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_scene_viewer_module_id getId()
	{
		return id;
	}

	SceneViewer createSceneViewer(SceneViewer::BufferingMode buffering_mode, SceneViewer::StereoMode stereo_mode)
	{
		return SceneViewer(Cmiss_scene_viewer_module_create_scene_viewer(id,
			static_cast<Cmiss_scene_viewer_buffering_mode>(buffering_mode),
			static_cast<Cmiss_scene_viewer_stereo_mode>(stereo_mode)));
	}

};

}  // namespace zinc

#endif
<commit_msg>Renamed APIs SceneViewer::getGraphicsFilter to SceneViewer::getFilter. https://tracker.physiomeproject.org/show_bug.cgi?id=3554<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is libZinc.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef __SCENE_VIEWER_HPP__
#define __SCENE_VIEWER_HPP__

#include "zinc/sceneviewer.h"
#include "zinc/sceneviewerinput.h"
#include "zinc/scene.hpp"
#include "zinc/graphicsfilter.hpp"

namespace zinc
{

class SceneViewerInput
{
protected:
	Cmiss_scene_viewer_input_id id;

public:
	enum InputEventType
	{
		INPUT_EVENT_TYPE_INVALID = CMISS_SCENE_VIEWER_INPUT_INVALID,
		INPUT_EVENT_TYPE_MOTION_NOTIFY = CMISS_SCENE_VIEWER_INPUT_MOTION_NOTIFY,
		INPUT_EVENT_TYPE_BUTTON_PRESS = CMISS_SCENE_VIEWER_INPUT_BUTTON_PRESS,
		INPUT_EVENT_TYPE_BUTTON_RELEASE = CMISS_SCENE_VIEWER_INPUT_BUTTON_RELEASE,
		INPUT_EVENT_TYPE_KEY_PRESS = CMISS_SCENE_VIEWER_INPUT_KEY_PRESS,
		INPUT_EVENT_TYPE_KEY_RELEASE = CMISS_SCENE_VIEWER_INPUT_KEY_RELEASE
	};

	enum InputButtonType
	{
		INPUT_BUTTON_INVALID = CMISS_SCENE_VIEWER_INPUT_BUTTON_INVALID,
		INPUT_BUTTON_LEFT = CMISS_SCENE_VIEWER_INPUT_BUTTON_LEFT,
		INPUT_BUTTON_MIDDLE = CMISS_SCENE_VIEWER_INPUT_BUTTON_MIDDLE,
		INPUT_BUTTON_RIGHT = CMISS_SCENE_VIEWER_INPUT_BUTTON_RIGHT,
		INPUT_BUTTON_SCROLL_DOWN = CMISS_SCENE_VIEWER_INPUT_BUTTON_SCROLL_DOWN,
		INPUT_BUTTON_SCROLL_UP = CMISS_SCENE_VIEWER_INPUT_BUTTON_SCROLL_UP
	};

	SceneViewerInput() : id(0)
	{  }

	// takes ownership of C-style region reference
	explicit SceneViewerInput(Cmiss_scene_viewer_input_id in_scene_viewer_input_id) :
		id(in_scene_viewer_input_id)
	{  }

	SceneViewerInput(const SceneViewerInput& scene_viewer_input) :
		id(Cmiss_scene_viewer_input_access(scene_viewer_input.id))
	{  }

	SceneViewerInput& operator=(const SceneViewerInput& scene_viewer_input)
	{
		Cmiss_scene_viewer_input_id temp_id = Cmiss_scene_viewer_input_access(scene_viewer_input.id);
		if (0 != id)
		{
			Cmiss_scene_viewer_input_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~SceneViewerInput()
	{
		if (0 != id)
		{
			Cmiss_scene_viewer_input_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_scene_viewer_input_id getId()
	{
		return id;
	}

	int setPosition(int x, int y)
	{
		return Cmiss_scene_viewer_input_set_position(id, x, y);
	}

	int setButtonNumber(int number)
	{
		return Cmiss_scene_viewer_input_set_button_number(id, number);
	}

	int setButton(InputButtonType button)
	{
		return Cmiss_scene_viewer_input_set_button(id, static_cast<Cmiss_scene_viewer_input_button_type>(button));
	}

	int setType(InputEventType type)
	{
		return Cmiss_scene_viewer_input_set_type(id, static_cast<Cmiss_scene_viewer_input_event_type>(type));
	}

};

class SceneViewer
{
protected:
	Cmiss_scene_viewer_id id;

public:

	enum BufferingMode
	{
		BUFFERING_MODE_ANY = CMISS_SCENE_VIEWER_BUFFERING_ANY_MODE,
		BUFFERING_MODE_SINGLE = CMISS_SCENE_VIEWER_BUFFERING_SINGLE,
		BUFFERING_MODE_DOUBLE = CMISS_SCENE_VIEWER_BUFFERING_DOUBLE,
		BUFFERING_MODE_RENDER_OFFSCREEN_AND_COPY = CMISS_SCENE_VIEWER_BUFFERING_RENDER_OFFSCREEN_AND_COPY,
		BUFFERING_MODE_RENDER_OFFSCREEN_AND_BLEND = CMISS_SCENE_VIEWER_BUFFERING_RENDER_OFFSCREEN_AND_BLEND
	};

	enum StereoMode
	{
		STEREO_MODE_ANY = CMISS_SCENE_VIEWER_STEREO_ANY_MODE,
		STEREO_MODE_MONO = CMISS_SCENE_VIEWER_STEREO_MONO,
		STEREO_MODE_STEREO = CMISS_SCENE_VIEWER_STEREO_STEREO
	};

	SceneViewer() : id(0)
	{  }

	// takes ownership of C-style region reference
	explicit SceneViewer(Cmiss_scene_viewer_id in_scene_viewer_id) :
		id(in_scene_viewer_id)
	{  }

	SceneViewer(const SceneViewer& scene_viewer_module) :
		id(Cmiss_scene_viewer_access(scene_viewer_module.id))
	{  }

	SceneViewer& operator=(const SceneViewer& scene_viewer)
	{
		Cmiss_scene_viewer_id temp_id = Cmiss_scene_viewer_access(scene_viewer.id);
		if (0 != id)
		{
			Cmiss_scene_viewer_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~SceneViewer()
	{
		if (0 != id)
		{
			Cmiss_scene_viewer_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_scene_viewer_id getId()
	{
		return id;
	}

	int renderScene()
	{
		return Cmiss_scene_viewer_render_scene(id);
	}

	int setScene(Scene scene)
	{
		return Cmiss_scene_viewer_set_scene(id, scene.getId());
	}

	Scene getScene()
	{
		return Scene(Cmiss_scene_viewer_get_scene(id));
	}

	int setFilter(GraphicsFilter graphicsFilter)
	{
		return Cmiss_scene_viewer_set_filter(id, graphicsFilter.getId());
	}

	GraphicsFilter getFilter()
	{
		return GraphicsFilter(Cmiss_scene_viewer_get_filter(id));
	}

	int setGraphicsBufferWidth(int width)
	{
		return Cmiss_scene_viewer_set_graphics_buffer_width(id, width);
	}

	int setGraphicsBufferHeight(int height)
	{
		return Cmiss_scene_viewer_set_graphics_buffer_height(id, height);
	}

	int setViewportSize(int width, int height)
	{
		return Cmiss_scene_viewer_set_viewport_size(id, width, height);
	}

	SceneViewerInput getInput()
	{
		return SceneViewerInput(Cmiss_scene_viewer_get_input(id));
	}

	int setInput(SceneViewerInput input)
	{
		return Cmiss_scene_viewer_input_viewport_transform(id, input.getId());
	}

	int getLookatParameters(double *eyex,double *eyey,double *eyez,
		double *lookatx,double *lookaty,double *lookatz,
		double *upx,double *upy,double *upz)
	{
		return Cmiss_scene_viewer_get_lookat_parameters(id, eyex, eyey, eyez,
			lookatx, lookaty, lookatz,
			upx, upy, upz);
	}

	int getViewingVolume(double *left,double *right,double *bottom,double *top,
		double *near_plane, double *far_plane)
	{
		return Cmiss_scene_viewer_get_viewing_volume(id, left, right, bottom, top,
			near_plane, far_plane);
	}

	int setBackgroundColourRGB(double red, double green, double blue)
	{
		return Cmiss_scene_viewer_set_background_colour_r_g_b(id, red, green, blue);
	}

	int viewAll()
	{
		return Cmiss_scene_viewer_view_all(id);
	}

};

class SceneViewerModule
{
protected:
	Cmiss_scene_viewer_module_id id;

public:

	SceneViewerModule() : id(0)
	{  }

	// takes ownership of C-style region reference
	SceneViewerModule(Cmiss_scene_viewer_module_id in_scene_viewer_module_id) :
		id(in_scene_viewer_module_id)
	{  }

	SceneViewerModule(const SceneViewerModule& scene_viewer_module) :
		id(Cmiss_scene_viewer_module_access(scene_viewer_module.id))
	{  }

	SceneViewerModule& operator=(const SceneViewerModule& scene_viewer_module)
	{
		Cmiss_scene_viewer_module_id temp_id = Cmiss_scene_viewer_module_access(scene_viewer_module.id);
		if (0 != id)
		{
			Cmiss_scene_viewer_module_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~SceneViewerModule()
	{
		if (0 != id)
		{
			Cmiss_scene_viewer_module_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_scene_viewer_module_id getId()
	{
		return id;
	}

	SceneViewer createSceneViewer(SceneViewer::BufferingMode buffering_mode, SceneViewer::StereoMode stereo_mode)
	{
		return SceneViewer(Cmiss_scene_viewer_module_create_scene_viewer(id,
			static_cast<Cmiss_scene_viewer_buffering_mode>(buffering_mode),
			static_cast<Cmiss_scene_viewer_stereo_mode>(stereo_mode)));
	}

};

}  // namespace zinc

#endif
<|endoftext|>