<commit_before>#include "syscall_model.h"
#include "sys/syscall.h"
#include "transport.h"
#include "config.h"

SyscallMdl::SyscallMdl(Network *net)
      : m_called_enter(false),
      m_ret_val(0),
      m_network(net)
{
}

void SyscallMdl::runExit(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   //if only the code below worked in enter...
   //int return_addr = PIN_GetContextReg(ctx, REG_INST_PTR);
   //return_addr += 2;
   //PIN_SetContextReg(ctx, REG_INST_PTR, return_addr);
   //PIN_ExecuteAt(ctx);

   if (m_called_enter)
   {
#ifdef TARGET_IA32E
      PIN_SetContextReg(ctx, REG_RAX, m_ret_val);
#else
      PIN_SetContextReg(ctx, REG_EAX, m_ret_val);
#endif
      m_called_enter = false;
   }
}

void SyscallMdl::runEnter(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   fprintf(stderr, "Syscall...\n");
   // Reset the buffers for the new transmission
   m_recv_buff.clear();
   m_send_buff.clear();

   int msg_type = MCP_MESSAGE_SYS_CALL;

   UInt8 syscall_number = (UInt8) PIN_GetSyscallNumber(ctx, syscall_standard);

   m_send_buff << msg_type << syscall_number;

   switch (syscall_number)
   {
   case SYS_open:
   {
      // Filter on the input
      char *path = (char *)PIN_GetSyscallArgument(ctx, syscall_standard, 0);
      if (!strcmp(path,"./common/tests/file_io/input"))
      {
         m_called_enter = true;
         m_ret_val = marshallOpenCall(ctx, syscall_standard);
      }
      break;
   }
   case SYS_read:
   {
      m_called_enter = true;
      m_ret_val = marshallReadCall(ctx, syscall_standard);
      break;
   }

   case SYS_write:
   {
      fprintf(stderr, "Calling write call\n");
      m_called_enter = true;
      m_ret_val = marshallWriteCall(ctx, syscall_standard);
      break;
   }
   case SYS_close:
   {
      int fd = PIN_GetSyscallArgument(ctx, syscall_standard, 0);
      if (fd == 0x08)
      {
         m_called_enter = true;
         m_ret_val = marshallCloseCall(ctx, syscall_standard);
      }
      break;
   }
   case SYS_access:
      m_called_enter = true;
      m_ret_val = marshallAccessCall(ctx, syscall_standard);
      break;
   case SYS_brk:
      //uncomment the following when our shared-mem handles mallocs properly
      //m_called_enter = true;
      break;

      // case SYS_exit:
      //    cerr << "exit()" << endl;
      //    break;
   case -1:
      break;
   default:
//            cerr << "SysCall: " << (int)syscall_number << endl;
      break;
   }

   if (m_called_enter)
      PIN_SetSyscallNumber(ctx, syscall_standard, SYS_getpid);

}

int SyscallMdl::marshallOpenCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   /*
       Syscall Args
       const char *pathname, int flags

       Transmit Protocol

       Field               Type
       -----------------|--------
       LEN_FNAME           UInt32
       FILE_NAME           char[]
       STATUS_FLAGS        int

       Receive Protocol

       Field               Type
       -----------------|--------
       STATUS              int

   */

   //cerr << "Entering SyscallMdl::marshallOpen()" << endl;

   char *path = (char *) PIN_GetSyscallArgument(ctx, syscall_standard, 0);
   int flags = (int) PIN_GetSyscallArgument(ctx, syscall_standard, 1);
   UInt32 len_fname = strlen(path) + 1;

   // cerr << "open(" << path << ")" << endl;

   m_send_buff << len_fname << make_pair(path, len_fname) << flags;
   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);
   assert(recv_pkt.length == sizeof(int));
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   int status;
   m_recv_buff >> status;

   delete [](Byte*)recv_pkt.data;

   return status;
}

int SyscallMdl::marshallReadCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{

   /*
       Syscall Args
       int fd, void *buf, size_t count

       Transmit

       Field               Type
       -----------------|--------
       FILE_DESCRIPTOR     int
       COUNT               size_t

       Receive

       Field               Type
       -----------------|--------
       BYTES               int
       BUFFER              void *

   */

   //cerr << "Entering syscall model marshall read" << endl;

   int fd = (int) PIN_GetSyscallArgument(ctx, syscall_standard, 0);
   void *buf = (void *) PIN_GetSyscallArgument(ctx, syscall_standard, 1);
   size_t count = (size_t) PIN_GetSyscallArgument(ctx, syscall_standard, 2);

   // cerr << "read(" << fd << hex << ", " << buf << dec << ", " << count << ")" << endl;

//if shared mem, provide the buf to read into
   m_send_buff << fd << count << (int)buf;
   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   //cerr << "sent to mcp " << m_send_buff.size() << " bytes" << endl;

   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);

   assert(recv_pkt.length >= sizeof(int));
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   int bytes;
   m_recv_buff >> bytes;

   if (bytes != -1)
   {
      m_recv_buff >> make_pair(buf, bytes);
   }
   else
   {
      assert(m_recv_buff.size() == 0);
   }
   //cerr << "Exiting syscall model marshall read" << endl;

   delete [](Byte*)recv_pkt.data;

   return bytes;
}

int SyscallMdl::marshallWriteCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   /*
       Syscall Args
       int fd, void *buf, size_t count

       Transmit

       Field               Type
       -----------------|--------
       FILE_DESCRIPTOR     int
       COUNT               size_t
       BUFFER              char[]

       Receive

       Field               Type
       -----------------|--------
       BYTES               int

   */

   //cerr << "Entering syscall model marshall write" << endl;

   int fd = (int) PIN_GetSyscallArgument(ctx, syscall_standard, 0);
   void *buf = (void *) PIN_GetSyscallArgument(ctx, syscall_standard, 1);
   size_t count = (size_t) PIN_GetSyscallArgument(ctx, syscall_standard, 2);

   // cerr << "write(" << fd << hex << ", " << buf << dec << ", " << count << ")" << endl;

   // If we are simulating shared memory, then we simply put
   // the address in the message. Otherwise, we need to put
   // the data in the message as well.
   if (g_config->isSimulatingSharedMemory())
      m_send_buff << fd << count << (int)buf;
   else
      m_send_buff << fd << count << make_pair(buf, count);

   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);
   assert(recv_pkt.length == sizeof(int));
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   int status;
   m_recv_buff >> status;

   delete [](Byte*) recv_pkt.data;

   return status;
}

int SyscallMdl::marshallCloseCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   /*
       Syscall Args
       int fd, void *buf, size_t count

       Transmit

       Field               Type
       -----------------|--------
       FILE_DESCRIPTOR     int

       Receive

       Field               Type
       -----------------|--------
       STATUS              int

   */

   //cerr << "Entering syscall model marshall close" << endl;

   int fd = (int) PIN_GetSyscallArgument(ctx, syscall_standard, 0);

   // cerr << "close(" << fd  << ")" << endl;

   m_send_buff << fd;
   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);
   assert(recv_pkt.length == sizeof(int));
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   int status;
   m_recv_buff >> status;

   delete [](Byte*) recv_pkt.data;

   return status;
}

int SyscallMdl::marshallAccessCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   //cerr << "Entering SyscallMdl::marshallAccessCall()" << endl;

   char *path = (char *)PIN_GetSyscallArgument(ctx, syscall_standard, 0);
   int mode = (int)PIN_GetSyscallArgument(ctx, syscall_standard, 1);
   UInt32 len_fname = strlen(path) + 1;

   // pack the data
   m_send_buff << len_fname << make_pair(path, len_fname) << mode;

   // send the data
   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   // get a result
   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);

   // Create a buffer out of the result
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   // return the result
   int result;
   m_recv_buff >> result;

   delete [](Byte*) recv_pkt.data;

   return result;
}

<commit_msg>[syscall_model] Enable more functionality in the syscall model as it should all be supported.<commit_after>#include "syscall_model.h"
#include "sys/syscall.h"
#include "transport.h"
#include "config.h"

SyscallMdl::SyscallMdl(Network *net)
      : m_called_enter(false),
      m_ret_val(0),
      m_network(net)
{
}

void SyscallMdl::runExit(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   //if only the code below worked in enter...
   //int return_addr = PIN_GetContextReg(ctx, REG_INST_PTR);
   //return_addr += 2;
   //PIN_SetContextReg(ctx, REG_INST_PTR, return_addr);
   //PIN_ExecuteAt(ctx);

   if (m_called_enter)
   {
#ifdef TARGET_IA32E
      PIN_SetContextReg(ctx, REG_RAX, m_ret_val);
#else
      PIN_SetContextReg(ctx, REG_EAX, m_ret_val);
#endif
      m_called_enter = false;
   }
}

void SyscallMdl::runEnter(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   // Reset the buffers for the new transmission
   m_recv_buff.clear();
   m_send_buff.clear();

   int msg_type = MCP_MESSAGE_SYS_CALL;

   UInt8 syscall_number = (UInt8) PIN_GetSyscallNumber(ctx, syscall_standard);

   m_send_buff << msg_type << syscall_number;

   switch (syscall_number)
   {
   case SYS_open:
   {
      m_called_enter = true;
      m_ret_val = marshallOpenCall(ctx, syscall_standard);
      break;
   }
   case SYS_read:
   {
      m_called_enter = true;
      m_ret_val = marshallReadCall(ctx, syscall_standard);
      break;
   }

   case SYS_write:
   {
      m_called_enter = true;
      m_ret_val = marshallWriteCall(ctx, syscall_standard);
      break;
   }
   case SYS_close:
   {
      m_called_enter = true;
      m_ret_val = marshallCloseCall(ctx, syscall_standard);
      break;
   }
   case SYS_access:
      m_called_enter = true;
      m_ret_val = marshallAccessCall(ctx, syscall_standard);
      break;
   case SYS_brk:
      //uncomment the following when our shared-mem handles mallocs properly
      //m_called_enter = true;
      break;

      // case SYS_exit:
      //    cerr << "exit()" << endl;
      //    break;
   case -1:
      break;
   default:
//            cerr << "SysCall: " << (int)syscall_number << endl;
      break;
   }

   if (m_called_enter)
      PIN_SetSyscallNumber(ctx, syscall_standard, SYS_getpid);

}

int SyscallMdl::marshallOpenCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   /*
       Syscall Args
       const char *pathname, int flags

       Transmit Protocol

       Field               Type
       -----------------|--------
       LEN_FNAME           UInt32
       FILE_NAME           char[]
       STATUS_FLAGS        int

       Receive Protocol

       Field               Type
       -----------------|--------
       STATUS              int

   */

   //cerr << "Entering SyscallMdl::marshallOpen()" << endl;

   char *path = (char *) PIN_GetSyscallArgument(ctx, syscall_standard, 0);
   int flags = (int) PIN_GetSyscallArgument(ctx, syscall_standard, 1);
   UInt32 len_fname = strlen(path) + 1;

   // cerr << "open(" << path << ")" << endl;

   m_send_buff << len_fname << make_pair(path, len_fname) << flags;
   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);
   assert(recv_pkt.length == sizeof(int));
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   int status;
   m_recv_buff >> status;

   delete [](Byte*)recv_pkt.data;

   return status;
}

int SyscallMdl::marshallReadCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{

   /*
       Syscall Args
       int fd, void *buf, size_t count

       Transmit

       Field               Type
       -----------------|--------
       FILE_DESCRIPTOR     int
       COUNT               size_t

       Receive

       Field               Type
       -----------------|--------
       BYTES               int
       BUFFER              void *

   */

   //cerr << "Entering syscall model marshall read" << endl;

   int fd = (int) PIN_GetSyscallArgument(ctx, syscall_standard, 0);
   void *buf = (void *) PIN_GetSyscallArgument(ctx, syscall_standard, 1);
   size_t count = (size_t) PIN_GetSyscallArgument(ctx, syscall_standard, 2);

   // cerr << "read(" << fd << hex << ", " << buf << dec << ", " << count << ")" << endl;

//if shared mem, provide the buf to read into
   m_send_buff << fd << count << (int)buf;
   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   //cerr << "sent to mcp " << m_send_buff.size() << " bytes" << endl;

   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);

   assert(recv_pkt.length >= sizeof(int));
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   int bytes;
   m_recv_buff >> bytes;

   if (bytes != -1)
   {
      m_recv_buff >> make_pair(buf, bytes);
   }
   else
   {
      assert(m_recv_buff.size() == 0);
   }
   //cerr << "Exiting syscall model marshall read" << endl;

   delete [](Byte*)recv_pkt.data;

   return bytes;
}

int SyscallMdl::marshallWriteCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   /*
       Syscall Args
       int fd, void *buf, size_t count

       Transmit

       Field               Type
       -----------------|--------
       FILE_DESCRIPTOR     int
       COUNT               size_t
       BUFFER              char[]

       Receive

       Field               Type
       -----------------|--------
       BYTES               int

   */

   //cerr << "Entering syscall model marshall write" << endl;

   int fd = (int) PIN_GetSyscallArgument(ctx, syscall_standard, 0);
   void *buf = (void *) PIN_GetSyscallArgument(ctx, syscall_standard, 1);
   size_t count = (size_t) PIN_GetSyscallArgument(ctx, syscall_standard, 2);

   // cerr << "write(" << fd << hex << ", " << buf << dec << ", " << count << ")" << endl;

   // If we are simulating shared memory, then we simply put
   // the address in the message. Otherwise, we need to put
   // the data in the message as well.
   if (g_config->isSimulatingSharedMemory())
      m_send_buff << fd << count << (int)buf;
   else
      m_send_buff << fd << count << make_pair(buf, count);

   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);
   assert(recv_pkt.length == sizeof(int));
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   int status;
   m_recv_buff >> status;

   delete [](Byte*) recv_pkt.data;

   return status;
}

int SyscallMdl::marshallCloseCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   /*
       Syscall Args
       int fd, void *buf, size_t count

       Transmit

       Field               Type
       -----------------|--------
       FILE_DESCRIPTOR     int

       Receive

       Field               Type
       -----------------|--------
       STATUS              int

   */

   //cerr << "Entering syscall model marshall close" << endl;

   int fd = (int) PIN_GetSyscallArgument(ctx, syscall_standard, 0);

   // cerr << "close(" << fd  << ")" << endl;

   m_send_buff << fd;
   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);
   assert(recv_pkt.length == sizeof(int));
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   int status;
   m_recv_buff >> status;

   delete [](Byte*) recv_pkt.data;

   return status;
}

int SyscallMdl::marshallAccessCall(CONTEXT *ctx, SYSCALL_STANDARD syscall_standard)
{
   //cerr << "Entering SyscallMdl::marshallAccessCall()" << endl;

   char *path = (char *)PIN_GetSyscallArgument(ctx, syscall_standard, 0);
   int mode = (int)PIN_GetSyscallArgument(ctx, syscall_standard, 1);
   UInt32 len_fname = strlen(path) + 1;

   // pack the data
   m_send_buff << len_fname << make_pair(path, len_fname) << mode;

   // send the data
   m_network->netSend(g_config->getMCPCoreNum(), MCP_REQUEST_TYPE, m_send_buff.getBuffer(), m_send_buff.size());

   // get a result
   NetPacket recv_pkt;
   recv_pkt = m_network->netRecv(g_config->getMCPCoreNum(), MCP_RESPONSE_TYPE);

   // Create a buffer out of the result
   m_recv_buff << make_pair(recv_pkt.data, recv_pkt.length);

   // return the result
   int result;
   m_recv_buff >> result;

   delete [](Byte*) recv_pkt.data;

   return result;
}

<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2014 nabijaczleweli

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "container.hpp"

using namespace sf;
using namespace std;
using namespace audiere;

const string assets_root("./assets");
const string textures_root("./assets/textures");
const string font_root("./assets/fonts");
const string sound_root("./assets/sound");
const string localization_root("./assets/lang");

const string app_name("BarbersAndRebarbs");
/***/ config app_configuration("./" + app_name + ".cfg");

const localizer fallback_izer;
const localizer local_izer(app_configuration.language);
const localizer global_izer(local_izer, fallback_izer);

const Font font_pixelish([] {
	Font tmp;
	tmp.loadFromFile(font_root + "/04B_30.ttf");
	return tmp;
}());
const Font font_swirly([] {
	Font tmp;
	tmp.loadFromFile(font_root + "/MACABRA_.ttf");
	return tmp;
}());

const AudioDevicePtr audio_device(OpenDevice());
<commit_msg>All assets come from exec's dir, not curdir<commit_after>// The MIT License (MIT)

// Copyright (c) 2014 nabijaczleweli

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "container.hpp"
#include "whereami++.hpp"

using namespace sf;
using namespace std;
using namespace audiere;
using namespace whereami;

const string assets_root(executable_dir() + "/assets");
const string textures_root(assets_root + "/textures");
const string font_root(assets_root + "/fonts");
const string sound_root(assets_root + "/sound");
const string localization_root(assets_root + "/lang");

const string app_name("BarbersAndRebarbs");
/***/ config app_configuration(executable_dir() + "/" + app_name + ".cfg");

const localizer fallback_izer;
const localizer local_izer(app_configuration.language);
const localizer global_izer(local_izer, fallback_izer);

const Font font_pixelish([] {
	Font tmp;
	tmp.loadFromFile(font_root + "/04B_30.ttf");
	return tmp;
}());
const Font font_swirly([] {
	Font tmp;
	tmp.loadFromFile(font_root + "/MACABRA_.ttf");
	return tmp;
}());

const AudioDevicePtr audio_device(OpenDevice());
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2015 nabijaczleweli

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "bezier_curve.hpp"
#include "../util/vector.hpp"
#include <algorithm>
#include <functional>
#include <future>

float bezier_curve::bezier_step       = .0001f;
bool bezier_curve::optimize_points    = true;
float bezier_curve::optimize_prettily = .01f;

bezier_curve::bezier_curve(sf::Vector2f the_start_point, sf::Vector2f the_control_point, sf::Vector2f the_end_point)
      : start_point(the_start_point), control_point(the_control_point), end_point(the_end_point) {
	compute_vertices();
}

void bezier_curve::swap(bezier_curve & with) {
#define VSWAP(var)       \
	{                      \
		temp     = var;      \
		var      = with.var; \
		with.var = temp;     \
	}

	sf::Vector2f temp;

	VSWAP(start_point);
	VSWAP(control_point);
	VSWAP(end_point);
	vertices.swap(with.vertices);

#undef VSWAP
}

void bezier_curve::draw(sf::RenderTarget & target, sf::RenderStates) const {
	target.draw(vertices.data(), vertices.size(), sf::PrimitiveType::LineStrip);
	// target.draw(&static_cast<const sf::Vertex &>(Vertex(control_point,sf:: Color::White)), 1, sf::PrimitiveType::Points);  // Debug
}

void bezier_curve::compute_vertices() {
	vertices.clear();
	const auto & scale(get_scale());
	for(float t = 0; t <= 1; t += bezier_step)
		vertices.emplace_back((1 - t) * (1 - t) * (scale * start_point) + 2 * (1 - t) * t * (scale * control_point) + t * t * (scale * end_point), sf::Color::White);
	if(optimize_points) {
		const unsigned int additional_offset = optimize_prettily * vertices.size();
		vertices.erase(
		    unique(vertices.begin() + additional_offset, vertices.end() - additional_offset,
		           [&](auto && lhs, auto && rhs) { return (round(lhs.position.x) == round(rhs.position.x)) && (round(lhs.position.y) == round(rhs.position.y)); }),
		    vertices.end() - additional_offset);
	}
	vertices.shrink_to_fit();
}

void bezier_curve::move(float x, float y) {
	sf::Vector2f by(x, y);
	start_point += by;
	control_point += by;
	end_point += by;
	compute_vertices();
}

void bezier_curve::set_scale(float factor_x, float factor_y) {
	transform.setScale(factor_x, factor_y);
	compute_vertices();
}

void bezier_curve::scale(const sf::Vector2f & factor) {
	scale(factor.x, factor.y);
}

void bezier_curve::scale(float factor_x, float factor_y) {
	transform.scale(factor_x, factor_y);
	compute_vertices();
}
<commit_msg>Use std::swap() in bezier_curve<commit_after>// The MIT License (MIT)

// Copyright (c) 2015 nabijaczleweli

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "bezier_curve.hpp"
#include "../util/vector.hpp"
#include <algorithm>
#include <functional>

float bezier_curve::bezier_step       = .0001f;
bool bezier_curve::optimize_points    = true;
float bezier_curve::optimize_prettily = .01f;

bezier_curve::bezier_curve(sf::Vector2f the_start_point, sf::Vector2f the_control_point, sf::Vector2f the_end_point)
      : start_point(the_start_point), control_point(the_control_point), end_point(the_end_point) {
	compute_vertices();
}

void bezier_curve::swap(bezier_curve & with) {
	std::swap(start_point, with.start_point);
	std::swap(control_point, with.control_point);
	std::swap(end_point, with.end_point);
	vertices.swap(with.vertices);
}

void bezier_curve::draw(sf::RenderTarget & target, sf::RenderStates) const {
	target.draw(vertices.data(), vertices.size(), sf::PrimitiveType::LineStrip);
	// target.draw(&static_cast<const sf::Vertex &>(Vertex(control_point,sf:: Color::White)), 1, sf::PrimitiveType::Points);  // Debug
}

void bezier_curve::compute_vertices() {
	vertices.clear();
	const auto & scale(get_scale());
	for(float t = 0; t <= 1; t += bezier_step)
		vertices.emplace_back((1 - t) * (1 - t) * (scale * start_point) + 2 * (1 - t) * t * (scale * control_point) + t * t * (scale * end_point), sf::Color::White);
	if(optimize_points) {
		const unsigned int additional_offset = optimize_prettily * vertices.size();
		vertices.erase(
		    unique(vertices.begin() + additional_offset, vertices.end() - additional_offset,
		           [&](auto && lhs, auto && rhs) { return (round(lhs.position.x) == round(rhs.position.x)) && (round(lhs.position.y) == round(rhs.position.y)); }),
		    vertices.end() - additional_offset);
	}
	vertices.shrink_to_fit();
}

void bezier_curve::move(float x, float y) {
	sf::Vector2f by(x, y);
	start_point += by;
	control_point += by;
	end_point += by;
	compute_vertices();
}

void bezier_curve::set_scale(float factor_x, float factor_y) {
	transform.setScale(factor_x, factor_y);
	compute_vertices();
}

void bezier_curve::scale(const sf::Vector2f & factor) {
	scale(factor.x, factor.y);
}

void bezier_curve::scale(float factor_x, float factor_y) {
	transform.scale(factor_x, factor_y);
	compute_vertices();
}
<|endoftext|>


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

#include <string>
#include <cmath>

#include "csimsbw.h"
#include "csim/error_codes.h"

// generated with test resource locations
#include "test_resources.h"

#define ABS_TOL 1.0e-7
#define LOOSE_TOL 1.0e-1

TEST(SBW, say_hello) {
    char* hello;
    int length;
    int code = csim_sayHello(&hello, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 11);
    EXPECT_EQ(std::string(hello), "Hello World");
    csim_freeVector(hello);
}

TEST(SBW, model_string) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    EXPECT_EQ(code, 0);
    int expectedLength = 9422 + strlen(" xml:base=\"\"") +
            strlen(TestResources::getLocation(
                       TestResources::CELLML_SINE_MODEL_RESOURCE));
    EXPECT_EQ(length, expectedLength);
    EXPECT_NE(std::string(modelString), "");
    csim_freeVector(modelString);
}

TEST(SBW, model_with_imports_string) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    EXPECT_EQ(code, 0);
    int expectedLength = 4629 + strlen(" xml:base=\"\"") +
            strlen(TestResources::getLocation(
                       TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE));
    EXPECT_EQ(length, expectedLength);
    EXPECT_NE(std::string(modelString), "");
    csim_freeVector(modelString);
}

TEST(SBW, load_model) {
    char* modelString;
    int length;
    // need to allow users to apply changes to the raw XML (from SED-ML for example)
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    EXPECT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    EXPECT_EQ(code, 0);
    csim_freeVector(modelString);
}

TEST(SBW, load_model_with_imports) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    EXPECT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    EXPECT_EQ(code, 0);
    csim_freeVector(modelString);
}

TEST(SBW, get_variables) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    char** variables;
    code = csim_getVariables(&variables, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 19);
    // test a few random variable IDs
    EXPECT_EQ(std::string(variables[0]), "actual_sin/sin");
    EXPECT_EQ(std::string(variables[2]), "deriv_approx_sin/sin");
    EXPECT_EQ(std::string(variables[5]), "main/deriv_approx_initial_value");
    EXPECT_EQ(std::string(variables[9]), "main/x");
    EXPECT_EQ(std::string(variables[15]), "parabolic_approx_sin/kPi_32");
    EXPECT_EQ(std::string(variables[10]), "parabolic_approx_sin/C");
    csim_freeMatrix((void**)variables, length);
}

TEST(SBW, get_variables_with_imports) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    char** variables;
    code = csim_getVariables(&variables, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 5);
    // test a few random variable IDs
    EXPECT_EQ(std::string(variables[1]), "main/sin1");
    EXPECT_EQ(std::string(variables[3]), "main/sin3");
    EXPECT_EQ(std::string(variables[4]), "main/x");
    csim_freeMatrix((void**)variables, length);
}

TEST(SBW, get_initial_values) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 19);
    // test a few random variable values
    EXPECT_NEAR(values[0], 0.0, ABS_TOL);
    EXPECT_NEAR(values[5], 0.0, ABS_TOL);
    EXPECT_NEAR(values[10], 0.75, ABS_TOL);
    csim_freeVector(values);
}

TEST(SBW, get_initial_values_import) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 5);
    // test a few random variable values
    EXPECT_NEAR(values[1], 0.0, ABS_TOL);
    EXPECT_NEAR(values[3], 0.0, ABS_TOL);
    EXPECT_NEAR(values[4], 0.0, ABS_TOL);
    csim_freeVector(values);
}

TEST(SBW, set_value) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    // get the initial values
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 19);
    // test a few random variable values
    EXPECT_NEAR(values[0], 0.0, ABS_TOL);
    EXPECT_NEAR(values[5], 0.0, ABS_TOL);
    EXPECT_NEAR(values[10], 0.75, ABS_TOL);
    csim_freeVector(values);
    // and now we should be able to set the value of the input variables
    code = csim_setValue("main/deriv_approx_initial_value", 123.456);
    EXPECT_EQ(code, 0);
    code = csim_setValue("parabolic_approx_sin/C", 987.654);
    EXPECT_EQ(code, 0);
    code = csim_getValues(&values, &length);
    EXPECT_NEAR(values[5], 123.456, ABS_TOL);
    EXPECT_NEAR(values[10], 987.654, ABS_TOL);
    csim_freeVector(values);
}

TEST(SBW, set_value_import) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 5);
    // test a few random variable values
    EXPECT_NEAR(values[1], 0.0, ABS_TOL);
    EXPECT_NEAR(values[3], 0.0, ABS_TOL);
    EXPECT_NEAR(values[4], 0.0, ABS_TOL);
    csim_freeVector(values);
    // try setting a variable (there are no inputs in this model)
    code = csim_setValue("main/sin1", 123.4);
    EXPECT_NE(code, 0);
}

TEST(SBW, one_step) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    // get the initial values
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 19);
    csim_freeVector(values);
    code = csim_setTolerances(1.0, 1.0, 10);
    code = csim_oneStep(1.5);
    EXPECT_EQ(code, 0);
    // check the outputs
    code = csim_getValues(&values, &length);
    EXPECT_NEAR(values[9], 1.5, ABS_TOL); // main/x
    EXPECT_NEAR(values[0], sin(1.5), ABS_TOL); // actual_sin/sin
    EXPECT_NEAR(values[2], sin(1.5), LOOSE_TOL); // deriv_approx_sin/sin
    csim_freeVector(values);
}
<commit_msg>add one step test for import model<commit_after>#include "gtest/gtest.h"

#include <string>
#include <cmath>

#include "csimsbw.h"
#include "csim/error_codes.h"

// generated with test resource locations
#include "test_resources.h"

#define ABS_TOL 1.0e-7
#define LOOSE_TOL 1.0e-1

TEST(SBW, say_hello) {
    char* hello;
    int length;
    int code = csim_sayHello(&hello, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 11);
    EXPECT_EQ(std::string(hello), "Hello World");
    csim_freeVector(hello);
}

TEST(SBW, model_string) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    EXPECT_EQ(code, 0);
    int expectedLength = 9422 + strlen(" xml:base=\"\"") +
            strlen(TestResources::getLocation(
                       TestResources::CELLML_SINE_MODEL_RESOURCE));
    EXPECT_EQ(length, expectedLength);
    EXPECT_NE(std::string(modelString), "");
    csim_freeVector(modelString);
}

TEST(SBW, model_with_imports_string) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    EXPECT_EQ(code, 0);
    int expectedLength = 4629 + strlen(" xml:base=\"\"") +
            strlen(TestResources::getLocation(
                       TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE));
    EXPECT_EQ(length, expectedLength);
    EXPECT_NE(std::string(modelString), "");
    csim_freeVector(modelString);
}

TEST(SBW, load_model) {
    char* modelString;
    int length;
    // need to allow users to apply changes to the raw XML (from SED-ML for example)
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    EXPECT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    EXPECT_EQ(code, 0);
    csim_freeVector(modelString);
}

TEST(SBW, load_model_with_imports) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    EXPECT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    EXPECT_EQ(code, 0);
    csim_freeVector(modelString);
}

TEST(SBW, get_variables) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    char** variables;
    code = csim_getVariables(&variables, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 19);
    // test a few random variable IDs
    EXPECT_EQ(std::string(variables[0]), "actual_sin/sin");
    EXPECT_EQ(std::string(variables[2]), "deriv_approx_sin/sin");
    EXPECT_EQ(std::string(variables[5]), "main/deriv_approx_initial_value");
    EXPECT_EQ(std::string(variables[9]), "main/x");
    EXPECT_EQ(std::string(variables[15]), "parabolic_approx_sin/kPi_32");
    EXPECT_EQ(std::string(variables[10]), "parabolic_approx_sin/C");
    csim_freeMatrix((void**)variables, length);
}

TEST(SBW, get_variables_with_imports) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    char** variables;
    code = csim_getVariables(&variables, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 5);
    // test a few random variable IDs
    EXPECT_EQ(std::string(variables[1]), "main/sin1");
    EXPECT_EQ(std::string(variables[3]), "main/sin3");
    EXPECT_EQ(std::string(variables[4]), "main/x");
    csim_freeMatrix((void**)variables, length);
}

TEST(SBW, get_initial_values) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 19);
    // test a few random variable values
    EXPECT_NEAR(values[0], 0.0, ABS_TOL);
    EXPECT_NEAR(values[5], 0.0, ABS_TOL);
    EXPECT_NEAR(values[10], 0.75, ABS_TOL);
    csim_freeVector(values);
}

TEST(SBW, get_initial_values_import) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 5);
    // test a few random variable values
    EXPECT_NEAR(values[1], 0.0, ABS_TOL);
    EXPECT_NEAR(values[3], 0.0, ABS_TOL);
    EXPECT_NEAR(values[4], 0.0, ABS_TOL);
    csim_freeVector(values);
}

TEST(SBW, set_value) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    // get the initial values
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 19);
    // test a few random variable values
    EXPECT_NEAR(values[0], 0.0, ABS_TOL);
    EXPECT_NEAR(values[5], 0.0, ABS_TOL);
    EXPECT_NEAR(values[10], 0.75, ABS_TOL);
    csim_freeVector(values);
    // and now we should be able to set the value of the input variables
    code = csim_setValue("main/deriv_approx_initial_value", 123.456);
    EXPECT_EQ(code, 0);
    code = csim_setValue("parabolic_approx_sin/C", 987.654);
    EXPECT_EQ(code, 0);
    code = csim_getValues(&values, &length);
    EXPECT_NEAR(values[5], 123.456, ABS_TOL);
    EXPECT_NEAR(values[10], 987.654, ABS_TOL);
    csim_freeVector(values);
}

TEST(SBW, set_value_import) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 5);
    // test a few random variable values
    EXPECT_NEAR(values[1], 0.0, ABS_TOL);
    EXPECT_NEAR(values[3], 0.0, ABS_TOL);
    EXPECT_NEAR(values[4], 0.0, ABS_TOL);
    csim_freeVector(values);
    // try setting a variable (there are no inputs in this model)
    code = csim_setValue("main/sin1", 123.4);
    EXPECT_NE(code, 0);
}

TEST(SBW, one_step) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    // get the initial values
    code = csim_getValues(&values, &length);
    EXPECT_EQ(code, 0);
    EXPECT_EQ(length, 19);
    csim_freeVector(values);
    code = csim_setTolerances(1.0, 1.0, 10);
    code = csim_oneStep(1.5);
    EXPECT_EQ(code, 0);
    // check the outputs
    code = csim_getValues(&values, &length);
    EXPECT_NEAR(values[9], 1.5, ABS_TOL); // main/x
    EXPECT_NEAR(values[0], sin(1.5), ABS_TOL); // actual_sin/sin
    EXPECT_NEAR(values[2], sin(1.5), LOOSE_TOL); // deriv_approx_sin/sin
    csim_freeVector(values);
}

TEST(SBW, one_step_import) {
    char* modelString;
    int length;
    int code = csim_serialiseCellmlFromUrl(
                TestResources::getLocation(
                    TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE),
                &modelString, &length);
    // no point continuing if this fails
    ASSERT_EQ(code, 0);
    code = csim_loadCellml(modelString);
    ASSERT_EQ(code, 0);
    csim_freeVector(modelString);
    double* values;
    code = csim_setTolerances(1.0, 1.0, 10);
    code = csim_oneStep(1.5);
    EXPECT_EQ(code, 0);
    // check the outputs
    code = csim_getValues(&values, &length);
    EXPECT_NEAR(values[4], 1.5, ABS_TOL); // main/x
    EXPECT_NEAR(values[1], sin(1.5), ABS_TOL); // main/sin1 (actual sine)
    EXPECT_NEAR(values[2], sin(1.5), LOOSE_TOL); // main/sin2 (deriv approx)
    EXPECT_NEAR(values[3], sin(1.5), LOOSE_TOL); // main/sin3 (parabolic approx)
    csim_freeVector(values);
}

<|endoftext|>


<commit_before>#pragma once

#include <cassert>
#include <vector>
#ifdef ENABLE_PROGRESS_THREAD
#include <pthread.h>
#endif
#ifdef FLUSH_ALLOC_RETRY
#include <algorithm> // std::min
#include <unistd.h>  // usleep
#define RETRY_MIN_INTERVAL 10	    // ms
#define RETRY_MAX_INTERVAL 1000	    // ms
#define RETRY_INTERVAL_FACTOR 2
#define RETRY_MAX_ITER 100
#endif
#include <upcxx.h>

#ifdef FLUSH_ALLOC_RETRY
// retry remote allocation statement A with exponential backoff
#ifdef FLUSH_WARN_ON_RETRY
#define FLUSH_WARN_RETRY if ( iter > 0 ) printf( "Warning: Thread %4i : ALLOC_WRAP required %li attempts\n", MYTHREAD, iter );
#else
#define FLUSH_WARN_RETRY /* noop */
#endif
#define ALLOC_WRAP( A ) \
  do { \
    long iter = 0; \
    useconds_t t = RETRY_MIN_INTERVAL; \
    while ( ( A ).raw_ptr() == NULL && iter++ < RETRY_MAX_ITER ) { \
      usleep( 1000 * t ); \
      t = std::min( t * RETRY_INTERVAL_FACTOR, (useconds_t) RETRY_MAX_INTERVAL ); \
    } \
    FLUSH_WARN_RETRY \
  } while(0)
#else
// just try once
#define ALLOC_WRAP( A ) A
#endif

namespace cm
{

  /// @cond INTERNAL_DOCS

  /**
   * A task that performs remote updates (spawned by Bin<T>)
   * \param g_my_data Reference to local storage on the target
   * \param g_ix Reference to update indexing (already transferred target)
   * \param g_data Reference to update data (already transferred target)
   */
  template <typename T>
  void
  update_task( long size,
               upcxx::global_ptr<T>    g_my_data,
               upcxx::global_ptr<long> g_ix,
               upcxx::global_ptr<T>    g_data )
  {
    // local ptrs (for casts)
    long *p_ix;
    T *p_data, *p_my_data;

#ifndef NOCHECK
    assert( g_my_data.where() == MYTHREAD );
    assert( g_ix.where()      == MYTHREAD );
    assert( g_data.where()    == MYTHREAD );
#endif

    // cast to local ptrs
    p_ix = (long *) g_ix;
    p_data = (T *) g_data;
    p_my_data = (T *) g_my_data;

    // update
    for ( long k = 0; k < size; k++ )
      p_my_data[p_ix[k]] += p_data[k];

    // free local (but remotely allocated) storage
    upcxx::deallocate( g_ix );
    upcxx::deallocate( g_data );

  } // end of update_task

  /**
   * Implements the binning / remote application for a single thread
   * Not very efficient in terms of space for the moment, in exchange for
   * simplicity.
   * \tparam T Matrix data type (e.g. float)
   */
  template<typename T>
  class Bin
  {

   private:

    bool _init;                           // whether fields intialized
    int _remote_tid;                      // thread id of target
    upcxx::global_ptr<T> _g_remote_data;  // global_ptr _local_ to target
    std::vector<long> _ix;                // linear indexing for target
    std::vector<T> _data;                 // update data for target
#ifdef ENABLE_PROGRESS_THREAD
    pthread_mutex_t *_tq_mutex;           // mutex protecting task-queue ops
#endif

    inline void
    clear()
    {
      _ix.clear();
      _data.clear();
    }

   public:

    /**
     * Create an uninitialized Bin object
     */
    Bin() :
      _init(false)
    {}

#ifdef ENABLE_PROGRESS_THREAD
    /**
     * Create the Bin object associated with a given target
     * \param g_remote_data global_ptr<T> reference to the target-local storage
     * \param tq_mutex pthread mutex protecting the task queue and associated
     * GASNet operations
     */
    Bin( upcxx::global_ptr<T> g_remote_data, pthread_mutex_t * tq_mutex ) :
      _init(true),
      _remote_tid(g_remote_data.where()),
      _g_remote_data(g_remote_data),
      _tq_mutex(tq_mutex)
    {}

    /**
     * Initialize the previously empty Bin object for a given target
     * \param g_remote_data global_ptr<T> reference to the target-local storage
     * \param tq_mutex pthread mutex protecting the task queue and associated
     * GASNet operations
     *
     * \b Note: It is erroneous to call this on a previously initialized Bin.
     */
    inline void
    init( upcxx::global_ptr<T> g_remote_data, pthread_mutex_t * tq_mutex )
    {
      assert( ! _init );
      _remote_tid = g_remote_data.where();
      _g_remote_data = g_remote_data;
      _tq_mutex = tq_mutex;
      _init = true;
    }
#else
    /**
     * Create the Bin object associated with a given target
     * \param g_remote_data global_ptr<T> reference to the target-local storage
     */
    Bin( upcxx::global_ptr<T> g_remote_data ) :
      _init(true),
      _remote_tid(g_remote_data.where()),
      _g_remote_data(g_remote_data)
    {}

    /**
     * Initialize the previously empty Bin object for a given target
     * \param g_remote_data global_ptr<T> reference to the target-local storage
     *
     * \b Note: It is erroneous to call this on a previously initialized Bin.
     */
    inline void
    init( upcxx::global_ptr<T> g_remote_data )
    {
      assert( ! _init );
      _remote_tid = g_remote_data.where();
      _g_remote_data = g_remote_data;
      _init = true;
    }
#endif

    /**
     * Current size of the bin (number of update elems not yet applied)
     */
    inline long
    size() const
    {
      return _ix.size();
    }

    /**
     * Add an elemental update to this bin
     * \param data Elemental update (r.h.s. of +=)
     * \param ij Linear index (on the target) of element to be updated
     */
    inline void
    append( T data, long ij )
    {
      _ix.push_back( ij );
      _data.push_back( data );
    }

    /**
     * "Flush" this bin by initiate remote async update using the current bin
     * contents.
     * \param e upcxx::event pointer to which the async task will be registered
     */
    void
    flush( upcxx::event *e )
    {
#ifndef NOCHECK
      assert( _init );
#endif

      // global ptrs to local storage for async remote copy
      upcxx::global_ptr<long> g_ix;
      upcxx::global_ptr<T> g_data;

#ifdef ENABLE_PROGRESS_THREAD
      pthread_mutex_lock( _tq_mutex );
#endif

      // allocate remote storage
      ALLOC_WRAP( g_ix = upcxx::allocate<long>( _remote_tid, _ix.size() ) );
#ifdef NOCHECK
      assert( g_ix.raw_ptr() != NULL );
#endif
      ALLOC_WRAP( g_data = upcxx::allocate<T>( _remote_tid, _data.size() ) );
#ifdef NOCHECK
      assert( g_data.raw_ptr() != NULL );
#endif

      // copy to remote
      upcxx::copy( (upcxx::global_ptr<long>) _ix.data(), g_ix, _ix.size() );
      upcxx::copy( (upcxx::global_ptr<T>) _data.data(), g_data, _data.size() );

      // spawn the remote update (responsible for deallocating g_ix, g_data)
      upcxx::async( _remote_tid, e )( update_task<T>,
                                      _data.size(),
                                      _g_remote_data,
                                      g_ix, g_data );

#ifdef ENABLE_PROGRESS_THREAD
      pthread_mutex_unlock( _tq_mutex );
#endif

      // clear internal (vector) storage
      clear();
    }

  }; // end of Bin

  /// @endcond

}
<commit_msg>A little cleanup in FLUSH_ALLOC_RETRY<commit_after>#pragma once

#include <cassert>
#include <vector>
#ifdef ENABLE_PROGRESS_THREAD
#include <pthread.h>
#endif
#ifdef FLUSH_ALLOC_RETRY
#include <algorithm> // std::min
#include <unistd.h>  // usleep
#define RETRY_MIN_INTERVAL 10	    // ms
#define RETRY_MAX_INTERVAL 1000	    // ms
#define RETRY_INTERVAL_FACTOR 2
#define RETRY_MAX_ITER 100
#endif
#include <upcxx.h>

#ifdef FLUSH_ALLOC_RETRY
// retry remote allocation statement A with exponential backoff
#ifdef FLUSH_WARN_ON_RETRY
#define FLUSH_WARN_RETRY if ( iter > 0 ) \
  printf( "Warning: Thread %4i : ALLOC_WRAP required %li attempts\n", \
	  MYTHREAD, iter );
#else
#define FLUSH_WARN_RETRY /* noop */
#endif
#define ALLOC_WRAP( A ) \
  do { \
    long iter = 0; \
    useconds_t t = RETRY_MIN_INTERVAL; \
    while ( ( A ).raw_ptr() == NULL && iter++ < RETRY_MAX_ITER ) { \
      usleep( 1000 * t ); \
      t = std::min( t * RETRY_INTERVAL_FACTOR, \
		    (useconds_t) RETRY_MAX_INTERVAL ); \
    } \
    FLUSH_WARN_RETRY \
  } while(0)
#else
// identity
#define ALLOC_WRAP( A ) A
#endif

namespace cm
{

  /// @cond INTERNAL_DOCS

  /**
   * A task that performs remote updates (spawned by Bin<T>)
   * \param g_my_data Reference to local storage on the target
   * \param g_ix Reference to update indexing (already transferred target)
   * \param g_data Reference to update data (already transferred target)
   */
  template <typename T>
  void
  update_task( long size,
               upcxx::global_ptr<T>    g_my_data,
               upcxx::global_ptr<long> g_ix,
               upcxx::global_ptr<T>    g_data )
  {
    // local ptrs (for casts)
    long *p_ix;
    T *p_data, *p_my_data;

#ifndef NOCHECK
    assert( g_my_data.where() == MYTHREAD );
    assert( g_ix.where()      == MYTHREAD );
    assert( g_data.where()    == MYTHREAD );
#endif

    // cast to local ptrs
    p_ix = (long *) g_ix;
    p_data = (T *) g_data;
    p_my_data = (T *) g_my_data;

    // update
    for ( long k = 0; k < size; k++ )
      p_my_data[p_ix[k]] += p_data[k];

    // free local (but remotely allocated) storage
    upcxx::deallocate( g_ix );
    upcxx::deallocate( g_data );

  } // end of update_task

  /**
   * Implements the binning / remote application for a single thread
   * Not very efficient in terms of space for the moment, in exchange for
   * simplicity.
   * \tparam T Matrix data type (e.g. float)
   */
  template<typename T>
  class Bin
  {

   private:

    bool _init;                           // whether fields intialized
    int _remote_tid;                      // thread id of target
    upcxx::global_ptr<T> _g_remote_data;  // global_ptr _local_ to target
    std::vector<long> _ix;                // linear indexing for target
    std::vector<T> _data;                 // update data for target
#ifdef ENABLE_PROGRESS_THREAD
    pthread_mutex_t *_tq_mutex;           // mutex protecting task-queue ops
#endif

    inline void
    clear()
    {
      _ix.clear();
      _data.clear();
    }

   public:

    /**
     * Create an uninitialized Bin object
     */
    Bin() :
      _init(false)
    {}

#ifdef ENABLE_PROGRESS_THREAD
    /**
     * Create the Bin object associated with a given target
     * \param g_remote_data global_ptr<T> reference to the target-local storage
     * \param tq_mutex pthread mutex protecting the task queue and associated
     * GASNet operations
     */
    Bin( upcxx::global_ptr<T> g_remote_data, pthread_mutex_t * tq_mutex ) :
      _init(true),
      _remote_tid(g_remote_data.where()),
      _g_remote_data(g_remote_data),
      _tq_mutex(tq_mutex)
    {}

    /**
     * Initialize the previously empty Bin object for a given target
     * \param g_remote_data global_ptr<T> reference to the target-local storage
     * \param tq_mutex pthread mutex protecting the task queue and associated
     * GASNet operations
     *
     * \b Note: It is erroneous to call this on a previously initialized Bin.
     */
    inline void
    init( upcxx::global_ptr<T> g_remote_data, pthread_mutex_t * tq_mutex )
    {
      assert( ! _init );
      _remote_tid = g_remote_data.where();
      _g_remote_data = g_remote_data;
      _tq_mutex = tq_mutex;
      _init = true;
    }
#else
    /**
     * Create the Bin object associated with a given target
     * \param g_remote_data global_ptr<T> reference to the target-local storage
     */
    Bin( upcxx::global_ptr<T> g_remote_data ) :
      _init(true),
      _remote_tid(g_remote_data.where()),
      _g_remote_data(g_remote_data)
    {}

    /**
     * Initialize the previously empty Bin object for a given target
     * \param g_remote_data global_ptr<T> reference to the target-local storage
     *
     * \b Note: It is erroneous to call this on a previously initialized Bin.
     */
    inline void
    init( upcxx::global_ptr<T> g_remote_data )
    {
      assert( ! _init );
      _remote_tid = g_remote_data.where();
      _g_remote_data = g_remote_data;
      _init = true;
    }
#endif

    /**
     * Current size of the bin (number of update elems not yet applied)
     */
    inline long
    size() const
    {
      return _ix.size();
    }

    /**
     * Add an elemental update to this bin
     * \param data Elemental update (r.h.s. of +=)
     * \param ij Linear index (on the target) of element to be updated
     */
    inline void
    append( T data, long ij )
    {
      _ix.push_back( ij );
      _data.push_back( data );
    }

    /**
     * "Flush" this bin by initiate remote async update using the current bin
     * contents.
     * \param e upcxx::event pointer to which the async task will be registered
     */
    void
    flush( upcxx::event *e )
    {
#ifndef NOCHECK
      assert( _init );
#endif

      // global ptrs to local storage for async remote copy
      upcxx::global_ptr<long> g_ix;
      upcxx::global_ptr<T> g_data;

#ifdef ENABLE_PROGRESS_THREAD
      pthread_mutex_lock( _tq_mutex );
#endif

      // allocate remote storage
      ALLOC_WRAP( g_ix = upcxx::allocate<long>( _remote_tid, _ix.size() ) );
#ifdef NOCHECK
      assert( g_ix.raw_ptr() != NULL );
#endif
      ALLOC_WRAP( g_data = upcxx::allocate<T>( _remote_tid, _data.size() ) );
#ifdef NOCHECK
      assert( g_data.raw_ptr() != NULL );
#endif

      // copy to remote
      upcxx::copy( (upcxx::global_ptr<long>) _ix.data(), g_ix, _ix.size() );
      upcxx::copy( (upcxx::global_ptr<T>) _data.data(), g_data, _data.size() );

      // spawn the remote update (responsible for deallocating g_ix, g_data)
      upcxx::async( _remote_tid, e )( update_task<T>,
                                      _data.size(),
                                      _g_remote_data,
                                      g_ix, g_data );

#ifdef ENABLE_PROGRESS_THREAD
      pthread_mutex_unlock( _tq_mutex );
#endif

      // clear internal (vector) storage
      clear();
    }

  }; // end of Bin

  /// @endcond

}
<|endoftext|>


<commit_before>#pragma once

#include "cpputil.hh"
#include "ns.hh"
#include "gc.hh"
#include "atomic.hh"
#include "ref.hh"

u64 namehash(const strbuf<DIRSIZ>&);

struct file : public referenced, public rcu_freed {
  static file* alloc();
  file*        dup();
  int          stat(struct stat*);
  int          read(char *addr, int n);
  ssize_t      pread(char *addr, size_t n, off_t offset);
  int          write(const char *addr, int n);

  enum { FD_NONE, FD_PIPE, FD_INODE, FD_SOCKET } type;

  char readable;
  char writable;

  int socket;
  struct pipe *pipe;
  struct inode *ip;
  u32 off;

  virtual void do_gc(void);

private:
  file();
  file& operator=(const file&);
  file(const file& x);
  NEW_DELETE_OPS(file);

protected:
  virtual void onzero() const;
};

// in-core file system types

struct inode : public rcu_freed {
  u32 dev;           // Device number
  u32 inum;          // Inode number
  u32 gen;           // Generation number
  std::atomic<int> ref; // Reference count
  int flags;         // I_BUSY, I_VALID
  std::atomic<int> readbusy;
  struct condvar cv;
  struct spinlock lock;
  char lockname[16];
  std::atomic<xns<strbuf<DIRSIZ>, u32, namehash>*> dir;

  short type;         // copy of disk inode
  short major;
  short minor;
  short nlink;
  u32 size;
  u32 addrs[NDIRECT+1];

  static inode* alloc(u32 dev, u32 inum);
  void init();
  inode();
  ~inode();
  virtual void do_gc() { delete this; }
  NEW_DELETE_OPS(inode)
};

#define I_BUSYR 0x1
#define I_BUSYW 0x2
#define I_VALID 0x4
#define I_FREE 0x8

// device implementations

struct devsw {
  int (*read)(struct inode*, char*, u32, u32);
  int (*write)(struct inode*, const char*, u32, u32);
  void (*stat)(struct inode*, struct stat*);
};

extern struct devsw devsw[];
<commit_msg>inode class definition nits<commit_after>#pragma once

#include "cpputil.hh"
#include "ns.hh"
#include "gc.hh"
#include "atomic.hh"
#include "ref.hh"

u64 namehash(const strbuf<DIRSIZ>&);

struct file : public referenced, public rcu_freed {
  static file* alloc();
  file*        dup();
  int          stat(struct stat*);
  int          read(char *addr, int n);
  ssize_t      pread(char *addr, size_t n, off_t offset);
  int          write(const char *addr, int n);

  enum { FD_NONE, FD_PIPE, FD_INODE, FD_SOCKET } type;

  char readable;
  char writable;

  int socket;
  struct pipe *pipe;
  struct inode *ip;
  u32 off;

  virtual void do_gc(void);

private:
  file();
  file& operator=(const file&);
  file(const file& x);
  NEW_DELETE_OPS(file);

protected:
  virtual void onzero() const;
};

// in-core file system types

struct inode : public rcu_freed
{
  static inode* alloc(u32 dev, u32 inum);
  virtual void do_gc() { delete this; }
  void init();

  inode& operator=(const inode&) = delete;
  inode(const inode& x) = delete;

  u32 dev;           // Device number
  u32 inum;          // Inode number
  u32 gen;           // Generation number
  std::atomic<int> ref; // Reference count
  int flags;         // I_BUSY, I_VALID
  std::atomic<int> readbusy;
  struct condvar cv;
  struct spinlock lock;
  char lockname[16];
  std::atomic<xns<strbuf<DIRSIZ>, u32, namehash>*> dir;

  short type;         // copy of disk inode
  short major;
  short minor;
  short nlink;
  u32 size;
  u32 addrs[NDIRECT+1];

private:
  inode();
  ~inode();
  NEW_DELETE_OPS(inode)
};

#define I_BUSYR 0x1
#define I_BUSYW 0x2
#define I_VALID 0x4
#define I_FREE 0x8

// device implementations

struct devsw {
  int (*read)(struct inode*, char*, u32, u32);
  int (*write)(struct inode*, const char*, u32, u32);
  void (*stat)(struct inode*, struct stat*);
};

extern struct devsw devsw[];
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: strarray.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 12:27: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_svx.hxx"

#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif

// include ---------------------------------------------------------------

#include "dialogs.hrc" // -> RID_SVXSTR_LANGUAGE_TABLE
#include "dialmgr.hxx"
#include "strarray.hxx"

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

SvxStringArray::SvxStringArray( USHORT nResId ) :

    ResStringArray( SVX_RES( nResId ) )

{
}

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

SvxStringArray::SvxStringArray( const ResId& rResId ) :
    ResStringArray( rResId )
{
}

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

SvxStringArray::~SvxStringArray()
{
}

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

const String& SvxStringArray::GetStringByPos( USHORT nPos ) const
{
    if ( RESARRAY_INDEX_NOTFOUND != nPos && nPos < Count() )
        return ResStringArray::GetString( nPos );
    else
        return String::EmptyString();
}

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

const String& SvxStringArray::GetStringByType( long nType ) const
{
    sal_uInt32 nPos = FindIndex( nType );

    if ( RESARRAY_INDEX_NOTFOUND != nPos && nPos < Count() )
        return ResStringArray::GetString( nPos );
    else
        return String::EmptyString();
}

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

long SvxStringArray::GetValueByStr( const String& rStr ) const
{
    long nType = 0;
    sal_uInt32 nCount = Count();

    for ( sal_uInt32 i = 0; i < nCount; ++i )
        if ( rStr == ResStringArray::GetString( i ) )
        {
            nType = GetValue( i );
            break;
        }
    return nType;
}

<commit_msg>INTEGRATION: CWS residcleanup (1.5.230); FILE MERGED 2007/02/21 22:04:12 pl 1.5.230.1: #i74635# get rid of global ResMgr<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: strarray.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 07:43:39 $
 *
 *  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_svx.hxx"

#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif

// include ---------------------------------------------------------------

#include "dialogs.hrc" // -> RID_SVXSTR_LANGUAGE_TABLE
#include "dialmgr.hxx"
#include "strarray.hxx"

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

SvxStringArray::SvxStringArray( sal_uInt32 nResId ) :

    ResStringArray( SVX_RES( nResId ) )

{
}

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

SvxStringArray::SvxStringArray( const ResId& rResId ) :
    ResStringArray( rResId )
{
}

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

SvxStringArray::~SvxStringArray()
{
}

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

const String& SvxStringArray::GetStringByPos( sal_uInt32 nPos ) const
{
    if ( RESARRAY_INDEX_NOTFOUND != nPos && nPos < Count() )
        return ResStringArray::GetString( nPos );
    else
        return String::EmptyString();
}

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

const String& SvxStringArray::GetStringByType( long nType ) const
{
    sal_uInt32 nPos = FindIndex( nType );

    if ( RESARRAY_INDEX_NOTFOUND != nPos && nPos < Count() )
        return ResStringArray::GetString( nPos );
    else
        return String::EmptyString();
}

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

long SvxStringArray::GetValueByStr( const String& rStr ) const
{
    long nType = 0;
    sal_uInt32 nCount = Count();

    for ( sal_uInt32 i = 0; i < nCount; ++i )
        if ( rStr == ResStringArray::GetString( i ) )
        {
            nType = GetValue( i );
            break;
        }
    return nType;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: swafopt.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 17:01:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SV_KEYCODES_HXX //autogen
#include <vcl/keycodes.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#include "swafopt.hxx"

#if defined UNX

#if defined GCC
extern const sal_Char __FAR_DATA sBulletFntName[];
const sal_Char __FAR_DATA sBulletFntName[] = "starbats";
#else
extern const sal_Char __FAR_DATA sBulletFntName[] = "starbats";
#endif

#else
extern const sal_Char __FAR_DATA sBulletFntName[] = "StarBats";
#endif

// !! JP - 17.04.00: which value becomes this Bulletchar
//                   in the Unicode Version?
const sal_Char cBulletChar  = '\x95';   // character for Aufzaehlungen

/*------------------------------------------------------------------------
 Beschreibung:
------------------------------------------------------------------------*/

SvxSwAutoFmtFlags::SvxSwAutoFmtFlags()
    : aBulletFont( String( sBulletFntName, RTL_TEXTENCODING_MS_1252 ),
                    Size( 0, 14 ) )
{
    bReplaceQuote =
    bAutoCorrect =
    bCptlSttSntnc =
    bCptlSttWrd =
    bChkFontAttr =
    bChgUserColl =
    bChgEnumNum =
    bChgFracionSymbol =
    bChgOrdinalNumber =
    bChgToEnEmDash =
    bChgWeightUnderl =
    bSetINetAttr =
    bAFmtDelSpacesAtSttEnd =
    bAFmtDelSpacesBetweenLines =
    bAFmtByInpDelSpacesAtSttEnd =
    bAFmtByInpDelSpacesBetweenLines =
    bDummy = TRUE;

    bReplaceStyles =
    bDelEmptyNode =
    bWithRedlining =
    bAutoCmpltEndless =
    bAutoCmpltAppendBlanc =
    bAutoCmpltShowAsTip = FALSE;

    bSetBorder =
    bCreateTable =
    bSetNumRule =
    bAFmtByInput =
    bRightMargin =
    bAutoCompleteWords =
    bAutoCmpltCollectWords = TRUE;

    bDummy4 = bDummy5 = bDummy6 = bDummy7 = bDummy8 =
         FALSE;

    nRightMargin = 50;      // dflt. 50 %
    nAutoCmpltExpandKey = KEY_RETURN;

    aBulletFont.SetCharSet( RTL_TEXTENCODING_SYMBOL );
    aBulletFont.SetFamily( FAMILY_DONTKNOW );
    aBulletFont.SetPitch( PITCH_DONTKNOW );
    aBulletFont.SetWeight( WEIGHT_DONTKNOW );
    aBulletFont.SetTransparent( TRUE );

    cBullet = ByteString::ConvertToUnicode( cBulletChar,
                                            RTL_TEXTENCODING_SYMBOL );
    cByInputBullet = cBullet;
    aByInputBulletFont = aBulletFont;

    nAutoCmpltWordLen = 10;
    nAutoCmpltListLen = 500;
    pAutoCmpltList = 0;
}

SvxSwAutoFmtFlags& SvxSwAutoFmtFlags::operator=( const SvxSwAutoFmtFlags& rAFFlags )
{
    bAutoCorrect = rAFFlags.bAutoCorrect;
    bReplaceQuote = rAFFlags.bReplaceQuote;
    bCptlSttSntnc = rAFFlags.bCptlSttSntnc;
    bCptlSttWrd = rAFFlags.bCptlSttWrd;
    bChkFontAttr = rAFFlags.bChkFontAttr;

    bChgUserColl = rAFFlags.bChgUserColl;
    bChgEnumNum = rAFFlags.bChgEnumNum;
    bDelEmptyNode = rAFFlags.bDelEmptyNode;
    bSetNumRule = rAFFlags.bSetNumRule;
    bAFmtByInput = rAFFlags.bAFmtByInput;

    bChgFracionSymbol = rAFFlags.bChgFracionSymbol;
    bChgOrdinalNumber = rAFFlags.bChgOrdinalNumber;
    bChgToEnEmDash = rAFFlags.bChgToEnEmDash;
    bChgWeightUnderl = rAFFlags.bChgWeightUnderl;
    bSetINetAttr = rAFFlags.bSetINetAttr;
    bSetBorder = rAFFlags.bSetBorder;
    bCreateTable = rAFFlags.bCreateTable;
    bReplaceStyles = rAFFlags.bReplaceStyles;
    bAFmtDelSpacesAtSttEnd = rAFFlags.bAFmtDelSpacesAtSttEnd;
    bAFmtDelSpacesBetweenLines = rAFFlags.bAFmtDelSpacesBetweenLines;
    bAFmtByInpDelSpacesAtSttEnd = rAFFlags.bAFmtByInpDelSpacesAtSttEnd;
    bAFmtByInpDelSpacesBetweenLines = rAFFlags.bAFmtByInpDelSpacesBetweenLines;

    bDummy = rAFFlags.bDummy;

    bDummy4 = rAFFlags.bDummy4;
    bDummy5 = rAFFlags.bDummy5;
    bDummy6 = rAFFlags.bDummy6;
    bDummy7 = rAFFlags.bDummy7;
    bDummy8 = rAFFlags.bDummy8;

    bWithRedlining = rAFFlags.bWithRedlining;

    bRightMargin = rAFFlags.bRightMargin;
    nRightMargin = rAFFlags.nRightMargin;

    cBullet = rAFFlags.cBullet;
    aBulletFont = rAFFlags.aBulletFont;

    cByInputBullet = rAFFlags.cByInputBullet;
    aByInputBulletFont = rAFFlags.aByInputBulletFont;

    bAutoCompleteWords = rAFFlags.bAutoCompleteWords;
    bAutoCmpltCollectWords = rAFFlags.bAutoCmpltCollectWords;
    bAutoCmpltEndless = rAFFlags.bAutoCmpltEndless;
    bAutoCmpltAppendBlanc = rAFFlags.bAutoCmpltAppendBlanc;
    bAutoCmpltShowAsTip = rAFFlags.bAutoCmpltShowAsTip;
    pAutoCmpltList = rAFFlags.pAutoCmpltList;
    nAutoCmpltExpandKey = rAFFlags.nAutoCmpltExpandKey;

    nAutoCmpltWordLen = rAFFlags.nAutoCmpltWordLen;
    nAutoCmpltListLen = rAFFlags.nAutoCmpltListLen;

    return *this;
}

<commit_msg>Bug #9110#/#88107#: changes for StarBats -> StarSymbol<commit_after>/*************************************************************************
 *
 *  $RCSfile: swafopt.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: jp $ $Date: 2001-08-16 12:49:51 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SV_KEYCODES_HXX //autogen
#include <vcl/keycodes.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#include "swafopt.hxx"

/*------------------------------------------------------------------------
 Beschreibung:
------------------------------------------------------------------------*/

SvxSwAutoFmtFlags::SvxSwAutoFmtFlags()
    : aBulletFont( String::CreateFromAscii(
                        RTL_CONSTASCII_STRINGPARAM( "StarSymbol" )),
                    Size( 0, 14 ) )
{
    bReplaceQuote =
    bAutoCorrect =
    bCptlSttSntnc =
    bCptlSttWrd =
    bChkFontAttr =
    bChgUserColl =
    bChgEnumNum =
    bChgFracionSymbol =
    bChgOrdinalNumber =
    bChgToEnEmDash =
    bChgWeightUnderl =
    bSetINetAttr =
    bAFmtDelSpacesAtSttEnd =
    bAFmtDelSpacesBetweenLines =
    bAFmtByInpDelSpacesAtSttEnd =
    bAFmtByInpDelSpacesBetweenLines =
    bDummy = TRUE;

    bReplaceStyles =
    bDelEmptyNode =
    bWithRedlining =
    bAutoCmpltEndless =
    bAutoCmpltAppendBlanc =
    bAutoCmpltShowAsTip = FALSE;

    bSetBorder =
    bCreateTable =
    bSetNumRule =
    bAFmtByInput =
    bRightMargin =
    bAutoCompleteWords =
    bAutoCmpltCollectWords = TRUE;

    bDummy4 = bDummy5 = bDummy6 = bDummy7 = bDummy8 =
         FALSE;

    nRightMargin = 50;      // dflt. 50 %
    nAutoCmpltExpandKey = KEY_RETURN;

    aBulletFont.SetCharSet( RTL_TEXTENCODING_SYMBOL );
    aBulletFont.SetFamily( FAMILY_DONTKNOW );
    aBulletFont.SetPitch( PITCH_DONTKNOW );
    aBulletFont.SetWeight( WEIGHT_DONTKNOW );
    aBulletFont.SetTransparent( TRUE );

    cBullet = 0x2022;
    cByInputBullet = cBullet;
    aByInputBulletFont = aBulletFont;

    nAutoCmpltWordLen = 10;
    nAutoCmpltListLen = 500;
    pAutoCmpltList = 0;
}

SvxSwAutoFmtFlags& SvxSwAutoFmtFlags::operator=( const SvxSwAutoFmtFlags& rAFFlags )
{
    bAutoCorrect = rAFFlags.bAutoCorrect;
    bReplaceQuote = rAFFlags.bReplaceQuote;
    bCptlSttSntnc = rAFFlags.bCptlSttSntnc;
    bCptlSttWrd = rAFFlags.bCptlSttWrd;
    bChkFontAttr = rAFFlags.bChkFontAttr;

    bChgUserColl = rAFFlags.bChgUserColl;
    bChgEnumNum = rAFFlags.bChgEnumNum;
    bDelEmptyNode = rAFFlags.bDelEmptyNode;
    bSetNumRule = rAFFlags.bSetNumRule;
    bAFmtByInput = rAFFlags.bAFmtByInput;

    bChgFracionSymbol = rAFFlags.bChgFracionSymbol;
    bChgOrdinalNumber = rAFFlags.bChgOrdinalNumber;
    bChgToEnEmDash = rAFFlags.bChgToEnEmDash;
    bChgWeightUnderl = rAFFlags.bChgWeightUnderl;
    bSetINetAttr = rAFFlags.bSetINetAttr;
    bSetBorder = rAFFlags.bSetBorder;
    bCreateTable = rAFFlags.bCreateTable;
    bReplaceStyles = rAFFlags.bReplaceStyles;
    bAFmtDelSpacesAtSttEnd = rAFFlags.bAFmtDelSpacesAtSttEnd;
    bAFmtDelSpacesBetweenLines = rAFFlags.bAFmtDelSpacesBetweenLines;
    bAFmtByInpDelSpacesAtSttEnd = rAFFlags.bAFmtByInpDelSpacesAtSttEnd;
    bAFmtByInpDelSpacesBetweenLines = rAFFlags.bAFmtByInpDelSpacesBetweenLines;

    bDummy = rAFFlags.bDummy;

    bDummy4 = rAFFlags.bDummy4;
    bDummy5 = rAFFlags.bDummy5;
    bDummy6 = rAFFlags.bDummy6;
    bDummy7 = rAFFlags.bDummy7;
    bDummy8 = rAFFlags.bDummy8;

    bWithRedlining = rAFFlags.bWithRedlining;

    bRightMargin = rAFFlags.bRightMargin;
    nRightMargin = rAFFlags.nRightMargin;

    cBullet = rAFFlags.cBullet;
    aBulletFont = rAFFlags.aBulletFont;

    cByInputBullet = rAFFlags.cByInputBullet;
    aByInputBulletFont = rAFFlags.aByInputBulletFont;

    bAutoCompleteWords = rAFFlags.bAutoCompleteWords;
    bAutoCmpltCollectWords = rAFFlags.bAutoCmpltCollectWords;
    bAutoCmpltEndless = rAFFlags.bAutoCmpltEndless;
    bAutoCmpltAppendBlanc = rAFFlags.bAutoCmpltAppendBlanc;
    bAutoCmpltShowAsTip = rAFFlags.bAutoCmpltShowAsTip;
    pAutoCmpltList = rAFFlags.pAutoCmpltList;
    nAutoCmpltExpandKey = rAFFlags.nAutoCmpltExpandKey;

    nAutoCmpltWordLen = rAFFlags.nAutoCmpltWordLen;
    nAutoCmpltListLen = rAFFlags.nAutoCmpltListLen;

    return *this;
}

<|endoftext|>


<commit_before><commit_msg>-Werror,-Wunused-const-variable<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: porexp.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: fme $ $Date: 2002-02-28 12:42:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _POREXP_HXX
#define _POREXP_HXX

#include "portxt.hxx"

/*************************************************************************
 *                      class SwExpandPortion
 *************************************************************************/

class SwExpandPortion : public SwTxtPortion
{
public:
    inline  SwExpandPortion() { SetWhichPor( POR_EXP ); }
    virtual sal_Bool Format( SwTxtFormatInfo &rInf );
    virtual xub_StrLen GetCrsrOfst( const MSHORT nOfst ) const;
    virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
    virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const;
    virtual void Paint( const SwTxtPaintInfo &rInf ) const;

    // Accessibility: pass information about this portion to the PortionHandler
    virtual void HandlePortion( SwPortionHandler& rPH ) const;

    OUTPUT_OPERATOR
};

/*************************************************************************
 *                      class SwBlankPortion
 *************************************************************************/

class SwBlankPortion : public SwExpandPortion
{
    xub_Unicode cChar;
    BOOL bMulti;        // For multiportion brackets
public:
    inline  SwBlankPortion( xub_Unicode cCh, BOOL bMult = sal_False )
        : cChar( cCh ), bMulti( bMult )
        { cChar = cCh; SetLen(1); SetWhichPor( POR_BLANK ); }

    BOOL IsMulti() const { return bMulti; }
    void SetMulti( BOOL bNew ) { bMulti = bNew; }

    virtual SwLinePortion *Compress();
    virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
    virtual void FormatEOL( SwTxtFormatInfo &rInf );
    virtual sal_Bool Format( SwTxtFormatInfo &rInf );
    virtual void Paint( const SwTxtPaintInfo &rInf ) const;
    MSHORT MayUnderFlow( const SwTxtFormatInfo &rInf, xub_StrLen nIdx,
        sal_Bool bUnderFlow ) const;

    // Accessibility: pass information about this portion to the PortionHandler
    virtual void HandlePortion( SwPortionHandler& rPH ) const;

    OUTPUT_OPERATOR
};

/*************************************************************************
 *                      class SwPostItsPortion
 *************************************************************************/

class SwPostItsPortion : public SwExpandPortion
{
    KSHORT  nViewWidth;
    sal_Bool    bScript;
public:
            SwPostItsPortion( sal_Bool bScrpt );
    virtual void Paint( const SwTxtPaintInfo &rInf ) const;
    virtual sal_Bool Format( SwTxtFormatInfo &rInf );
    virtual KSHORT GetViewWidth( const SwTxtSizeInfo &rInf ) const;
    virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
    sal_Bool IsScript() const { return bScript; }
    OUTPUT_OPERATOR
};

CLASSIO( SwExpandPortion )
CLASSIO( SwBlankPortion )
CLASSIO( SwPostItsPortion )

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.1426); FILE MERGED 2005/09/05 13:40:54 rt 1.5.1426.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: porexp.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 04:57:24 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _POREXP_HXX
#define _POREXP_HXX

#include "portxt.hxx"

/*************************************************************************
 *                      class SwExpandPortion
 *************************************************************************/

class SwExpandPortion : public SwTxtPortion
{
public:
    inline  SwExpandPortion() { SetWhichPor( POR_EXP ); }
    virtual sal_Bool Format( SwTxtFormatInfo &rInf );
    virtual xub_StrLen GetCrsrOfst( const MSHORT nOfst ) const;
    virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
    virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const;
    virtual void Paint( const SwTxtPaintInfo &rInf ) const;

    // Accessibility: pass information about this portion to the PortionHandler
    virtual void HandlePortion( SwPortionHandler& rPH ) const;

    OUTPUT_OPERATOR
};

/*************************************************************************
 *                      class SwBlankPortion
 *************************************************************************/

class SwBlankPortion : public SwExpandPortion
{
    xub_Unicode cChar;
    BOOL bMulti;        // For multiportion brackets
public:
    inline  SwBlankPortion( xub_Unicode cCh, BOOL bMult = sal_False )
        : cChar( cCh ), bMulti( bMult )
        { cChar = cCh; SetLen(1); SetWhichPor( POR_BLANK ); }

    BOOL IsMulti() const { return bMulti; }
    void SetMulti( BOOL bNew ) { bMulti = bNew; }

    virtual SwLinePortion *Compress();
    virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
    virtual void FormatEOL( SwTxtFormatInfo &rInf );
    virtual sal_Bool Format( SwTxtFormatInfo &rInf );
    virtual void Paint( const SwTxtPaintInfo &rInf ) const;
    MSHORT MayUnderFlow( const SwTxtFormatInfo &rInf, xub_StrLen nIdx,
        sal_Bool bUnderFlow ) const;

    // Accessibility: pass information about this portion to the PortionHandler
    virtual void HandlePortion( SwPortionHandler& rPH ) const;

    OUTPUT_OPERATOR
};

/*************************************************************************
 *                      class SwPostItsPortion
 *************************************************************************/

class SwPostItsPortion : public SwExpandPortion
{
    KSHORT  nViewWidth;
    sal_Bool    bScript;
public:
            SwPostItsPortion( sal_Bool bScrpt );
    virtual void Paint( const SwTxtPaintInfo &rInf ) const;
    virtual sal_Bool Format( SwTxtFormatInfo &rInf );
    virtual KSHORT GetViewWidth( const SwTxtSizeInfo &rInf ) const;
    virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
    sal_Bool IsScript() const { return bScript; }
    OUTPUT_OPERATOR
};

CLASSIO( SwExpandPortion )
CLASSIO( SwBlankPortion )
CLASSIO( SwPostItsPortion )

#endif
<|endoftext|>