<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * This file is part of the libvisio project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <vector>
#include <string>
#include <algorithm> // std::count
#include <cstdarg>
#include <cstdio>
#include "VSDInternalStream.h"
#include "libvisio_utils.h"

uint8_t libvisio::readU8(librevenge::RVNGInputStream *input)
{
  if (!input || input->isEnd())
  {
    VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint8_t))
    return *(uint8_t const *)(p);
  VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

uint16_t libvisio::readU16(librevenge::RVNGInputStream *input)
{
  if (!input || input->isEnd())
  {
    VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint16_t))
    return (uint16_t)p[0]|((uint16_t)p[1]<<8);
  VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

int16_t libvisio::readS16(librevenge::RVNGInputStream *input)
{
  return (int16_t)readU16(input);
}

uint32_t libvisio::readU32(librevenge::RVNGInputStream *input)
{
  if (!input || input->isEnd())
  {
    VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint32_t))
    return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);
  VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

int32_t libvisio::readS32(librevenge::RVNGInputStream *input)
{
  return (int32_t)readU32(input);
}

uint64_t libvisio::readU64(librevenge::RVNGInputStream *input)
{
  if (!input || input->isEnd())
  {
    VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint64_t))
    return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56);
  VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

double libvisio::readDouble(librevenge::RVNGInputStream *input)
{
  union
  {
    uint64_t u;
    double d;
  } tmpUnion;

  tmpUnion.u = readU64(input);

  return tmpUnion.d;
}

const librevenge::RVNGString libvisio::getColourString(const Colour &c)
{
  librevenge::RVNGString sColour;
  sColour.sprintf("#%.2x%.2x%.2x", c.r, c.g, c.b);
  return sColour;
}

unsigned long libvisio::getRemainingLength(librevenge::RVNGInputStream *const input)
{
  if (!input)
    throw EndOfStreamException();

  const unsigned long begin = (unsigned long) input->tell();
  unsigned long end = begin;

  if (0 == input->seek(0, librevenge::RVNG_SEEK_END))
  {
    end = (unsigned long) input->tell();
  }
  else
  {
    // librevenge::RVNG_SEEK_END does not work. Use the harder way.
    while (!input->isEnd())
    {
      readU8(input);
      ++end;
    }
  }

  input->seek(begin, librevenge::RVNG_SEEK_SET);

  return end - begin;
}

void libvisio::appendUCS4(librevenge::RVNGString &text, UChar32 ucs4Character)
{
  // Convert carriage returns to new line characters
  if (ucs4Character == (UChar32) 0x0d || ucs4Character == (UChar32) 0x0e)
    ucs4Character = (UChar32) '\n';

  unsigned char outbuf[U8_MAX_LENGTH+1];
  int i = 0;
  U8_APPEND_UNSAFE(&outbuf[0], i, ucs4Character);
  outbuf[i] = 0;

  text.append((char *)outbuf);
}

void libvisio::debugPrint(const char *format, ...)
{
  va_list args;
  va_start(args, format);
  std::vfprintf(stderr, format, args);
  va_end(args);
}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>cid#1419957 rewrite to avoid coverity warning<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * This file is part of the libvisio project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <vector>
#include <string>
#include <algorithm> // std::count
#include <cstdarg>
#include <cstdio>
#include "VSDInternalStream.h"
#include "libvisio_utils.h"

uint8_t libvisio::readU8(librevenge::RVNGInputStream *input)
{
  if (!input || input->isEnd())
  {
    VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint8_t))
    return *(uint8_t const *)(p);
  VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

uint16_t libvisio::readU16(librevenge::RVNGInputStream *input)
{
  if (!input || input->isEnd())
  {
    VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint16_t))
    return (uint16_t)p[0]|((uint16_t)p[1]<<8);
  VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

int16_t libvisio::readS16(librevenge::RVNGInputStream *input)
{
  return (int16_t)readU16(input);
}

uint32_t libvisio::readU32(librevenge::RVNGInputStream *input)
{
  if (!input || input->isEnd())
  {
    VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint32_t))
    return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);
  VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

int32_t libvisio::readS32(librevenge::RVNGInputStream *input)
{
  return (int32_t)readU32(input);
}

uint64_t libvisio::readU64(librevenge::RVNGInputStream *input)
{
  if (!input || input->isEnd())
  {
    VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
    throw EndOfStreamException();
  }
  unsigned long numBytesRead;
  uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead);

  if (p && numBytesRead == sizeof(uint64_t))
    return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56);
  VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
  throw EndOfStreamException();
}

double libvisio::readDouble(librevenge::RVNGInputStream *input)
{
  union
  {
    uint64_t u;
    double d;
  } tmpUnion;

  tmpUnion.u = readU64(input);

  return tmpUnion.d;
}

const librevenge::RVNGString libvisio::getColourString(const Colour &c)
{
  librevenge::RVNGString sColour;
  sColour.sprintf("#%.2x%.2x%.2x", c.r, c.g, c.b);
  return sColour;
}

unsigned long libvisio::getRemainingLength(librevenge::RVNGInputStream *const input)
{
  if (!input)
    throw EndOfStreamException();

  const long begin = input->tell();

  if (input->seek(0, librevenge::RVNG_SEEK_END) != 0)
  {
    // librevenge::RVNG_SEEK_END does not work. Use the harder way.
    while (!input->isEnd())
      readU8(input);
  }
  const long end = input->tell();

  input->seek(begin, librevenge::RVNG_SEEK_SET);

  if (end < begin)
    throw EndOfStreamException();
  return static_cast<unsigned long>(end - begin);
}

void libvisio::appendUCS4(librevenge::RVNGString &text, UChar32 ucs4Character)
{
  // Convert carriage returns to new line characters
  if (ucs4Character == (UChar32) 0x0d || ucs4Character == (UChar32) 0x0e)
    ucs4Character = (UChar32) '\n';

  unsigned char outbuf[U8_MAX_LENGTH+1];
  int i = 0;
  U8_APPEND_UNSAFE(&outbuf[0], i, ucs4Character);
  outbuf[i] = 0;

  text.append((char *)outbuf);
}

void libvisio::debugPrint(const char *format, ...)
{
  va_list args;
  va_start(args, format);
  std::vfprintf(stderr, format, args);
  va_end(args);
}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>


<commit_before>
#include <cctype>
#include <cstring>

#include "Word.h"

Word& Word::operator=(const String& other)
{
  (String&)*this = other;
  return *this;
}

bool Word::operator==(const Word& other) const
{
  return *(String*)this == other;
}

bool Word::operator!=(const Word& other) const
{
  return *(String*)this != other;
}

void Word::split(const String& text, List<Word>& words)
{
  const char* str = text.getData();
  for(;;)
  {
    while(isspace(*str))
      ++str;
    if(!*str)
      break;
    if(*str == '"')
    {
      ++str;
      const char* end = str;
      for(; *end; ++end)
        if(*end == '\\' && end[1] == '"')
          ++end;
        else if(*end == '"')
          break;
      if(end > str) // TODO: read escaped spaces as ordinary spaces?
        words.append(Word(text.substr(str - text.getData(), end - str), true));
      str = end;
      if(*str)
        ++str; // skip closing '"'
    }
    else
    {
      const char* end = str;
      for(; *end; ++end)
        if(isspace(*end))
          break;
      // TODO: read escaped spaces as ordinary spaces
      words.append(Word(text.substr(str - text.getData(), end - str), false));
      str = end;
    }
  }
}

void Word::append(const List<Word>& words, String& text)
{
  if(words.isEmpty())
    return;

  int totalLen = words.getSize() * 3;
  for(const List<Word>::Node* i = words.getFirst(); i; i = i->getNext())
    totalLen += i->data.getLength();
  text.setCapacity(totalLen + 16);

  const List<Word>::Node* i = words.getFirst();
  const List<Word>::Node* previousWord = i;
  i->data.appendTo(text);
  for(i = i->getNext(); i; i = i->getNext())
  {
    text.append(/*previousWord->data.terminated ? '\n' : */' ');
    i->data.appendTo(text);
    previousWord = i;
  }
}

void Word::appendTo(String& text) const
{
  if(quoted)
  {
    text.append('"');
    text.append(*this);
    text.append('"');
  }
  else // TODO: escape spaces using blackslashes
    text.append(*this);
}

void Word::splitLines(const String& text, List<Word>& words)
{
  const char* str = text.getData();
  for(;;)
  {
    const char* end = str;
    for(; *end; ++end)
      if(*end == '\n' || *end == '\r')
        break;
    // TODO: read escaped spaces as ordinary spaces
    Word& word = words.append(Word(text.substr(str - text.getData(), end - str), false));
    str = end;
    if(*str)
    {
      if(*str == '\r' && str[1] == '\n')
        str += 2;
      else
        ++str;
    }
    else
      break;
  }
}
<commit_msg>Remove warning<commit_after>
#include <cctype>
#include <cstring>

#include "Word.h"

Word& Word::operator=(const String& other)
{
  (String&)*this = other;
  return *this;
}

bool Word::operator==(const Word& other) const
{
  return *(String*)this == other;
}

bool Word::operator!=(const Word& other) const
{
  return *(String*)this != other;
}

void Word::split(const String& text, List<Word>& words)
{
  const char* str = text.getData();
  for(;;)
  {
    while(isspace(*str))
      ++str;
    if(!*str)
      break;
    if(*str == '"')
    {
      ++str;
      const char* end = str;
      for(; *end; ++end)
        if(*end == '\\' && end[1] == '"')
          ++end;
        else if(*end == '"')
          break;
      if(end > str) // TODO: read escaped spaces as ordinary spaces?
        words.append(Word(text.substr(str - text.getData(), end - str), true));
      str = end;
      if(*str)
        ++str; // skip closing '"'
    }
    else
    {
      const char* end = str;
      for(; *end; ++end)
        if(isspace(*end))
          break;
      // TODO: read escaped spaces as ordinary spaces
      words.append(Word(text.substr(str - text.getData(), end - str), false));
      str = end;
    }
  }
}

void Word::append(const List<Word>& words, String& text)
{
  if(words.isEmpty())
    return;

  int totalLen = words.getSize() * 3;
  for(const List<Word>::Node* i = words.getFirst(); i; i = i->getNext())
    totalLen += i->data.getLength();
  text.setCapacity(totalLen + 16);

  const List<Word>::Node* i = words.getFirst();
  const List<Word>::Node* previousWord = i;
  i->data.appendTo(text);
  for(i = i->getNext(); i; i = i->getNext())
  {
    text.append(/*previousWord->data.terminated ? '\n' : */' ');
    i->data.appendTo(text);
    previousWord = i;
  }
}

void Word::appendTo(String& text) const
{
  if(quoted)
  {
    text.append('"');
    text.append(*this);
    text.append('"');
  }
  else // TODO: escape spaces using blackslashes
    text.append(*this);
}

void Word::splitLines(const String& text, List<Word>& words)
{
  const char* str = text.getData();
  for(;;)
  {
    const char* end = str;
    for(; *end; ++end)
      if(*end == '\n' || *end == '\r')
        break;
    // TODO: read escaped spaces as ordinary spaces
    words.append(Word(text.substr(str - text.getData(), end - str), false));
    str = end;
    if(*str)
    {
      if(*str == '\r' && str[1] == '\n')
        str += 2;
      else
        ++str;
    }
    else
      break;
  }
}
<|endoftext|>


<commit_before>#include "qmdatabase.h"

QMDatabase::onCreate()
{
   // table for frames
    Exec("CREATE TABLE frames ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "time REAL NOT NULL,"
        "step INT NOT NULL,"
        "box11 REAL NOT NULL,"
        "box12 REAL NOT NULL,"
        "box13 REAL NOT NULL,"
        "box21 REAL NOT NULL,"
        "box22 REAL NOT NULL,"
        "box23 REAL NOT NULL,"
        "box31 REAL NOT NULL,"
        "box32 REAL NOT NULL,"
        "box33 REAL NOT NULL)");

    // table for molecules
    Exec("CREATE TABLE molecules ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "id INT NOT NULL,"
        "name TEXT NOT NULL,"
        "frame INT NOT NULL)");

    // delete molecules if frame is deleted
    Exec("CREATE TRIGGER trig_delete_frame BEFOR DELETE ON frames "
            "FOR EACH ROW BEGIN "
            "DELETE FROM molecules WHERE molecules.frame = OLD._id;"
            " END");

    // table for conjugated segments
    Exec("CREATE TABLE segments ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "id INT NOT NULL,"
        "name TEXT NOT NULL,"
        "occ REAL NOT NULL)");

    // additional properties of conjugated segments
    Exec("CREATE TABLE segment_properties ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "segmentid INTEGER NOT NULL,"
        "key TEXT NOT NULL,"
        "value REAL NOT NULL)");

        // delete molecules if frame is deleted
    Exec("CREATE TRIGGER trig_delete_frame BEFOR DELETE ON frames "
            "FOR EACH ROW BEGIN "
            "DELETE FROM molecules WHERE molecules.frame = OLD._id;"
            " END");

    // table for rigid fragments
    Exec("CREATE TABLE fragments ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "id INT NOT NULL,"
        "name TEXT NOT NULL,"
        "symmetry INT NOT NULL,"
        "type TEXT NOT NULL,"
        "resnr INT NOT NULL,"
        "mass REAL NOT NULL,"
        "charge REAL NOT NULL,"
        "molid INT NOT NULL,"
        "segment_id INT NOT NULL,"
        "segment_index INT NOT NULL,"
        "pos_x REAL NOT NULL,"
        "pos_y REAL NOT NULL,"
        "pos_z REAL NOT NULL,"
        "u_x REAL NOT NULL,"
        "u_y REAL NOT NULL,"
        "u_z REAL NOT NULL,"
        "v_x REAL NOT NULL,"
        "v_y REAL NOT NULL,"
        "v_z REAL NOT NULL)");

    // additional properties of rigid fragments
    Exec("CREATE TABLE fragment_properties ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "fragmenttid INTEGER NOT NULL,"
        "key TEXT NOT NULL,"
        "value REAL NOT NULL)");

    // table for pairs
    Exec("CREATE TABLE pairs ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "segment1 INT NOT NULL,"
        "segment2 INT NOT NULL,"
        "rate12 REAL NOT NULL,"
        "rate21 REAL NOT NULL,"
        "r_x REAL NOT NULL,"
        "r_y REAL NOT NULL,"
        "r_z REAL NOT NULL)");

    // additional properties of pairs
    Exec("CREATE TABLE pair_properties ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "pairid INTEGER NOT NULL,"
        "key TEXT NOT NULL,"
        "value REAL NOT NULL)");
}
<commit_msg>some more triggers<commit_after>#include "qmdatabase.h"

void QMDatabase::onCreate()
{
   // table for frames
    Exec("CREATE TABLE frames ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "time REAL NOT NULL,"
        "step INT NOT NULL,"
        "box11 REAL NOT NULL,"
        "box12 REAL NOT NULL,"
        "box13 REAL NOT NULL,"
        "box21 REAL NOT NULL,"
        "box22 REAL NOT NULL,"
        "box23 REAL NOT NULL,"
        "box31 REAL NOT NULL,"
        "box32 REAL NOT NULL,"
        "box33 REAL NOT NULL)");

    // table for molecules
    Exec("CREATE TABLE molecules ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "id INT NOT NULL,"
        "name TEXT NOT NULL,"
        "frame INT NOT NULL)");

    // table for conjugated segments
    Exec("CREATE TABLE segments ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "id INT NOT NULL,"
        "name TEXT NOT NULL,"
        "occ REAL NOT NULL)");

    // additional properties of conjugated segments
    Exec("CREATE TABLE segment_properties ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "segment INTEGER NOT NULL,"
        "key TEXT NOT NULL,"
        "value REAL NOT NULL)");

    // table for rigid fragments
    Exec("CREATE TABLE fragments ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "id INT NOT NULL,"
        "name TEXT NOT NULL,"
        "symmetry INT NOT NULL,"
        "type TEXT NOT NULL,"
        "resnr INT NOT NULL,"
        "mass REAL NOT NULL,"
        "charge REAL NOT NULL,"
        "molid INT NOT NULL,"
        "segment_id INT NOT NULL,"
        "segment_index INT NOT NULL,"
        "pos_x REAL NOT NULL,"
        "pos_y REAL NOT NULL,"
        "pos_z REAL NOT NULL,"
        "u_x REAL NOT NULL,"
        "u_y REAL NOT NULL,"
        "u_z REAL NOT NULL,"
        "v_x REAL NOT NULL,"
        "v_y REAL NOT NULL,"
        "v_z REAL NOT NULL)");

    // additional properties of rigid fragments
    Exec("CREATE TABLE fragment_properties ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "fragmenttid INTEGER NOT NULL,"
        "key TEXT NOT NULL,"
        "value REAL NOT NULL)");

    // table for pairs
    Exec("CREATE TABLE pairs ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "segment1 INT NOT NULL,"
        "segment2 INT NOT NULL,"
        "rate12 REAL NOT NULL,"
        "rate21 REAL NOT NULL,"
        "r_x REAL NOT NULL,"
        "r_y REAL NOT NULL,"
        "r_z REAL NOT NULL)");

    // additional properties of pairs
    Exec("CREATE TABLE pair_properties ("
        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "pair INTEGER NOT NULL,"
        "key TEXT NOT NULL,"
        "value REAL NOT NULL)");

    // delete molecules if frame is deleted
    Exec("CREATE TRIGGER trig_delete_frame BEFOR DELETE ON frames "
            "FOR EACH ROW BEGIN "
            "DELETE FROM molecules WHERE molecules.frame = OLD._id;"
            " END");

    // delete segment properties + fragments + pairs if segment is deleted
    Exec("CREATE TRIGGER trig_delete_segment BEFOR DELETE ON segments "
            "FOR EACH ROW BEGIN "
            "DELETE FROM segment_properties WHERE segment_properties=segmentid.segment = OLD._id;"
            "DELETE FROM fragments WHERE segment_id=segmentid.frame = OLD._id;"
            "DELETE FROM pairs WHERE pairs.segment1 = OLD._id OR pairs.segment2 = OLD._id;"
            " END");

    // delete fragment properties if fragment is deleted
    Exec("CREATE TRIGGER trig_delete_fragment BEFOR DELETE ON fragments "
            "FOR EACH ROW BEGIN "
            "DELETE FROM fragment_properties WHERE fragment_properties.fragment = OLD._id;"
            "DELETE FROM fragments WHERE segment_id=segmentid.frame = OLD._id;"
            " END");

    // delete pair property if property is deleted
    Exec("CREATE TRIGGER trig_delete_pair BEFOR DELETE ON pairs "
            "FOR EACH ROW BEGIN "
            "DELETE FROM pair_properties WHERE pair_properties.pair = OLD._id;"
            " END");

}
<|endoftext|>


<commit_before>#include "standard_entity_validators.h"
#include "halley/entity/entity.h"
#include "halley/entity/world.h"

#define DONT_INCLUDE_HALLEY_HPP
#include "component_editor_context.h"
#include "halley/entity/components/transform_2d_component.h"

using namespace Halley;

std::vector<IEntityValidator::Result> TransformEntityValidator::validateEntity(EntityValidator& validator, EntityData& entityData)
{
	std::vector<Result> result;

	const auto entity = validator.getWorld().findEntity(entityData.getInstanceUUID());
	if (entity->isValid()) {
		const bool hasTransform = entity->hasComponent<Transform2DComponent>();

		if (!hasTransform) {
			for (auto c: entity->getChildren()) {
				if (c.hasComponent<Transform2DComponent>()) {
					result.emplace_back("Entity has no Transform2D component, but some of its children do.", Action("Add Component", AddComponentValidatorActionHandler::makeAction("Transform2D")));
				}
			}
		}
	}

	return result;
}

bool AddComponentValidatorActionHandler::canHandle(const ConfigNode& actionData)
{
	return actionData["action"].asString() == "addComponent" && actionData.hasKey("component");
}

void AddComponentValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)
{
	const auto compType = actionData["component"].asString();
	entityEditor.addComponent(compType, ConfigNode::MapType());
}

ConfigNode AddComponentValidatorActionHandler::makeAction(String componentName)
{
	ConfigNode::MapType action;
	action["action"] = "addComponent";
	action["component"] = std::move(componentName);
	return action;
}

bool ModifyFieldsValidatorActionHandler::canHandle(const ConfigNode& actionData)
{
	return actionData["action"].asString() == "modifyField" || actionData["action"].asString() == "modifyFields";
}

void ModifyFieldsValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)
{
	if (actionData["action"].asString() == "modifyField") {
		applyEntry(entityEditor, entityData, actionData);
	} else if (actionData["action"].asString() == "modifyFields") {
		for (const auto& entry: actionData["entries"].asSequence()) {
			applyEntry(entityEditor, entityData, entry);
		}
	}
}

ConfigNode ModifyFieldsValidatorActionHandler::makeAction(String componentName, String fieldName, ConfigNode fieldData)
{
	ConfigNode::MapType result;

	result["action"] = "modifyField";
	result["component"] = componentName;
	result["field"] = fieldName;
	result["data"] = fieldData;

	return result;
}

void ModifyFieldsValidatorActionHandler::applyEntry(IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& entry)
{
	const auto component = entry["component"].asString();
	const auto field = entry["field"].asString();

	bool found = false;
	for (auto& comp: entityData.getComponents()) {
		if (comp.first == component) {
			auto& compData = comp.second.asMap();
			compData[field] = ConfigNode(entry["data"]);
			found = true;
			break;
		}
	}

	if (found) {
		entityEditor.onFieldChangedByGizmo(component, field);
	}
}
<commit_msg>Some missing moves<commit_after>#include "standard_entity_validators.h"
#include "halley/entity/entity.h"
#include "halley/entity/world.h"

#define DONT_INCLUDE_HALLEY_HPP
#include "component_editor_context.h"
#include "halley/entity/components/transform_2d_component.h"

using namespace Halley;

std::vector<IEntityValidator::Result> TransformEntityValidator::validateEntity(EntityValidator& validator, EntityData& entityData)
{
	std::vector<Result> result;

	const auto entity = validator.getWorld().findEntity(entityData.getInstanceUUID());
	if (entity->isValid()) {
		const bool hasTransform = entity->hasComponent<Transform2DComponent>();

		if (!hasTransform) {
			for (auto c: entity->getChildren()) {
				if (c.hasComponent<Transform2DComponent>()) {
					result.emplace_back("Entity has no Transform2D component, but some of its children do.", Action("Add Component", AddComponentValidatorActionHandler::makeAction("Transform2D")));
				}
			}
		}
	}

	return result;
}

bool AddComponentValidatorActionHandler::canHandle(const ConfigNode& actionData)
{
	return actionData["action"].asString() == "addComponent" && actionData.hasKey("component");
}

void AddComponentValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)
{
	const auto compType = actionData["component"].asString();
	entityEditor.addComponent(compType, ConfigNode::MapType());
}

ConfigNode AddComponentValidatorActionHandler::makeAction(String componentName)
{
	ConfigNode::MapType action;
	action["action"] = "addComponent";
	action["component"] = std::move(componentName);
	return action;
}

bool ModifyFieldsValidatorActionHandler::canHandle(const ConfigNode& actionData)
{
	return actionData["action"].asString() == "modifyField" || actionData["action"].asString() == "modifyFields";
}

void ModifyFieldsValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)
{
	if (actionData["action"].asString() == "modifyField") {
		applyEntry(entityEditor, entityData, actionData);
	} else if (actionData["action"].asString() == "modifyFields") {
		for (const auto& entry: actionData["entries"].asSequence()) {
			applyEntry(entityEditor, entityData, entry);
		}
	}
}

ConfigNode ModifyFieldsValidatorActionHandler::makeAction(String componentName, String fieldName, ConfigNode fieldData)
{
	ConfigNode::MapType result;

	result["action"] = "modifyField";
	result["component"] = std::move(componentName);
	result["field"] = std::move(fieldName);
	result["data"] = std::move(fieldData);

	return result;
}

void ModifyFieldsValidatorActionHandler::applyEntry(IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& entry)
{
	const auto component = entry["component"].asString();
	const auto field = entry["field"].asString();

	bool found = false;
	for (auto& comp: entityData.getComponents()) {
		if (comp.first == component) {
			auto& compData = comp.second.asMap();
			compData[field] = ConfigNode(entry["data"]);
			found = true;
			break;
		}
	}

	if (found) {
		entityEditor.onFieldChangedByGizmo(component, field);
	}
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "NetworkClient.hpp"

//fToServerStc NetworkClient::toServerData;

NetworkClient::NetworkClient() : NetworkWorker()
{
	tryToConnect = true;
	clientConnected = false;

	myType = CLIENT;
}

int NetworkClient::initialize(int port)
{
	last = now = AnnEngine::Instance()->getTimeFromStartUp();
	return 0;
}
void NetworkClient::update(){
	AnnDebug() << "client update";
	now = AnnEngine::Instance()->getTimeFromStartUp();
	float frameTime = now - last;
	last = now;
	communicate(frameTime);
}

// --- Do network communications ---
void NetworkClient::communicate(float frameTime)
{
	AnnDebug() << "Com";
	if(clientConnected)
		getInfoFromServer(); // Get game state from server
	// Calculate elapsed time for network communications
	/*netTime += frameTime;
	if(netTime < netNS::NET_TIMER) // if not time to communicate*/
		//return;
	if(tryToConnect)
		connectToServer(); // Attempt to connect to game server
	else if(clientConnected)
	{
		AnnDebug() << "Should transmit data here";
		checkNetworkTimeout(); // check for disconnect from server
		sendInfoToServer(); //
	}
	netTime -= netNS::NET_TIMER;

}

void NetworkClient::connectToServer()
{
	AnnDebug() << "Call connect to server..." ;
	static int step = 0;
    static float waitTime;  // seconds we have waited for a response from server
    int size;
    int newPort;
    std::string str;
    std::stringstream ss;

    if(clientConnected)     // if connected
    {
        tryToConnect = false;
        AnnDebug() << "Currently connected";
        return;
    }

        AnnDebug() << "----- Vr AirHockey Client -----";

		switch (step)
		{
		case 0:

		newPort = config.port;
        if(newPort == 0)
            newPort = netNS::DEFAULT_PORT;
        if(newPort > netNS::MIN_PORT && newPort < 65536)
        {
            port = newPort;
        }
        else
        AnnDebug() << "Invalid port number";
		strcpy(remoteIP, config.serverAddress.c_str());
        error = net.createClient(remoteIP, port, netNS::UDP);
        if(error != netNS::NET_OK)          // if error
        {
            AnnDebug() << net.getError(error);    // display error message
            tryToConnect = false;
            return;
        }
        // send request to join the server
        AnnDebug() << "Attempting to connect with server."; // display message
        toServerData.playerN = 255;        // playerN=255 is request to join
        size = sizeof(toServerData);
        AnnDebug() << "'Request to join' sent to server.";
        error = net.sendData((char*) &toServerData, size, remoteIP, port);
        AnnDebug() << net.getError(error);
        waitTime = 0;

		step = 4;
        break;

    case 4:
        waitTime+=netTime;      // add time since last call to connect
        // if we timed out with no reponse to our request to join
        if (waitTime > CONNECT_TIMEOUT)
        {
            AnnDebug() << "'Request to join' timed out.";
            //tryToConnect = false;
            return;
        }
        // read ConnectResponse from server
        size = sizeof(connectResponse);
        error = net.readData((char*)&connectResponse, size, remoteIP, remotePort);
        if (error == netNS::NET_OK)     // if read was OK
        {
            if(size == 0)   // if no data received
                return;
            // if the server sent back the proper ID then we are connected
            if (strcmp(connectResponse.response, netNS::SERVER_ID) == 0)
            {
                if (connectResponse.number < MAX_CLIENT)   // if valid player number
                {
                    playerN = connectResponse.number;       // set my player number
                    ss << "Connected as player number: " << playerN;
                    AnnDebug() << ss.str();
                    clientConnected = true;
                    commErrors = 0;
                    commWarnings = 0;
                }
                else
                    AnnDebug() << "Invalid player number received from server.";
            }
            else if (strcmp(connectResponse.response, netNS::SERVER_FULL) == 0)
                AnnDebug() << "Server Full";
            else
            {
                AnnDebug() << "Invalid ID from server. Server sent:";
                AnnDebug() << connectResponse.response;
            }
        }
        else        // read error
        {
            AnnDebug() << net.getError(error);
        }
        tryToConnect = false;
        step = 0;
    }
}

//=============================================================================
// Check for network timeout
//=============================================================================
void NetworkClient::checkNetworkTimeout()
{
    if (!clientConnected)
        return;
    commErrors++;                         // increment timeout count
    if (commErrors > netNS::MAX_ERRORS)   // if communication timeout
    {
        clientConnected = false;
        AnnDebug() << "***** Disconnected from server. *****";
    }
}

//=============================================================================
// Send the keypress codes to the server
//=============================================================================
void NetworkClient::sendInfoToServer()
{
    int size;
    // prepare structure to be sent
    //toServerData.buttons = buttonState;
    toServerData.playerN = playerN;
	//toServerData.ClientPaddlePos = AnnVect3(10,20,30);
    // send data from client to server

	toServerData.ClientPaddlePos = localPosiion;
    size = sizeof(toServerData);
    error = net.sendData((char*) &toServerData, size, remoteIP, remotePort);
}

//=============================================================================
// Get toClientData from server.
// called by client to get game state from server
//=============================================================================
void NetworkClient::getInfoFromServer()
{
    int size;
    size = sizeof(toClientData);
    int readStatus = net.readData((char *)&toClientData, size, remoteIP, remotePort);
    if( readStatus == netNS::NET_OK && size > 0)
    {

		distantPosition = toClientData.postition;
		referencePuckPosiion = toClientData.PuckPos;

		for(int i=0; i<MAX_CLIENT; i++)        // for all player positions
        {
            // load new data into each player
           // player[i].setNetData(toClientData.player[i].playerData);

        }

        // Game state
        // Bit 0 = roundStart
        // Bits 1-7 reserved for future use
        if((toClientData.gameState & ROUND_START_BIT) &&
            countDownOn == false)
            roundStart();

        gameState = toClientData.gameState; // save new game state

        commErrors = 0;
        commWarnings = 0;
    }

}

//=============================================================================
// Start a new round of play
//=============================================================================
void NetworkClient::roundStart()
{
    // Start ships on opposite sides of planet in stable clockwise orbit
    //player[0].setX();
    //player[1].setX();
    //player[0].setY();
    //player[1].setY();

    countDownTimer = COUNT_DOWN;
    countDownOn = true;
}

AnnVect3 NetworkClient::getRefPuckPosition()
{
	return referencePuckPosiion;
}

<commit_msg>remove useless stuff in the client code<commit_after>#include "stdafx.h"
#include "NetworkClient.hpp"

//fToServerStc NetworkClient::toServerData;

NetworkClient::NetworkClient() : NetworkWorker()
{
	tryToConnect = true;
	clientConnected = false;

	myType = CLIENT;
}

int NetworkClient::initialize(int port)
{
	last = now = AnnEngine::Instance()->getTimeFromStartUp();
	return 0;
}
void NetworkClient::update(){
	//AnnDebug() << "client update";
	now = AnnEngine::Instance()->getTimeFromStartUp();
	float frameTime = now - last;
	last = now;
	communicate(frameTime);
}

// --- Do network communications ---
void NetworkClient::communicate(float frameTime)
{
	//AnnDebug() << "Com";
	if(clientConnected)
		getInfoFromServer(); // Get game state from server
	// Calculate elapsed time for network communications
	/*netTime += frameTime;
	if(netTime < netNS::NET_TIMER) // if not time to communicate*/
		//return;
	if(tryToConnect)
		connectToServer(); // Attempt to connect to game server
	else if(clientConnected)
	{
		/*AnnDebug() << "Should transmit data here";*/
		//checkNetworkTimeout(); // check for disconnect from server
		sendInfoToServer(); //
	}
	netTime -= netNS::NET_TIMER;

}

void NetworkClient::connectToServer()
{
	AnnDebug() << "Call connect to server..." ;
	static int step = 0;
    static float waitTime;  // seconds we have waited for a response from server
    int size;
    int newPort;
    std::string str;
    std::stringstream ss;

    if(clientConnected)     // if connected
    {
        tryToConnect = false;
        AnnDebug() << "Currently connected";
        return;
    }

        AnnDebug() << "----- Vr AirHockey Client -----";

		switch (step)
		{
		case 0:

		newPort = config.port;
        if(newPort == 0)
            newPort = netNS::DEFAULT_PORT;
        if(newPort > netNS::MIN_PORT && newPort < 65536)
        {
            port = newPort;
        }
        else
        AnnDebug() << "Invalid port number";
		strcpy(remoteIP, config.serverAddress.c_str());
        error = net.createClient(remoteIP, port, netNS::UDP);
        if(error != netNS::NET_OK)          // if error
        {
            AnnDebug() << net.getError(error);    // display error message
            tryToConnect = false;
            return;
        }
        // send request to join the server
        AnnDebug() << "Attempting to connect with server."; // display message
        toServerData.playerN = 255;        // playerN=255 is request to join
        size = sizeof(toServerData);
        AnnDebug() << "'Request to join' sent to server.";
        error = net.sendData((char*) &toServerData, size, remoteIP, port);
        AnnDebug() << net.getError(error);
        waitTime = 0;

		step = 4;
        break;

    case 4:
        waitTime+=netTime;      // add time since last call to connect
        // if we timed out with no reponse to our request to join
        if (waitTime > CONNECT_TIMEOUT)
        {
            AnnDebug() << "'Request to join' timed out.";
            //tryToConnect = false;
            return;
        }
        // read ConnectResponse from server
        size = sizeof(connectResponse);
        error = net.readData((char*)&connectResponse, size, remoteIP, remotePort);
        if (error == netNS::NET_OK)     // if read was OK
        {
            if(size == 0)   // if no data received
                return;
            // if the server sent back the proper ID then we are connected
            if (strcmp(connectResponse.response, netNS::SERVER_ID) == 0)
            {
                if (connectResponse.number < MAX_CLIENT)   // if valid player number
                {
                    playerN = connectResponse.number;       // set my player number
                    ss << "Connected as player number: " << playerN;
                    AnnDebug() << ss.str();
                    clientConnected = true;
                    commErrors = 0;
                    commWarnings = 0;
                }
                else
                    AnnDebug() << "Invalid player number received from server.";
            }
            else if (strcmp(connectResponse.response, netNS::SERVER_FULL) == 0)
                AnnDebug() << "Server Full";
            else
            {
                AnnDebug() << "Invalid ID from server. Server sent:";
                AnnDebug() << connectResponse.response;
            }
        }
        else        // read error
        {
            AnnDebug() << net.getError(error);
        }
        tryToConnect = false;
        step = 0;
    }
}

//=============================================================================
// Check for network timeout
//=============================================================================
void NetworkClient::checkNetworkTimeout()
{
    if (!clientConnected)
        return;
    commErrors++;                         // increment timeout count
    if (commErrors > netNS::MAX_ERRORS)   // if communication timeout
    {
        clientConnected = false;
        AnnDebug() << "***** Disconnected from server. *****";
    }
}

//=============================================================================
// Send the keypress codes to the server
//=============================================================================
void NetworkClient::sendInfoToServer()
{
    int size;
    // prepare structure to be sent
    //toServerData.buttons = buttonState;
    toServerData.playerN = playerN;
	//toServerData.ClientPaddlePos = AnnVect3(10,20,30);
    // send data from client to server

	toServerData.ClientPaddlePos = localPosiion;
    size = sizeof(toServerData);
    error = net.sendData((char*) &toServerData, size, remoteIP, remotePort);
}

//=============================================================================
// Get toClientData from server.
// called by client to get game state from server
//=============================================================================
void NetworkClient::getInfoFromServer()
{
    int size;
    size = sizeof(toClientData);
    int readStatus = net.readData((char *)&toClientData, size, remoteIP, remotePort);
    if( readStatus == netNS::NET_OK && size > 0)
    {

		distantPosition = toClientData.postition;
		referencePuckPosiion = toClientData.PuckPos;

		for(int i=0; i<MAX_CLIENT; i++)        // for all player positions
        {
            // load new data into each player
           // player[i].setNetData(toClientData.player[i].playerData);

        }

        // Game state
        // Bit 0 = roundStart
        // Bits 1-7 reserved for future use
        if((toClientData.gameState & ROUND_START_BIT) &&
            countDownOn == false)
            roundStart();

        gameState = toClientData.gameState; // save new game state

        commErrors = 0;
        commWarnings = 0;
    }

}

//=============================================================================
// Start a new round of play
//=============================================================================
void NetworkClient::roundStart()
{
    // Start ships on opposite sides of planet in stable clockwise orbit
    //player[0].setX();
    //player[1].setX();
    //player[0].setY();
    //player[1].setY();

    countDownTimer = COUNT_DOWN;
    countDownOn = true;
}

AnnVect3 NetworkClient::getRefPuckPosition()
{
	return referencePuckPosiion;
}

<|endoftext|>


<commit_before>#include "accelometerwidget.h"

AccelometerWidget::AccelometerWidget(QQuickItem *parent) :
    QQuickPaintedItem(parent)
{
}

void AccelometerWidget::paint(QPainter *painter)
{
    const int boundX = boundingRect().x();
    const int boundY = boundingRect().y();
    const int boundHeight = boundingRect().height();
    const int boundWidth = boundingRect().width();
    const QPointF center = boundingRect().center();

    //draw outer circle
    painter->setPen(QPen(p_edgeColor));
    painter->setBrush(QBrush(p_edgeColor));
    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawEllipse(boundingRect());

   //draw inner circle
    painter->setPen(QPen(p_color));
    painter->setBrush(QBrush(p_color));
    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawEllipse(boundX + p_edgeWidth, boundY + p_edgeWidth, boundWidth - 2 * p_edgeWidth, boundHeight - 2 * p_edgeWidth);

    //draw arrow
    //set triangle path
    QPainterPath path;
    path.moveTo(p_arrowWidth / 2, 0);
    path.lineTo(0, boundHeight /2 - p_edgeWidth * 0.75);
    path.lineTo(- p_arrowWidth / 2, 0);
    path.lineTo( - p_arrowWidth / 2, 0);

    //set painter
    painter->setPen(QPen(p_arrowColor));
    painter->setBrush(QBrush(p_arrowColor));
    painter->translate(center.x(), center.y());
    painter->rotate(p_angle + 180);
    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawPath(path);

    //draw text
    painter->resetTransform();

    QFont font = painter->font();
    font.setPixelSize(boundHeight / 3);
    //font.setFamily("Roboto");
    font.setBold(true);
    painter->setFont(QFont("Arial Narrow", boundHeight / 3.5, QFont::Black));

    painter->setPen(QPen(QColor("white")));
    painter->setBrush(QBrush(QColor("white")));
    painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(p_angle).append("°"));
}

/*-------------------------------------*/
/*---------------SETTERS---------------*/
/*-------------------------------------*/

void AccelometerWidget::setAngle(qreal &value)
{
    if(p_angle != value)
    {
        p_angle = value;
        emit angleChanged();
    }
}

void AccelometerWidget::setColor(QColor &value)
{
    if(p_color != value)
    {
        p_color = value;
        emit colorChanged();
    }
}

void AccelometerWidget::setEdgeColor(QColor &value)
{
    if(p_edgeColor != value)
    {
        p_edgeColor = value;
        emit edgeColorChanged();
    }
}

void AccelometerWidget::setArrowColor(QColor &value)
{
    if(p_arrowColor != value)
    {
        p_arrowColor = value;
        emit arrowColorChanged();
    }
}

void AccelometerWidget::setEdgeWidth(int &value)
{
    if(p_edgeWidth != value)
    {
        p_edgeWidth = value;
        emit edgeWidthChanged();
    }
}

void AccelometerWidget::setArrowWidth(int &value)
{
    if(p_arrowWidth != value)
    {
        p_arrowWidth = value;
        emit arrowWidthChanged();
    }
}

/*-------------------------------------*/
/*---------------GETTERS---------------*/
/*-------------------------------------*/

qreal AccelometerWidget::angle() const
{
    return p_angle;
}

QColor AccelometerWidget::color() const
{
    return p_color;
}

QColor AccelometerWidget::edgeColor() const
{
    return p_edgeColor;
}

QColor AccelometerWidget::arrowColor() const
{
    return p_arrowColor;
}

int AccelometerWidget::edgeWidth() const
{
    return p_edgeWidth;
}

int AccelometerWidget::arrowWidth() const
{
    return p_arrowWidth;
}
<commit_msg>Typos C++: AccelometerWidget<commit_after>#include "accelometerwidget.h"

AccelometerWidget::AccelometerWidget(QQuickItem *parent) :
    QQuickPaintedItem(parent)
{
}

void AccelometerWidget::paint(QPainter *painter)
{
    const int boundX = boundingRect().x();
    const int boundY = boundingRect().y();
    const int boundHeight = boundingRect().height();
    const int boundWidth = boundingRect().width();
    const QPointF center = boundingRect().center();

    //draw outer circle
    painter->setPen(QPen(p_edgeColor));
    painter->setBrush(QBrush(p_edgeColor));
    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawEllipse(boundingRect());

   //draw inner circle
    painter->setPen(QPen(p_color));
    painter->setBrush(QBrush(p_color));
    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawEllipse(boundX + p_edgeWidth, boundY + p_edgeWidth, boundWidth - 2 * p_edgeWidth, boundHeight - 2 * p_edgeWidth);

    //draw arrow
    //set triangle path
    QPainterPath path;
    path.moveTo(p_arrowWidth / 2, 0);
    path.lineTo(0, boundHeight /2 - p_edgeWidth * 0.75);
    path.lineTo(- p_arrowWidth / 2, 0);
    path.lineTo( - p_arrowWidth / 2, 0);

    //set painter
    painter->setPen(QPen(p_arrowColor));
    painter->setBrush(QBrush(p_arrowColor));
    painter->translate(center.x(), center.y());
    painter->rotate(p_angle + 180);
    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawPath(path);

    //draw text
    painter->resetTransform();
    painter->setFont(QFont("Arial Narrow", boundHeight / 3.5, QFont::Black));
    painter->setPen(QPen(QColor("white")));
    painter->setBrush(QBrush(QColor("white")));
    painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(p_angle).append("°"));
}

/*-------------------------------------*/
/*---------------SETTERS---------------*/
/*-------------------------------------*/

void AccelometerWidget::setAngle(qreal &value)
{
    if(p_angle != value)
    {
        p_angle = value;
        emit angleChanged();
    }
}

void AccelometerWidget::setColor(QColor &value)
{
    if(p_color != value)
    {
        p_color = value;
        emit colorChanged();
    }
}

void AccelometerWidget::setEdgeColor(QColor &value)
{
    if(p_edgeColor != value)
    {
        p_edgeColor = value;
        emit edgeColorChanged();
    }
}

void AccelometerWidget::setArrowColor(QColor &value)
{
    if(p_arrowColor != value)
    {
        p_arrowColor = value;
        emit arrowColorChanged();
    }
}

void AccelometerWidget::setEdgeWidth(int &value)
{
    if(p_edgeWidth != value)
    {
        p_edgeWidth = value;
        emit edgeWidthChanged();
    }
}

void AccelometerWidget::setArrowWidth(int &value)
{
    if(p_arrowWidth != value)
    {
        p_arrowWidth = value;
        emit arrowWidthChanged();
    }
}

/*-------------------------------------*/
/*---------------GETTERS---------------*/
/*-------------------------------------*/

qreal AccelometerWidget::angle() const
{
    return p_angle;
}

QColor AccelometerWidget::color() const
{
    return p_color;
}

QColor AccelometerWidget::edgeColor() const
{
    return p_edgeColor;
}

QColor AccelometerWidget::arrowColor() const
{
    return p_arrowColor;
}

int AccelometerWidget::edgeWidth() const
{
    return p_edgeWidth;
}

int AccelometerWidget::arrowWidth() const
{
    return p_arrowWidth;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: convuno.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 14:30:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#include <tools/debug.hxx>
#include <i18npool/mslangid.hxx>

#include "convuno.hxx"
#include "global.hxx"

using namespace com::sun::star;

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

//  everything is static...

LanguageType ScUnoConversion::GetLanguage( const lang::Locale& rLocale )
{
    //  empty language -> LANGUAGE_SYSTEM
    if ( rLocale.Language.getLength() == 0 )
        return LANGUAGE_SYSTEM;

    LanguageType eRet = MsLangId::convertLocaleToLanguage( rLocale );
    if ( eRet == LANGUAGE_NONE )
        eRet = LANGUAGE_SYSTEM;         //! or throw an exception?

    return eRet;
}

void ScUnoConversion::FillLocale( lang::Locale& rLocale, LanguageType eLang )
{
    MsLangId::convertLanguageToLocale( eLang, rLocale );
}

<commit_msg>INTEGRATION: CWS changefileheader (1.6.492); FILE MERGED 2008/03/31 17:19:33 rt 1.6.492.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: convuno.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#include <tools/debug.hxx>
#include <i18npool/mslangid.hxx>

#include "convuno.hxx"
#include "global.hxx"

using namespace com::sun::star;

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

//  everything is static...

LanguageType ScUnoConversion::GetLanguage( const lang::Locale& rLocale )
{
    //  empty language -> LANGUAGE_SYSTEM
    if ( rLocale.Language.getLength() == 0 )
        return LANGUAGE_SYSTEM;

    LanguageType eRet = MsLangId::convertLocaleToLanguage( rLocale );
    if ( eRet == LANGUAGE_NONE )
        eRet = LANGUAGE_SYSTEM;         //! or throw an exception?

    return eRet;
}

void ScUnoConversion::FillLocale( lang::Locale& rLocale, LanguageType eLang )
{
    MsLangId::convertLanguageToLocale( eLang, rLocale );
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: test_activedatasink.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:53:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"

/**************************************************************************
                                TODO
 **************************************************************************

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

#ifndef _TEST_ACTIVEDATASINK_HXX_
#include "test_activedatasink.hxx"
#endif

using namespace test_ftp;
using namespace com::sun::star::uno;
using namespace com::sun::star::io;

Any SAL_CALL Test_ActiveDataSink::queryInterface( const Type& rType ) throw( RuntimeException ) {
    Any aRet = ::cppu::queryInterface(rType,
                                      SAL_STATIC_CAST( XActiveDataSink*,this ));

    return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}

void SAL_CALL Test_ActiveDataSink::acquire( void ) throw() {
    OWeakObject::acquire();
}

void SAL_CALL Test_ActiveDataSink::release( void ) throw() {
    OWeakObject::release();
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.118); FILE MERGED 2008/03/31 15:30:21 rt 1.4.118.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: test_activedatasink.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"

/**************************************************************************
                                TODO
 **************************************************************************

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

#ifndef _TEST_ACTIVEDATASINK_HXX_
#include "test_activedatasink.hxx"
#endif

using namespace test_ftp;
using namespace com::sun::star::uno;
using namespace com::sun::star::io;

Any SAL_CALL Test_ActiveDataSink::queryInterface( const Type& rType ) throw( RuntimeException ) {
    Any aRet = ::cppu::queryInterface(rType,
                                      SAL_STATIC_CAST( XActiveDataSink*,this ));

    return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}

void SAL_CALL Test_ActiveDataSink::acquire( void ) throw() {
    OWeakObject::acquire();
}

void SAL_CALL Test_ActiveDataSink::release( void ) throw() {
    OWeakObject::release();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pkgdatasupplier.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 18:13:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"

/**************************************************************************
                                TODO
 **************************************************************************

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

#include <vector>

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_
#include <com/sun/star/container/XEnumeration.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _UCBHELPER_PROVIDERHELPER_HXX
#include <ucbhelper/providerhelper.hxx>
#endif

#ifndef _PKGDATASUPPLIER_HXX
#include "pkgdatasupplier.hxx"
#endif
#ifndef _PKGCONTENT_HXX
#include "pkgcontent.hxx"
#endif
#ifndef _PKGPROVIDER_HXX
#include "pkgprovider.hxx"
#endif

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

using namespace com::sun::star;
using namespace package_ucp;

namespace package_ucp
{

//=========================================================================
//
// struct ResultListEntry.
//
//=========================================================================

struct ResultListEntry
{
    rtl::OUString                             aURL;
    uno::Reference< ucb::XContentIdentifier > xId;
    uno::Reference< ucb::XContent >           xContent;
    uno::Reference< sdbc::XRow >              xRow;

    ResultListEntry( const rtl::OUString& rURL ) : aURL( rURL ) {}
};

//=========================================================================
//
// ResultList.
//
//=========================================================================

typedef std::vector< ResultListEntry* > ResultList;

//=========================================================================
//
// struct DataSupplier_Impl.
//
//=========================================================================

struct DataSupplier_Impl
{
    osl::Mutex                                   m_aMutex;
    ResultList                                   m_aResults;
    rtl::Reference< Content >                    m_xContent;
    uno::Reference< lang::XMultiServiceFactory > m_xSMgr;
    uno::Reference< container::XEnumeration >    m_xFolderEnum;
    sal_Int32                                    m_nOpenMode;
    sal_Bool                                     m_bCountFinal;
    sal_Bool                                     m_bThrowException;

    DataSupplier_Impl(
            const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
            const rtl::Reference< Content >& rContent,
            sal_Int32 nOpenMode )
    : m_xContent( rContent ), m_xSMgr( rxSMgr ),
      m_xFolderEnum( rContent->getIterator() ), m_nOpenMode( nOpenMode ),
      m_bCountFinal( !m_xFolderEnum.is() ), m_bThrowException( m_bCountFinal )
    {}
    ~DataSupplier_Impl();
};

//=========================================================================
DataSupplier_Impl::~DataSupplier_Impl()
{
    ResultList::const_iterator it  = m_aResults.begin();
    ResultList::const_iterator end = m_aResults.end();

    while ( it != end )
    {
        delete (*it);
        it++;
    }
}

}

//=========================================================================
//=========================================================================
//
// DataSupplier Implementation.
//
//=========================================================================
//=========================================================================

DataSupplier::DataSupplier(
                const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
                const rtl::Reference< Content >& rContent,
                sal_Int32 nOpenMode )
: m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) )
{
}

//=========================================================================
// virtual
DataSupplier::~DataSupplier()
{
    delete m_pImpl;
}

//=========================================================================
// virtual
rtl::OUString DataSupplier::queryContentIdentifierString( sal_uInt32 nIndex )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
    {
        rtl::OUString aId = m_pImpl->m_aResults[ nIndex ]->aURL;
        if ( aId.getLength() )
        {
            // Already cached.
            return aId;
        }
    }

    if ( getResult( nIndex ) )
    {
        // Note: getResult fills m_pImpl->m_aResults[ nIndex ]->aURL.
        return m_pImpl->m_aResults[ nIndex ]->aURL;
    }
    return rtl::OUString();
}

//=========================================================================
// virtual
uno::Reference< ucb::XContentIdentifier >
DataSupplier::queryContentIdentifier( sal_uInt32 nIndex )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
    {
        uno::Reference< ucb::XContentIdentifier > xId
                                = m_pImpl->m_aResults[ nIndex ]->xId;
        if ( xId.is() )
        {
            // Already cached.
            return xId;
        }
    }

    rtl::OUString aId = queryContentIdentifierString( nIndex );
    if ( aId.getLength() )
    {
        uno::Reference< ucb::XContentIdentifier > xId
            = new ::ucbhelper::ContentIdentifier( aId );
        m_pImpl->m_aResults[ nIndex ]->xId = xId;
        return xId;
    }
    return uno::Reference< ucb::XContentIdentifier >();
}

//=========================================================================
// virtual
uno::Reference< ucb::XContent > DataSupplier::queryContent(
                                                        sal_uInt32 nIndex )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
    {
        uno::Reference< ucb::XContent > xContent
                                = m_pImpl->m_aResults[ nIndex ]->xContent;
        if ( xContent.is() )
        {
            // Already cached.
            return xContent;
        }
    }

    uno::Reference< ucb::XContentIdentifier > xId
        = queryContentIdentifier( nIndex );
    if ( xId.is() )
    {
        try
        {
            uno::Reference< ucb::XContent > xContent
                = m_pImpl->m_xContent->getProvider()->queryContent( xId );
            m_pImpl->m_aResults[ nIndex ]->xContent = xContent;
            return xContent;

        }
        catch ( ucb::IllegalIdentifierException const & )
        {
        }
    }
    return uno::Reference< ucb::XContent >();
}

//=========================================================================
// virtual
sal_Bool DataSupplier::getResult( sal_uInt32 nIndex )
{
    osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( m_pImpl->m_aResults.size() > nIndex )
    {
        // Result already present.
        return sal_True;
    }

    // Result not (yet) present.

    if ( m_pImpl->m_bCountFinal )
        return sal_False;

    // Try to obtain result...

    sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
    sal_Bool bFound = sal_False;
    sal_uInt32 nPos = nOldCount;

    while ( m_pImpl->m_xFolderEnum->hasMoreElements() )
    {
        try
        {
            uno::Reference< container::XNamed > xNamed;
            m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;

            if ( !xNamed.is() )
            {
                OSL_ENSURE( sal_False,
                            "DataSupplier::getResult - Got no XNamed!" );
                break;
            }

            rtl::OUString aName = xNamed->getName();

            if ( !aName.getLength() )
            {
                OSL_ENSURE( sal_False,
                            "DataSupplier::getResult - Empty name!" );
                break;
            }

            // Assemble URL for child.
            rtl::OUString aURL = assembleChildURL( aName );

            m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );

            if ( nPos == nIndex )
            {
                // Result obtained.
                bFound = sal_True;
                break;
            }

            nPos++;
        }
        catch ( container::NoSuchElementException const & )
        {
            m_pImpl->m_bThrowException = sal_True;
            break;
        }
        catch ( lang::WrappedTargetException const & )
        {
            m_pImpl->m_bThrowException = sal_True;
            break;
        }
    }

    if ( !bFound )
        m_pImpl->m_bCountFinal = sal_True;

    rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();
    if ( xResultSet.is() )
    {
        // Callbacks follow!
        aGuard.clear();

        if ( nOldCount < m_pImpl->m_aResults.size() )
            xResultSet->rowCountChanged(
                                    nOldCount, m_pImpl->m_aResults.size() );

        if ( m_pImpl->m_bCountFinal )
            xResultSet->rowCountFinal();
    }

    return bFound;
}

//=========================================================================
// virtual
sal_uInt32 DataSupplier::totalCount()
{
    osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( m_pImpl->m_bCountFinal )
        return m_pImpl->m_aResults.size();

    sal_uInt32 nOldCount = m_pImpl->m_aResults.size();

    while ( m_pImpl->m_xFolderEnum->hasMoreElements() )
    {
        try
        {
            uno::Reference< container::XNamed > xNamed;
            m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;

            if ( !xNamed.is() )
            {
                OSL_ENSURE( sal_False,
                            "DataSupplier::getResult - Got no XNamed!" );
                break;
            }

            rtl::OUString aName = xNamed->getName();

            if ( !aName.getLength() )
            {
                OSL_ENSURE( sal_False,
                            "DataSupplier::getResult - Empty name!" );
                break;
            }

            // Assemble URL for child.
            rtl::OUString aURL = assembleChildURL( aName );

            m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );
        }
        catch ( container::NoSuchElementException const & )
        {
            m_pImpl->m_bThrowException = sal_True;
            break;
        }
        catch ( lang::WrappedTargetException const & )
        {
            m_pImpl->m_bThrowException = sal_True;
            break;
        }
    }

    m_pImpl->m_bCountFinal = sal_True;

    rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();
    if ( xResultSet.is() )
    {
        // Callbacks follow!
        aGuard.clear();

        if ( nOldCount < m_pImpl->m_aResults.size() )
            xResultSet->rowCountChanged(
                                    nOldCount, m_pImpl->m_aResults.size() );

        xResultSet->rowCountFinal();
    }

    return m_pImpl->m_aResults.size();
}

//=========================================================================
// virtual
sal_uInt32 DataSupplier::currentCount()
{
    return m_pImpl->m_aResults.size();
}

//=========================================================================
// virtual
sal_Bool DataSupplier::isCountFinal()
{
    return m_pImpl->m_bCountFinal;
}

//=========================================================================
// virtual
uno::Reference< sdbc::XRow > DataSupplier::queryPropertyValues(
                                                        sal_uInt32 nIndex  )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
    {
        uno::Reference< sdbc::XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow;
        if ( xRow.is() )
        {
            // Already cached.
            return xRow;
        }
    }

    if ( getResult( nIndex ) )
    {
        uno::Reference< sdbc::XRow > xRow = Content::getPropertyValues(
                        m_pImpl->m_xSMgr,
                        getResultSet()->getProperties(),
                        static_cast< ContentProvider * >(
                            m_pImpl->m_xContent->getProvider().get() ),
                        queryContentIdentifierString( nIndex ) );
        m_pImpl->m_aResults[ nIndex ]->xRow = xRow;
        return xRow;
    }

    return uno::Reference< sdbc::XRow >();
}

//=========================================================================
// virtual
void DataSupplier::releasePropertyValues( sal_uInt32 nIndex )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
        m_pImpl->m_aResults[ nIndex ]->xRow = uno::Reference< sdbc::XRow >();
}

//=========================================================================
// virtual
void DataSupplier::close()
{
}

//=========================================================================
// virtual
void DataSupplier::validate()
    throw( ucb::ResultSetException )
{
    if ( m_pImpl->m_bThrowException )
        throw ucb::ResultSetException();
}

//=========================================================================
::rtl::OUString DataSupplier::assembleChildURL( const ::rtl::OUString& aName )
{
    rtl::OUString aURL;
    rtl::OUString aContURL
        = m_pImpl->m_xContent->getIdentifier()->getContentIdentifier();
    sal_Int32 nParam = aContURL.indexOf( '?' );
    if ( nParam >= 0 )
    {
        aURL = aContURL.copy( 0, nParam );

        sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' );
        if ( nPackageUrlEnd != aURL.getLength() - 1 )
            aURL += rtl::OUString::createFromAscii( "/" );

        aURL += ::ucb_impl::urihelper::encodeSegment( aName );
        aURL += aContURL.copy( nParam );
    }
    else
    {
        aURL = aContURL;

        sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' );
        if ( nPackageUrlEnd != aURL.getLength() - 1 )
            aURL += rtl::OUString::createFromAscii( "/" );

        aURL += ::ucb_impl::urihelper::encodeSegment( aName );
    }
    return aURL;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.15.72); FILE MERGED 2008/04/01 16:02:23 thb 1.15.72.3: #i85898# Stripping all external header guards 2008/04/01 12:58:22 thb 1.15.72.2: #i85898# Stripping all external header guards 2008/03/31 15:30:27 rt 1.15.72.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: pkgdatasupplier.cxx,v $
 * $Revision: 1.16 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"

/**************************************************************************
                                TODO
 **************************************************************************

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

#include <vector>
#include <osl/diagnose.h>
#include <com/sun/star/container/XEnumeration.hpp>
#include <com/sun/star/container/XNamed.hpp>
#include <ucbhelper/contentidentifier.hxx>
#include <ucbhelper/providerhelper.hxx>
#include "pkgdatasupplier.hxx"
#include "pkgcontent.hxx"
#include "pkgprovider.hxx"

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

using namespace com::sun::star;
using namespace package_ucp;

namespace package_ucp
{

//=========================================================================
//
// struct ResultListEntry.
//
//=========================================================================

struct ResultListEntry
{
    rtl::OUString                             aURL;
    uno::Reference< ucb::XContentIdentifier > xId;
    uno::Reference< ucb::XContent >           xContent;
    uno::Reference< sdbc::XRow >              xRow;

    ResultListEntry( const rtl::OUString& rURL ) : aURL( rURL ) {}
};

//=========================================================================
//
// ResultList.
//
//=========================================================================

typedef std::vector< ResultListEntry* > ResultList;

//=========================================================================
//
// struct DataSupplier_Impl.
//
//=========================================================================

struct DataSupplier_Impl
{
    osl::Mutex                                   m_aMutex;
    ResultList                                   m_aResults;
    rtl::Reference< Content >                    m_xContent;
    uno::Reference< lang::XMultiServiceFactory > m_xSMgr;
    uno::Reference< container::XEnumeration >    m_xFolderEnum;
    sal_Int32                                    m_nOpenMode;
    sal_Bool                                     m_bCountFinal;
    sal_Bool                                     m_bThrowException;

    DataSupplier_Impl(
            const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
            const rtl::Reference< Content >& rContent,
            sal_Int32 nOpenMode )
    : m_xContent( rContent ), m_xSMgr( rxSMgr ),
      m_xFolderEnum( rContent->getIterator() ), m_nOpenMode( nOpenMode ),
      m_bCountFinal( !m_xFolderEnum.is() ), m_bThrowException( m_bCountFinal )
    {}
    ~DataSupplier_Impl();
};

//=========================================================================
DataSupplier_Impl::~DataSupplier_Impl()
{
    ResultList::const_iterator it  = m_aResults.begin();
    ResultList::const_iterator end = m_aResults.end();

    while ( it != end )
    {
        delete (*it);
        it++;
    }
}

}

//=========================================================================
//=========================================================================
//
// DataSupplier Implementation.
//
//=========================================================================
//=========================================================================

DataSupplier::DataSupplier(
                const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
                const rtl::Reference< Content >& rContent,
                sal_Int32 nOpenMode )
: m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) )
{
}

//=========================================================================
// virtual
DataSupplier::~DataSupplier()
{
    delete m_pImpl;
}

//=========================================================================
// virtual
rtl::OUString DataSupplier::queryContentIdentifierString( sal_uInt32 nIndex )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
    {
        rtl::OUString aId = m_pImpl->m_aResults[ nIndex ]->aURL;
        if ( aId.getLength() )
        {
            // Already cached.
            return aId;
        }
    }

    if ( getResult( nIndex ) )
    {
        // Note: getResult fills m_pImpl->m_aResults[ nIndex ]->aURL.
        return m_pImpl->m_aResults[ nIndex ]->aURL;
    }
    return rtl::OUString();
}

//=========================================================================
// virtual
uno::Reference< ucb::XContentIdentifier >
DataSupplier::queryContentIdentifier( sal_uInt32 nIndex )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
    {
        uno::Reference< ucb::XContentIdentifier > xId
                                = m_pImpl->m_aResults[ nIndex ]->xId;
        if ( xId.is() )
        {
            // Already cached.
            return xId;
        }
    }

    rtl::OUString aId = queryContentIdentifierString( nIndex );
    if ( aId.getLength() )
    {
        uno::Reference< ucb::XContentIdentifier > xId
            = new ::ucbhelper::ContentIdentifier( aId );
        m_pImpl->m_aResults[ nIndex ]->xId = xId;
        return xId;
    }
    return uno::Reference< ucb::XContentIdentifier >();
}

//=========================================================================
// virtual
uno::Reference< ucb::XContent > DataSupplier::queryContent(
                                                        sal_uInt32 nIndex )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
    {
        uno::Reference< ucb::XContent > xContent
                                = m_pImpl->m_aResults[ nIndex ]->xContent;
        if ( xContent.is() )
        {
            // Already cached.
            return xContent;
        }
    }

    uno::Reference< ucb::XContentIdentifier > xId
        = queryContentIdentifier( nIndex );
    if ( xId.is() )
    {
        try
        {
            uno::Reference< ucb::XContent > xContent
                = m_pImpl->m_xContent->getProvider()->queryContent( xId );
            m_pImpl->m_aResults[ nIndex ]->xContent = xContent;
            return xContent;

        }
        catch ( ucb::IllegalIdentifierException const & )
        {
        }
    }
    return uno::Reference< ucb::XContent >();
}

//=========================================================================
// virtual
sal_Bool DataSupplier::getResult( sal_uInt32 nIndex )
{
    osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( m_pImpl->m_aResults.size() > nIndex )
    {
        // Result already present.
        return sal_True;
    }

    // Result not (yet) present.

    if ( m_pImpl->m_bCountFinal )
        return sal_False;

    // Try to obtain result...

    sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
    sal_Bool bFound = sal_False;
    sal_uInt32 nPos = nOldCount;

    while ( m_pImpl->m_xFolderEnum->hasMoreElements() )
    {
        try
        {
            uno::Reference< container::XNamed > xNamed;
            m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;

            if ( !xNamed.is() )
            {
                OSL_ENSURE( sal_False,
                            "DataSupplier::getResult - Got no XNamed!" );
                break;
            }

            rtl::OUString aName = xNamed->getName();

            if ( !aName.getLength() )
            {
                OSL_ENSURE( sal_False,
                            "DataSupplier::getResult - Empty name!" );
                break;
            }

            // Assemble URL for child.
            rtl::OUString aURL = assembleChildURL( aName );

            m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );

            if ( nPos == nIndex )
            {
                // Result obtained.
                bFound = sal_True;
                break;
            }

            nPos++;
        }
        catch ( container::NoSuchElementException const & )
        {
            m_pImpl->m_bThrowException = sal_True;
            break;
        }
        catch ( lang::WrappedTargetException const & )
        {
            m_pImpl->m_bThrowException = sal_True;
            break;
        }
    }

    if ( !bFound )
        m_pImpl->m_bCountFinal = sal_True;

    rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();
    if ( xResultSet.is() )
    {
        // Callbacks follow!
        aGuard.clear();

        if ( nOldCount < m_pImpl->m_aResults.size() )
            xResultSet->rowCountChanged(
                                    nOldCount, m_pImpl->m_aResults.size() );

        if ( m_pImpl->m_bCountFinal )
            xResultSet->rowCountFinal();
    }

    return bFound;
}

//=========================================================================
// virtual
sal_uInt32 DataSupplier::totalCount()
{
    osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( m_pImpl->m_bCountFinal )
        return m_pImpl->m_aResults.size();

    sal_uInt32 nOldCount = m_pImpl->m_aResults.size();

    while ( m_pImpl->m_xFolderEnum->hasMoreElements() )
    {
        try
        {
            uno::Reference< container::XNamed > xNamed;
            m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;

            if ( !xNamed.is() )
            {
                OSL_ENSURE( sal_False,
                            "DataSupplier::getResult - Got no XNamed!" );
                break;
            }

            rtl::OUString aName = xNamed->getName();

            if ( !aName.getLength() )
            {
                OSL_ENSURE( sal_False,
                            "DataSupplier::getResult - Empty name!" );
                break;
            }

            // Assemble URL for child.
            rtl::OUString aURL = assembleChildURL( aName );

            m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );
        }
        catch ( container::NoSuchElementException const & )
        {
            m_pImpl->m_bThrowException = sal_True;
            break;
        }
        catch ( lang::WrappedTargetException const & )
        {
            m_pImpl->m_bThrowException = sal_True;
            break;
        }
    }

    m_pImpl->m_bCountFinal = sal_True;

    rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();
    if ( xResultSet.is() )
    {
        // Callbacks follow!
        aGuard.clear();

        if ( nOldCount < m_pImpl->m_aResults.size() )
            xResultSet->rowCountChanged(
                                    nOldCount, m_pImpl->m_aResults.size() );

        xResultSet->rowCountFinal();
    }

    return m_pImpl->m_aResults.size();
}

//=========================================================================
// virtual
sal_uInt32 DataSupplier::currentCount()
{
    return m_pImpl->m_aResults.size();
}

//=========================================================================
// virtual
sal_Bool DataSupplier::isCountFinal()
{
    return m_pImpl->m_bCountFinal;
}

//=========================================================================
// virtual
uno::Reference< sdbc::XRow > DataSupplier::queryPropertyValues(
                                                        sal_uInt32 nIndex  )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
    {
        uno::Reference< sdbc::XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow;
        if ( xRow.is() )
        {
            // Already cached.
            return xRow;
        }
    }

    if ( getResult( nIndex ) )
    {
        uno::Reference< sdbc::XRow > xRow = Content::getPropertyValues(
                        m_pImpl->m_xSMgr,
                        getResultSet()->getProperties(),
                        static_cast< ContentProvider * >(
                            m_pImpl->m_xContent->getProvider().get() ),
                        queryContentIdentifierString( nIndex ) );
        m_pImpl->m_aResults[ nIndex ]->xRow = xRow;
        return xRow;
    }

    return uno::Reference< sdbc::XRow >();
}

//=========================================================================
// virtual
void DataSupplier::releasePropertyValues( sal_uInt32 nIndex )
{
    osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );

    if ( nIndex < m_pImpl->m_aResults.size() )
        m_pImpl->m_aResults[ nIndex ]->xRow = uno::Reference< sdbc::XRow >();
}

//=========================================================================
// virtual
void DataSupplier::close()
{
}

//=========================================================================
// virtual
void DataSupplier::validate()
    throw( ucb::ResultSetException )
{
    if ( m_pImpl->m_bThrowException )
        throw ucb::ResultSetException();
}

//=========================================================================
::rtl::OUString DataSupplier::assembleChildURL( const ::rtl::OUString& aName )
{
    rtl::OUString aURL;
    rtl::OUString aContURL
        = m_pImpl->m_xContent->getIdentifier()->getContentIdentifier();
    sal_Int32 nParam = aContURL.indexOf( '?' );
    if ( nParam >= 0 )
    {
        aURL = aContURL.copy( 0, nParam );

        sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' );
        if ( nPackageUrlEnd != aURL.getLength() - 1 )
            aURL += rtl::OUString::createFromAscii( "/" );

        aURL += ::ucb_impl::urihelper::encodeSegment( aName );
        aURL += aContURL.copy( nParam );
    }
    else
    {
        aURL = aContURL;

        sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' );
        if ( nPackageUrlEnd != aURL.getLength() - 1 )
            aURL += rtl::OUString::createFromAscii( "/" );

        aURL += ::ucb_impl::urihelper::encodeSegment( aName );
    }
    return aURL;
}

<|endoftext|>


<commit_before>// Author: Enrico Guiraud, 2021

/*************************************************************************
 * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_RDF_RSAMPLEINFO
#define ROOT_RDF_RSAMPLEINFO

#include <ROOT/RStringView.hxx>
#include <Rtypes.h>

#include <functional>
#include <stdexcept>
#include <string>

namespace ROOT {
namespace RDF {

/// This type represents a sample identifier, to be used in conjunction with RDataFrame features such as
/// DefinePerSample() and per-sample callbacks.
///
/// When the input data comes from a TTree, the string representation of RSampleInfo (which is returned by AsString()
/// and that can be queried e.g. with Contains()) is of the form "<filename>/<treename>".
///
/// In multi-thread runs different tasks might process different entry ranges of the same sample,
/// so RSampleInfo also provides methods to inspect which part of a sample is being taken into consideration.
class RSampleInfo {
   // Currently backed by a simple string, might change in the future as we get usage experience.
   std::string fID;
   std::pair<ULong64_t, ULong64_t> fEntryRange;

public:
   explicit RSampleInfo(std::string_view id, std::pair<ULong64_t, ULong64_t> entryRange)
      : fID(id), fEntryRange(entryRange)
   {
   }
   RSampleInfo() = default;
   RSampleInfo(const RSampleInfo &) = default;
   RSampleInfo &operator=(const RSampleInfo &) = default;
   RSampleInfo(RSampleInfo &&) = default;
   RSampleInfo &operator=(RSampleInfo &&) = default;
   ~RSampleInfo() = default;

   /// Check whether the sample name contains the given substring.
   bool Contains(std::string_view substr) const
   {
      // C++14 needs the conversion from std::string_view to std::string
      return fID.find(std::string(substr)) != std::string::npos;
   }

   /// Check whether the sample name is empty.
   ///
   /// This is the case e.g. when using a RDataFrame with no input data, constructed as `RDataFrame(nEntries)`.
   bool Empty() const {
      return fID.empty();
   }

   /// Return a string representation of the sample name.
   ///
   /// The representation is of the form "<filename>/<treename>" if the input data comes from a TTree or a TChain.
   const std::string &AsString() const
   {
      return fID;
   }

   /// Return the entry range in this sample that is being taken into consideration.
   ///
   /// Multiple multi-threading tasks might process different entry ranges of the same sample.
   std::pair<ULong64_t, ULong64_t> EntryRange() const { return fEntryRange; }

   /// Return the number of entries of this sample that is being taken into consideration.
   ULong64_t NEntries() const { return fEntryRange.second - fEntryRange.first; }

   bool operator==(const RSampleInfo &other) const { return fID == other.fID; }
   bool operator!=(const RSampleInfo &other) const { return !(*this == other); }
};

/// The type of a data-block callback, registered with a RDataFrame computation graph via e.g.
/// DefinePerSample() or by certain actions (e.g. Snapshot()).
using SampleCallback_t = std::function<void(unsigned int, const ROOT::RDF::RSampleInfo &)>;

} // namespace RDF
} // namespace ROOT

#endif
<commit_msg>[DF][NFC] Add a comma<commit_after>// Author: Enrico Guiraud, 2021

/*************************************************************************
 * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_RDF_RSAMPLEINFO
#define ROOT_RDF_RSAMPLEINFO

#include <ROOT/RStringView.hxx>
#include <Rtypes.h>

#include <functional>
#include <stdexcept>
#include <string>

namespace ROOT {
namespace RDF {

/// This type represents a sample identifier, to be used in conjunction with RDataFrame features such as
/// DefinePerSample() and per-sample callbacks.
///
/// When the input data comes from a TTree, the string representation of RSampleInfo (which is returned by AsString()
/// and that can be queried e.g. with Contains()) is of the form "<filename>/<treename>".
///
/// In multi-thread runs, different tasks might process different entry ranges of the same sample,
/// so RSampleInfo also provides methods to inspect which part of a sample is being taken into consideration.
class RSampleInfo {
   // Currently backed by a simple string, might change in the future as we get usage experience.
   std::string fID;
   std::pair<ULong64_t, ULong64_t> fEntryRange;

public:
   explicit RSampleInfo(std::string_view id, std::pair<ULong64_t, ULong64_t> entryRange)
      : fID(id), fEntryRange(entryRange)
   {
   }
   RSampleInfo() = default;
   RSampleInfo(const RSampleInfo &) = default;
   RSampleInfo &operator=(const RSampleInfo &) = default;
   RSampleInfo(RSampleInfo &&) = default;
   RSampleInfo &operator=(RSampleInfo &&) = default;
   ~RSampleInfo() = default;

   /// Check whether the sample name contains the given substring.
   bool Contains(std::string_view substr) const
   {
      // C++14 needs the conversion from std::string_view to std::string
      return fID.find(std::string(substr)) != std::string::npos;
   }

   /// Check whether the sample name is empty.
   ///
   /// This is the case e.g. when using a RDataFrame with no input data, constructed as `RDataFrame(nEntries)`.
   bool Empty() const {
      return fID.empty();
   }

   /// Return a string representation of the sample name.
   ///
   /// The representation is of the form "<filename>/<treename>" if the input data comes from a TTree or a TChain.
   const std::string &AsString() const
   {
      return fID;
   }

   /// Return the entry range in this sample that is being taken into consideration.
   ///
   /// Multiple multi-threading tasks might process different entry ranges of the same sample.
   std::pair<ULong64_t, ULong64_t> EntryRange() const { return fEntryRange; }

   /// Return the number of entries of this sample that is being taken into consideration.
   ULong64_t NEntries() const { return fEntryRange.second - fEntryRange.first; }

   bool operator==(const RSampleInfo &other) const { return fID == other.fID; }
   bool operator!=(const RSampleInfo &other) const { return !(*this == other); }
};

/// The type of a data-block callback, registered with a RDataFrame computation graph via e.g.
/// DefinePerSample() or by certain actions (e.g. Snapshot()).
using SampleCallback_t = std::function<void(unsigned int, const ROOT::RDF::RSampleInfo &)>;

} // namespace RDF
} // namespace ROOT

#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

/*void doExec(char* cmd){
	int pid = fork();

	if (pid == -1){
		perror("There was an error with fork()");
		exit(1);
	}
	else if (pid == 0){
		if (-1 == execvp(cmd, argv)){
			perror("There was an error with execvp()");
			exit(1);
		}
	}
	else {
		if (-1 == wait(0)){
			perror("There was an error with wait()");
			exit(1);
		}
	}
}*/

char* convert(const string& str){
	char* p = new char[str.size()+1];
	strcpy(p,str.c_str());
	return p;
}

vector<char*> str_parse(string str){
	string arg;
	vector<string> argList;
	vector<char*> argListC;
	istringstream inSS(arg);

	while(!inSS.eof()){
		inSS >> str;
		argList.push_back(arg);
	}

	transform(argList.begin(), argList.end(), back_inserter(argListC), convert);

	return argListC;
}

int main () {
	string cmd;

	while (true){
		cout << "$ ";
		getline(cin, cmd);

		//check for exit command
		if (cmd == "exit") exit(0);

		str_parse(cmd);
	}

	return 0;

}
<commit_msg>shell now functions properly on single command w/ args<commit_after>#include <stdio.h>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

void doExec(vector<char*> instr){
	int pid = fork();

	if (pid == -1){
		perror("There was an error with fork()");
		exit(1);
	}
	else if (pid == 0){
			if (-1 == execvp(instr[0],&instr[0] )){
			perror("There was an error with execvp()");
			exit(1);
		}
	}
	else {
		if (-1 == wait(0)){
			perror("There was an error with wait()");
			exit(1);
		}
	}
}

char* convert(const string& str){
	char* p = new char[str.size()+1];
	strcpy(p,str.c_str());
	return p;
}

vector<char*> str_parse(string str){
	string arg;
	vector<string> argList;
	vector<char*> argListC;
	istringstream inSS(str);

	//parse from command string
	while(!inSS.eof()){
		inSS >> arg;
		argList.push_back(arg);
	}

	//convert c++ string vector into cstring array
	transform(argList.begin(), argList.end(), back_inserter(argListC), convert);
	argListC.push_back(NULL);

	return argListC;
}

int main () {
	string cmd;

	while (true){
		cout << "$ ";
		getline(cin, cmd);

		//check for exit command
		if (cmd == "exit") exit(0);

		vector<char*> v = str_parse(cmd);

		doExec(str_parse(cmd));
	}

	return 0;

}
<|endoftext|>