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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkGeometry2DDataVtkMapper3D.h"
#include "mitkPlaneGeometry.h"
#include "mitkDataTree.h"
#include "mitkImageMapper2D.h"
#include "mitkSurface.h"
#include "mitkGeometry2DDataToSurfaceFilter.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkLookupTableProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkSmartPointerProperty.h"
#include "mitkWeakPointerProperty.h"

#include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkTexture.h>
#include <vtkPlaneSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyData.h>
#include <vtkLookupTable.h>
#include <vtkActor.h>
#include <vtkImageData.h>
#include <vtkLinearTransform.h>
#include <vtkAssembly.h>
#include <vtkFeatureEdges.h>
#include <vtkTubeFilter.h>

#include "pic2vtk.h"

//##ModelId=3E691E09038E
mitk::Geometry2DDataVtkMapper3D::Geometry2DDataVtkMapper3D() : m_DataTreeIterator(NULL), m_LastTextureUpdateTime(0)
{
  m_VtkPolyDataMapper = vtkPolyDataMapper::New();
  m_VtkPolyDataMapper->ImmediateModeRenderingOn();

  m_ImageActor = vtkActor::New();
  m_ImageActor->SetMapper(m_VtkPolyDataMapper);
  m_ImageActor->GetProperty()->SetAmbient(0.5);

  m_VtkLookupTable = vtkLookupTable::New();
  m_VtkLookupTable->SetTableRange (-1024, 4096);
  m_VtkLookupTable->SetSaturationRange (0, 0);
  m_VtkLookupTable->SetHueRange (0, 0);
  m_VtkLookupTable->SetValueRange (0, 1);
  m_VtkLookupTable->Build ();

  m_VtkLookupTableDefault = m_VtkLookupTable;

  m_VtkTexture = vtkTexture::New();
  m_VtkTexture->InterpolateOn();
  m_VtkTexture->SetLookupTable(m_VtkLookupTable);
  m_VtkTexture->MapColorScalarsThroughLookupTableOn();

  m_EdgeTuber = vtkTubeFilter::New();
  m_EdgeMapper = vtkPolyDataMapper::New();
  m_Edges = vtkFeatureEdges::New();
  m_EdgeActor = vtkActor::New();

  m_EdgeTuber->SetInput( m_Edges->GetOutput() );
  m_EdgeTuber->SetNumberOfSides( 12 );
  m_EdgeTuber->CappingOn();

  m_EdgeMapper->SetInput( m_EdgeTuber->GetOutput() );
  m_EdgeMapper->ScalarVisibilityOff();

  m_EdgeActor->SetMapper( m_EdgeMapper );

  m_Prop3DAssembly = vtkAssembly::New();
  m_Prop3DAssembly->AddPart( m_ImageActor );
  m_Prop3DAssembly->AddPart( m_EdgeActor );

  m_Prop3D = m_Prop3DAssembly;
  m_Prop3D->Register(NULL);
}

//##ModelId=3E691E090394
mitk::Geometry2DDataVtkMapper3D::~Geometry2DDataVtkMapper3D()
{
  m_VtkPolyDataMapper->Delete();
  m_Prop3DAssembly->Delete();
  m_ImageActor->Delete();
  m_VtkLookupTable->Delete();
  m_VtkTexture->Delete();
  m_EdgeTuber->Delete();
  m_EdgeMapper->Delete();
  m_Edges->Delete();
  m_EdgeActor->Delete();
}

//##ModelId=3E691E090380
const mitk::Geometry2DData *mitk::Geometry2DDataVtkMapper3D::GetInput()
{
  return static_cast<const mitk::Geometry2DData * > ( GetData() );
}

//##ModelId=3E6E874F0007
void mitk::Geometry2DDataVtkMapper3D::SetDataIteratorForTexture(const mitk::DataTreeIteratorBase* iterator)
{
  if(m_DataTreeIterator != iterator)
  {
    m_DataTreeIterator = iterator;
    Modified();
  }
}

//##ModelId=3EF19F850151
void mitk::Geometry2DDataVtkMapper3D::GenerateData(mitk::BaseRenderer* renderer)
{
  if ( !this->IsVisible(renderer) )
  {
    m_Prop3DAssembly->VisibilityOff();
    return;
  }

  m_Prop3DAssembly->VisibilityOn();

  mitk::Geometry2DData::Pointer input  = const_cast<mitk::Geometry2DData*>(this->GetInput());

  if(input.IsNotNull() && (input->GetGeometry2D() != NULL))
  {
    mitk::Geometry2DDataToSurfaceFilter::Pointer surfaceCreator;
    mitk::SmartPointerProperty::Pointer surfacecreatorprop;
    surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty("surfacegeometry", renderer).GetPointer());
    if( (surfacecreatorprop.IsNull()) ||
      (surfacecreatorprop->GetSmartPointer().IsNull()) ||
      ((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull())
      )
    {
      surfaceCreator = mitk::Geometry2DDataToSurfaceFilter::New();
      surfaceCreator->PlaceByGeometryOn();
      surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);
      GetDataTreeNode()->SetProperty("surfacegeometry", surfacecreatorprop);
    }

    surfaceCreator->SetInput(input);

    int res;
    if(GetDataTreeNode()->GetIntProperty("xresolution", res, renderer))
      surfaceCreator->SetXResolution(res);
    if(GetDataTreeNode()->GetIntProperty("yresolution", res, renderer))
      surfaceCreator->SetYResolution(res);

    surfaceCreator->Update(); //@FIXME ohne das crash
    m_VtkPolyDataMapper->SetInput(surfaceCreator->GetOutput()->GetVtkPolyData());

    bool texture=false;
    if(m_DataTreeIterator.IsNotNull())
    {
      mitk::DataTreeIteratorClone it=m_DataTreeIterator.GetPointer();
      while(!it->IsAtEnd())
      {
        mitk::DataTreeNode* node=it->Get();
        if ( node != NULL )
        {
          mitk::Mapper::Pointer mapper = node->GetMapper(1);
          mitk::ImageMapper2D* imagemapper = dynamic_cast<ImageMapper2D*>(mapper.GetPointer());

          if((node->IsVisible(renderer)) && (imagemapper))
          {
            mitk::WeakPointerProperty::Pointer rendererProp
                                                = dynamic_cast<mitk::WeakPointerProperty*>(GetDataTreeNode()->GetPropertyList()->GetProperty("renderer").GetPointer());
            if(rendererProp.IsNotNull())
            {
              mitk::BaseRenderer::Pointer renderer = dynamic_cast<mitk::BaseRenderer*>(rendererProp->GetWeakPointer().GetPointer());
              if(renderer.IsNotNull())
              {
                bool useColor = true;

                // check for "use color"
                node->GetBoolProperty("use color", useColor, renderer);

                // check for LookupTable
                mitk::LookupTableProperty::Pointer lookupTableProp;
                lookupTableProp = dynamic_cast<mitk::LookupTableProperty*>(node->GetPropertyList()->GetProperty("LookupTable").GetPointer());
                if (lookupTableProp.IsNotNull() && !useColor)
                {
                  m_VtkLookupTable = lookupTableProp->GetLookupTable()->GetVtkLookupTable();
                  m_VtkTexture->SetLookupTable(m_VtkLookupTable);
                  // m_VtkTexture->Modified();
                } else {
                  m_VtkLookupTable = m_VtkLookupTableDefault;
                }

                // check for level window prop and use it for display if it exists
                mitk::LevelWindow levelWindow;
                if(node->GetLevelWindow(levelWindow, renderer))
                  m_VtkLookupTable->SetTableRange(levelWindow.GetMin(),levelWindow.GetMax());

                //we have to do this before GenerateAllData() is called there may be
                //no RendererInfo for renderer yet, thus GenerateAllData won't update
                //the (non-existing) RendererInfo for renderer. By calling GetRendererInfo
                //a RendererInfo will be created for renderer (if it does not exist yet).
                const ImageMapper2D::RendererInfo* ri=imagemapper->GetRendererInfo(renderer);
                imagemapper->GenerateAllData();
                texture = true;
                if((ri!=NULL) && (ri->m_Pic!=NULL) &&(m_LastTextureUpdateTime<ri->m_LastUpdateTime))
                {
                  ipPicDescriptor *p=ri->m_Pic;
                  if((p->dim==2) && (p->n[0]>2) && (p->n[1]>2))
                  {
                    vtkImageData* vtkimage=Pic2vtk::convert(p);
                    m_VtkTexture->SetInput(vtkimage);
                    vtkimage->Delete(); vtkimage=NULL;
                    m_ImageActor->SetTexture(m_VtkTexture);
                    m_LastTextureUpdateTime=ri->m_LastUpdateTime;
                    bool textureInterpolation=true;
                    m_VtkTexture->SetInterpolate(textureInterpolation ? 1 : 0);
                  }
                  else
                    texture = false;
                }
                break;
              }
            }
          }
        }
        ++it;
      }
    }
    if(texture==false)
    {
      m_ImageActor->SetTexture(NULL);
    }

    // Configurate the tube-shaped frame: size according to the surface
    // bounds, color as specified in the plane's properties
    vtkPolyData* surfacePolyData = surfaceCreator->GetOutput()->GetVtkPolyData();
    m_Edges->SetInput( surfacePolyData );

    // Determine maximum extent
    vtkFloatingPointType* surfaceBounds = surfacePolyData->GetBounds();
    vtkFloatingPointType extent = surfaceBounds[1] - surfaceBounds[0];
    vtkFloatingPointType extentY = surfaceBounds[3] - surfaceBounds[2];
    vtkFloatingPointType extentZ = surfaceBounds[5] - surfaceBounds[4];

    if ( extent < extentY ) extent = extentY;
    if ( extent < extentZ ) extent = extentZ;

    // Adjust the radius according to extent
    m_EdgeTuber->SetRadius( extent / 250.0 );

    // Get the plane's color and set the tube properties accordingly
    mitk::ColorProperty::Pointer colorProperty;
    colorProperty = dynamic_cast<mitk::ColorProperty*>(
      this->GetDataTreeNode()->GetProperty("color").GetPointer( )
    );
    if ( colorProperty.IsNotNull() )
    {
      const mitk::Color& color = colorProperty->GetColor();
      m_EdgeActor->GetProperty()->SetColor(
        color.GetRed(), color.GetGreen(), color.GetBlue()
      );
    }
    else
    {
      m_EdgeActor->GetProperty()->SetColor( 1.0, 1.0, 1.0 );
    }

    // Apply properties read from the PropertyList
    this->ApplyProperties(m_ImageActor, renderer);

    m_Prop3D->SetUserTransform(GetDataTreeNode()->GetVtkTransform());
  }
}
<commit_msg>FIX: visibility has to be set explicitly for each member of the vtkPropAssembly. Otherwise cell picking hits the rendered object, even if its assembly is set to invisible.<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkGeometry2DDataVtkMapper3D.h"
#include "mitkPlaneGeometry.h"
#include "mitkDataTree.h"
#include "mitkImageMapper2D.h"
#include "mitkSurface.h"
#include "mitkGeometry2DDataToSurfaceFilter.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkLookupTableProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkSmartPointerProperty.h"
#include "mitkWeakPointerProperty.h"

#include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkTexture.h>
#include <vtkPlaneSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyData.h>
#include <vtkLookupTable.h>
#include <vtkActor.h>
#include <vtkImageData.h>
#include <vtkLinearTransform.h>
#include <vtkAssembly.h>
#include <vtkFeatureEdges.h>
#include <vtkTubeFilter.h>

#include "pic2vtk.h"

//##ModelId=3E691E09038E
mitk::Geometry2DDataVtkMapper3D::Geometry2DDataVtkMapper3D() : m_DataTreeIterator(NULL), m_LastTextureUpdateTime(0)
{
  m_VtkPolyDataMapper = vtkPolyDataMapper::New();
  m_VtkPolyDataMapper->ImmediateModeRenderingOn();

  m_ImageActor = vtkActor::New();
  m_ImageActor->SetMapper(m_VtkPolyDataMapper);
  m_ImageActor->GetProperty()->SetAmbient(0.5);

  m_VtkLookupTable = vtkLookupTable::New();
  m_VtkLookupTable->SetTableRange (-1024, 4096);
  m_VtkLookupTable->SetSaturationRange (0, 0);
  m_VtkLookupTable->SetHueRange (0, 0);
  m_VtkLookupTable->SetValueRange (0, 1);
  m_VtkLookupTable->Build ();

  m_VtkLookupTableDefault = m_VtkLookupTable;

  m_VtkTexture = vtkTexture::New();
  m_VtkTexture->InterpolateOn();
  m_VtkTexture->SetLookupTable(m_VtkLookupTable);
  m_VtkTexture->MapColorScalarsThroughLookupTableOn();

  m_EdgeTuber = vtkTubeFilter::New();
  m_EdgeMapper = vtkPolyDataMapper::New();
  m_Edges = vtkFeatureEdges::New();
  m_EdgeActor = vtkActor::New();

  m_EdgeTuber->SetInput( m_Edges->GetOutput() );
  m_EdgeTuber->SetNumberOfSides( 12 );
  m_EdgeTuber->CappingOn();

  m_EdgeMapper->SetInput( m_EdgeTuber->GetOutput() );
  m_EdgeMapper->ScalarVisibilityOff();

  m_EdgeActor->SetMapper( m_EdgeMapper );

  m_Prop3DAssembly = vtkAssembly::New();
  m_Prop3DAssembly->AddPart( m_ImageActor );
  m_Prop3DAssembly->AddPart( m_EdgeActor );

  m_Prop3D = m_Prop3DAssembly;
  m_Prop3D->Register(NULL);
}

//##ModelId=3E691E090394
mitk::Geometry2DDataVtkMapper3D::~Geometry2DDataVtkMapper3D()
{
  m_VtkPolyDataMapper->Delete();
  m_Prop3DAssembly->Delete();
  m_ImageActor->Delete();
  m_VtkLookupTable->Delete();
  m_VtkTexture->Delete();
  m_EdgeTuber->Delete();
  m_EdgeMapper->Delete();
  m_Edges->Delete();
  m_EdgeActor->Delete();
}

//##ModelId=3E691E090380
const mitk::Geometry2DData *mitk::Geometry2DDataVtkMapper3D::GetInput()
{
  return static_cast<const mitk::Geometry2DData * > ( GetData() );
}

//##ModelId=3E6E874F0007
void mitk::Geometry2DDataVtkMapper3D::SetDataIteratorForTexture(const mitk::DataTreeIteratorBase* iterator)
{
  if(m_DataTreeIterator != iterator)
  {
    m_DataTreeIterator = iterator;
    Modified();
  }
}

//##ModelId=3EF19F850151
void mitk::Geometry2DDataVtkMapper3D::GenerateData(mitk::BaseRenderer* renderer)
{
  if ( !this->IsVisible(renderer) )
  {
    m_Prop3DAssembly->VisibilityOff();
    // visibility has explicitly to be set in the single actors
    // due to problems when using cell picking:
    // even if the assembly is invisible, the renderer contains
    // references to the assemblies parts. During picking the
    // visibility of each part is checked, and not only for the
    // whole assembly.
    m_ImageActor->VisibilityOff();
    m_EdgeActor->VisibilityOff();
    return;
  }

  m_Prop3DAssembly->VisibilityOn();
  // visibility has explicitly to be set in the single actors
  // due to problems when using cell picking:
  // even if the assembly is invisible, the renderer contains
  // references to the assemblies parts. During picking the
  // visibility of each part is checked, and not only for the
  // whole assembly.
  m_ImageActor->VisibilityOn();
  m_EdgeActor->VisibilityOn();

  mitk::Geometry2DData::Pointer input  = const_cast<mitk::Geometry2DData*>(this->GetInput());

  if(input.IsNotNull() && (input->GetGeometry2D() != NULL))
  {
    mitk::Geometry2DDataToSurfaceFilter::Pointer surfaceCreator;
    mitk::SmartPointerProperty::Pointer surfacecreatorprop;
    surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty("surfacegeometry", renderer).GetPointer());
    if( (surfacecreatorprop.IsNull()) ||
      (surfacecreatorprop->GetSmartPointer().IsNull()) ||
      ((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull())
      )
    {
      surfaceCreator = mitk::Geometry2DDataToSurfaceFilter::New();
      surfaceCreator->PlaceByGeometryOn();
      surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);
      GetDataTreeNode()->SetProperty("surfacegeometry", surfacecreatorprop);
    }

    surfaceCreator->SetInput(input);

    int res;
    if(GetDataTreeNode()->GetIntProperty("xresolution", res, renderer))
      surfaceCreator->SetXResolution(res);
    if(GetDataTreeNode()->GetIntProperty("yresolution", res, renderer))
      surfaceCreator->SetYResolution(res);

    surfaceCreator->Update(); //@FIXME ohne das crash
    m_VtkPolyDataMapper->SetInput(surfaceCreator->GetOutput()->GetVtkPolyData());

    bool texture=false;
    if(m_DataTreeIterator.IsNotNull())
    {
      mitk::DataTreeIteratorClone it=m_DataTreeIterator.GetPointer();
      while(!it->IsAtEnd())
      {
        mitk::DataTreeNode* node=it->Get();
        if ( node != NULL )
        {
          mitk::Mapper::Pointer mapper = node->GetMapper(1);
          mitk::ImageMapper2D* imagemapper = dynamic_cast<ImageMapper2D*>(mapper.GetPointer());

          if((node->IsVisible(renderer)) && (imagemapper))
          {
            mitk::WeakPointerProperty::Pointer rendererProp
                                                = dynamic_cast<mitk::WeakPointerProperty*>(GetDataTreeNode()->GetPropertyList()->GetProperty("renderer").GetPointer());
            if(rendererProp.IsNotNull())
            {
              mitk::BaseRenderer::Pointer renderer = dynamic_cast<mitk::BaseRenderer*>(rendererProp->GetWeakPointer().GetPointer());
              if(renderer.IsNotNull())
              {
                bool useColor = true;

                // check for "use color"
                node->GetBoolProperty("use color", useColor, renderer);

                // check for LookupTable
                mitk::LookupTableProperty::Pointer lookupTableProp;
                lookupTableProp = dynamic_cast<mitk::LookupTableProperty*>(node->GetPropertyList()->GetProperty("LookupTable").GetPointer());
                if (lookupTableProp.IsNotNull() && !useColor)
                {
                  m_VtkLookupTable = lookupTableProp->GetLookupTable()->GetVtkLookupTable();
                  m_VtkTexture->SetLookupTable(m_VtkLookupTable);
                  // m_VtkTexture->Modified();
                } else {
                  m_VtkLookupTable = m_VtkLookupTableDefault;
                }

                // check for level window prop and use it for display if it exists
                mitk::LevelWindow levelWindow;
                if(node->GetLevelWindow(levelWindow, renderer))
                  m_VtkLookupTable->SetTableRange(levelWindow.GetMin(),levelWindow.GetMax());

                //we have to do this before GenerateAllData() is called there may be
                //no RendererInfo for renderer yet, thus GenerateAllData won't update
                //the (non-existing) RendererInfo for renderer. By calling GetRendererInfo
                //a RendererInfo will be created for renderer (if it does not exist yet).
                const ImageMapper2D::RendererInfo* ri=imagemapper->GetRendererInfo(renderer);
                imagemapper->GenerateAllData();
                texture = true;
                if((ri!=NULL) && (ri->m_Pic!=NULL) &&(m_LastTextureUpdateTime<ri->m_LastUpdateTime))
                {
                  ipPicDescriptor *p=ri->m_Pic;
                  if((p->dim==2) && (p->n[0]>2) && (p->n[1]>2))
                  {
                    vtkImageData* vtkimage=Pic2vtk::convert(p);
                    m_VtkTexture->SetInput(vtkimage);
                    vtkimage->Delete(); vtkimage=NULL;
                    m_ImageActor->SetTexture(m_VtkTexture);
                    m_LastTextureUpdateTime=ri->m_LastUpdateTime;
                    bool textureInterpolation=true;
                    m_VtkTexture->SetInterpolate(textureInterpolation ? 1 : 0);
                  }
                  else
                    texture = false;
                }
                break;
              }
            }
          }
        }
        ++it;
      }
    }
    if(texture==false)
    {
      m_ImageActor->SetTexture(NULL);
    }

    // Configurate the tube-shaped frame: size according to the surface
    // bounds, color as specified in the plane's properties
    vtkPolyData* surfacePolyData = surfaceCreator->GetOutput()->GetVtkPolyData();
    m_Edges->SetInput( surfacePolyData );

    // Determine maximum extent
    vtkFloatingPointType* surfaceBounds = surfacePolyData->GetBounds();
    vtkFloatingPointType extent = surfaceBounds[1] - surfaceBounds[0];
    vtkFloatingPointType extentY = surfaceBounds[3] - surfaceBounds[2];
    vtkFloatingPointType extentZ = surfaceBounds[5] - surfaceBounds[4];

    if ( extent < extentY ) extent = extentY;
    if ( extent < extentZ ) extent = extentZ;

    // Adjust the radius according to extent
    m_EdgeTuber->SetRadius( extent / 250.0 );

    // Get the plane's color and set the tube properties accordingly
    mitk::ColorProperty::Pointer colorProperty;
    colorProperty = dynamic_cast<mitk::ColorProperty*>(
      this->GetDataTreeNode()->GetProperty("color").GetPointer( )
    );
    if ( colorProperty.IsNotNull() )
    {
      const mitk::Color& color = colorProperty->GetColor();
      m_EdgeActor->GetProperty()->SetColor(
        color.GetRed(), color.GetGreen(), color.GetBlue()
      );
    }
    else
    {
      m_EdgeActor->GetProperty()->SetColor( 1.0, 1.0, 1.0 );
    }

    // Apply properties read from the PropertyList
    this->ApplyProperties(m_ImageActor, renderer);

    m_Prop3D->SetUserTransform(GetDataTreeNode()->GetVtkTransform());
  }
}
<|endoftext|>


<commit_before>#include "remote_client.h"
#include "../model/entity.h"
#include "../model/board.h"
#include "../model/game.h"
#include "../socket/socket.h"

#include <iostream>
#include <sstream>

using namespace std;

void RemoteClient::setFrame() {
	auto board = owner.getBoard();
	if (board) {
		frame = board->getFrame();
	}
}

void RemoteClient::update() {
	auto board = this->owner.getBoard();
	deletedMutex.lock();
	board->mapEntities([this](shared_ptr<Entity> e) {
			if (e->getDeletable()) {
				deleted.push(e->getId());
			}
		});
	setFrame();
	deletedMutex.unlock();
	if (!running) {
		running = true;
		th = thread(&RemoteClient::run, this);
	}
}

RemoteClient::RemoteClient(Game& owner, Player& player, shared_ptr<Socket> socket) :
	AClient(owner, player), running(false), socket(socket)
{
	setFrame();
}

void RemoteClient::run() {
	auto& board = *owner.getBoard();
	ostream& out = cout;
	istream& in = cin;
	out << "+\t" << frame
		<< '\t' << player.getId() << '\t' << board.getPlayers().size()
		<< '\t' << board.name << endl;

	for(auto& p : board.getPlayers()) {
		out << p->serialize();
	}
	out << "T\t" << board.sizeX << '\t' << board.sizeY<< endl;
	// TODO: EntityFactories
	for(size_t x = board.sizeX - 1; x > 0; x--) {
		for(size_t y = board.sizeY - 1; y > 0; y--) {
			auto e = board.getTerrain(x, y);
			out << e->serialize();
		}
	}
	out << "T" << endl;
	out << "Entities";
	board.mapEntities([&out](shared_ptr<Entity> e) {out << e->serialize();});
	string command;
	while (!(command == "L" || in.eof() || this->owner.willExit())) {
		bool ack = false;
		cerr << endl << ">";
		stringstream answer;
		in >> command;
		if (command == "L") {
			ack = true;
		} else if (command == "S") {
			int i;
			in >> i;
			auto e = board.findEntity(i);
			if(e) {
				if (&(e->owner) == &(this->player)) {
					board.pushCommand(make_shared<StopCommand>(e->getId()));
					ack = true;
				}
			}
		} else if (command == "M") {
			int i;
			double x, y;
			in >> i >> x >> y;
			if (!this->owner.willExit()) {
				auto e = board.findEntity(i);
				if (e) {
					if (&(e->owner) == &(this->player)) {
						board.pushCommand(make_shared<MoveCommand>(e->getId(), r2(x, y)));
						ack = true;
					}
				}
			}
		} else if (command == "U") {
			size_t frame;
			in >> frame;
			answer << this->frame << '\t';
			board.mapEntities([this, &answer, frame](shared_ptr<Entity> e) {
					if (e->getFrame() > frame) {
					answer << e->serialize();
					}
					});
			for(auto& p : board.getPlayers()) {
				if (p->getFrame() > frame) {
					answer << p->serialize();
				}
			}
			deletedMutex.lock();
			while (deleted.size() > 0) {
				answer << "D\t" << deleted.front() << endl;
				deleted.pop();
			}
			deletedMutex.unlock();
			ack = true;
		}
		string payload;
		if (ack) {
			payload = "+" + answer.str() + "\n";
		} else {
			payload = "-\n";
		}
		out << payload;
	}
}

RemoteClient::~RemoteClient() {
	if(running) {
		th.join();
	}
}
<commit_msg>Tee a socket<commit_after>#include "remote_client.h"
#include "../model/entity.h"
#include "../model/board.h"
#include "../model/game.h"
#include "../socket/socket.h"

#include <iostream>
#include <sstream>

using namespace std;

void RemoteClient::setFrame() {
	auto board = owner.getBoard();
	if (board) {
		frame = board->getFrame();
	}
}

void RemoteClient::update() {
	auto board = this->owner.getBoard();
	deletedMutex.lock();
	board->mapEntities([this](shared_ptr<Entity> e) {
			if (e->getDeletable()) {
				deleted.push(e->getId());
			}
		});
	setFrame();
	deletedMutex.unlock();
	if (!running) {
		running = true;
		th = thread(&RemoteClient::run, this);
	}
}

RemoteClient::RemoteClient(Game& owner, Player& player, shared_ptr<Socket> socket) :
	AClient(owner, player), running(false), socket(socket)
{
	setFrame();
}

void RemoteClient::run() {
	auto& board = *owner.getBoard();
	stringstream out;
	istream& in = cin;
	out << "+\t" << frame
		<< '\t' << player.getId() << '\t' << board.getPlayers().size()
		<< '\t' << board.name << endl;

	for(auto& p : board.getPlayers()) {
		out << p->serialize();
	}
	out << "T\t" << board.sizeX << '\t' << board.sizeY<< endl;
	// TODO: EntityFactories
	for(size_t x = board.sizeX - 1; x > 0; x--) {
		for(size_t y = board.sizeY - 1; y > 0; y--) {
			auto e = board.getTerrain(x, y);
			out << e->serialize();
		}
	}
	out << "T" << endl;
	out << "Entities";
	board.mapEntities([&out](shared_ptr<Entity> e) {out << e->serialize();});
	string payload = out.str();
	socket->Send((void*)payload.c_str(), payload.length());
	cout << payload;
	string command;
	while (!(command == "L" || in.eof() || this->owner.willExit())) {
		bool ack = false;
		cerr << endl << ">";
		stringstream answer;
		in >> command;
		if (command == "L") {
			ack = true;
		} else if (command == "S") {
			int i;
			in >> i;
			auto e = board.findEntity(i);
			if(e) {
				if (&(e->owner) == &(this->player)) {
					board.pushCommand(make_shared<StopCommand>(e->getId()));
					ack = true;
				}
			}
		} else if (command == "M") {
			int i;
			double x, y;
			in >> i >> x >> y;
			if (!this->owner.willExit()) {
				auto e = board.findEntity(i);
				if (e) {
					if (&(e->owner) == &(this->player)) {
						board.pushCommand(make_shared<MoveCommand>(e->getId(), r2(x, y)));
						ack = true;
					}
				}
			}
		} else if (command == "U") {
			size_t frame;
			in >> frame;
			answer << this->frame << '\t';
			board.mapEntities([this, &answer, frame](shared_ptr<Entity> e) {
					if (e->getFrame() > frame) {
					answer << e->serialize();
					}
					});
			for(auto& p : board.getPlayers()) {
				if (p->getFrame() > frame) {
					answer << p->serialize();
				}
			}
			deletedMutex.lock();
			while (deleted.size() > 0) {
				answer << "D\t" << deleted.front() << endl;
				deleted.pop();
			}
			deletedMutex.unlock();
			ack = true;
		}
		string payload;
		if (ack) {
			payload = "+" + answer.str() + "\n";
		} else {
			payload = "-\n";
		}
		socket->Send((void*)payload.c_str(), payload.length());
		cout << payload;
	}
}

RemoteClient::~RemoteClient() {
	if(running) {
		th.join();
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: slidebitmap.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:28:53 $
 *
 *  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_slideshow.hxx"

// must be first
#include <canvas/debug.hxx>
#include <slidebitmap.hxx>

#ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP_
#include <com/sun/star/rendering/XCanvas.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XBITMAP_HPP_
#include <com/sun/star/rendering/XBitmap.hpp>
#endif

#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif

#include <canvas/canvastools.hxx>
#include <basegfx/tools/canvastools.hxx>

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

namespace presentation
{
    namespace internal
    {

        SlideBitmap::SlideBitmap( const ::cppcanvas::BitmapSharedPtr& rBitmap ) :
            maOutputPos(),
            maClipPoly(),
            mxBitmap()
        {
            if( rBitmap.get() )
                mxBitmap = rBitmap->getUNOBitmap();

            ENSURE_AND_THROW( mxBitmap.is(), "SlideBitmap::SlideBitmap(): Invalid bitmap" );
        }

        bool SlideBitmap::draw( const ::cppcanvas::CanvasSharedPtr& rCanvas ) const
        {
            ENSURE_AND_RETURN( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(),
                               "SlideBitmap::draw(): Invalid canvas" );

            // selectively only copy the transformation from current viewstate,
            // don't want no clipping here.
            rendering::ViewState aViewState;
            aViewState.AffineTransform = rCanvas->getViewState().AffineTransform;

            rendering::RenderState aRenderState;
            ::canvas::tools::initRenderState( aRenderState );

            ::basegfx::B2DHomMatrix aTranslation;
            aTranslation.translate( maOutputPos.getX(),
                                    maOutputPos.getY() );
            ::canvas::tools::setRenderStateTransform( aRenderState, aTranslation );

            if( maClipPoly.count() )
            {
                // TODO(P1): Buffer the clip polygon
                aRenderState.Clip =
                    ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
                        rCanvas->getUNOCanvas()->getDevice(),
                        maClipPoly );
            }

            rCanvas->getUNOCanvas()->drawBitmap( mxBitmap,
                                                 aViewState,
                                                 aRenderState );
            return true;
        }

        ::basegfx::B2ISize SlideBitmap::getSize() const
        {
            return ::basegfx::unotools::b2ISizeFromIntegerSize2D( mxBitmap->getSize() );
        }

        void SlideBitmap::move( const ::basegfx::B2DPoint& rNewPos )
        {
            maOutputPos = rNewPos;
        }

        void SlideBitmap::clip( const ::basegfx::B2DPolyPolygon& rClipPoly )
        {
            maClipPoly = rClipPoly;
        }

    }
}
<commit_msg>INTEGRATION: CWS presfixes09 (1.6.18); FILE MERGED 2006/10/18 19:51:08 thb 1.6.18.4: RESYNC: (1.6-1.7); FILE MERGED 2006/04/12 20:40:04 thb 1.6.18.3: #i37778# Replaced all shared_ptr.get() != NULL places with the more elegant automatic-conversion-to-bool version (at least where the compiler tolerated that) 2006/03/24 18:23:10 thb 1.6.18.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006/03/15 15:22:18 thb 1.6.18.1: #i49357# Removed external include guards from all non-export headers (and from the cxx files, anyway)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: slidebitmap.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 15:20: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
 *
 ************************************************************************/

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

// must be first
#include <canvas/debug.hxx>
#include <slidebitmap.hxx>

#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/rendering/XBitmap.hpp>

#include <basegfx/matrix/b2dhommatrix.hxx>

#include <canvas/canvastools.hxx>
#include <basegfx/tools/canvastools.hxx>

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

namespace slideshow
{
    namespace internal
    {

        SlideBitmap::SlideBitmap( const ::cppcanvas::BitmapSharedPtr& rBitmap ) :
            maOutputPos(),
            maClipPoly(),
            mxBitmap()
        {
            if( rBitmap )
                mxBitmap = rBitmap->getUNOBitmap();

            ENSURE_AND_THROW( mxBitmap.is(), "SlideBitmap::SlideBitmap(): Invalid bitmap" );
        }

        bool SlideBitmap::draw( const ::cppcanvas::CanvasSharedPtr& rCanvas ) const
        {
            ENSURE_AND_RETURN( rCanvas && rCanvas->getUNOCanvas().is(),
                               "SlideBitmap::draw(): Invalid canvas" );

            // selectively only copy the transformation from current viewstate,
            // don't want no clipping here.
            rendering::ViewState aViewState;
            aViewState.AffineTransform = rCanvas->getViewState().AffineTransform;

            rendering::RenderState aRenderState;
            ::canvas::tools::initRenderState( aRenderState );

            ::basegfx::B2DHomMatrix aTranslation;
            aTranslation.translate( maOutputPos.getX(),
                                    maOutputPos.getY() );
            ::canvas::tools::setRenderStateTransform( aRenderState, aTranslation );

            if( maClipPoly.count() )
            {
                // TODO(P1): Buffer the clip polygon
                aRenderState.Clip =
                    ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
                        rCanvas->getUNOCanvas()->getDevice(),
                        maClipPoly );
            }

            rCanvas->getUNOCanvas()->drawBitmap( mxBitmap,
                                                 aViewState,
                                                 aRenderState );
            return true;
        }

        ::basegfx::B2ISize SlideBitmap::getSize() const
        {
            return ::basegfx::unotools::b2ISizeFromIntegerSize2D( mxBitmap->getSize() );
        }

        void SlideBitmap::move( const ::basegfx::B2DPoint& rNewPos )
        {
            maOutputPos = rNewPos;
        }

        void SlideBitmap::clip( const ::basegfx::B2DPolyPolygon& rClipPoly )
        {
            maClipPoly = rClipPoly;
        }

    }
}
<|endoftext|>


<commit_before>/*
 * This program source code file is part of KICAD, a free EDA CAD application.
 *
 * Copyright (C) 2007-2008 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
 * Copyright (C) 2007 Kicad Developers, see change_log.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

/*  This source is a complement to specctra.cpp and implements the export to
    specctra dsn file format.  The specification for the grammar of the specctra
    dsn file used to develop this code is given here:
    http://www.autotraxeda.com/docs/SPECCTRA/SPECCTRA.pdf

    Also see the comments at the top of the specctra.cpp file itself.
*/

#include "specctra.h"
#include "collectors.h"

using namespace DSN;

// see wxPcbStruct.h
void WinEDA_PcbFrame::ExportToSPECCTRA( wxCommandEvent& event )
{
    wxString        fullFileName = GetScreen()->m_FileName;
    wxString        std_ext = wxT( ".dsn" );
    wxString        mask    = wxT( "*" ) + std_ext;

    ChangeFileNameExt( fullFileName, std_ext );

    fullFileName = EDA_FileSelector( _( "Specctra DSN file:" ),
                                     wxEmptyString,     /* Chemin par defaut */
                                     fullFileName,      /* nom fichier par defaut */
                                     std_ext,           /* extension par defaut */
                                     mask,              /* Masque d'affichage */
                                     this,
                                     wxFD_SAVE,
                                     FALSE
                                     );
    if( fullFileName == wxEmptyString )
        return;

    SPECCTRA_DB     db;

    db.SetPCB( SPECCTRA_DB::MakePCB() );

    try
    {
        db.FromBOARD( m_Pcb );
        db.ExportPCB(  fullFileName, true );

        // if an exception is thrown by FromBOARD or Export(), then
        // ~SPECCTRA_DB() will close the file.
    }
    catch ( IOError ioe )
    {
        DisplayError( this, ioe.errorText );
        return;
    }

    // @todo display a message saying the export is complete.
}

namespace DSN {

struct POINT_PAIR
{
    POINT       p1;         ///< start
    POINT       p2;         ///< end
    BOARD_ITEM* item;       ///< the item which has these points, TRACK or DRAWSEGMENT
};
typedef std::vector<POINT_PAIR>     POINT_PAIRS;

static inline void swap( POINT_PAIR& pair )
{
    POINT temp = pair.p1;
    pair.p1 = pair.p2;
    pair.p2 = temp;
}

/**
 * Function mapPt
 * converts a Kicad point into a DSN file point.  Kicad's BOARD coordinates
 * are in deci-mils  (i.e. 1/10,000th of an inch) and we are exporting in units
 * of mils, so we have to divide by 10.
 */
static POINT mapPt( const wxPoint& pt )
{
    POINT ret;
    ret.x = pt.x / 10.0;
    ret.y = -pt.y /10.0;      // make y negative, since it is increasing going down.
    return ret;
}

/**
 * Function swapEnds
 * will swap ends of any POINT_PAIR in the POINT_PAIRS list in order to
 * make the consecutive POINT_PAIRs be "connected" at their ends.
 */
static void swapEnds( POINT_PAIRS& aList )
{
    POINT   temp;

    if( aList.size() <= 1 )
        return;

    for( unsigned i=0;  i<aList.size();  ++i )
    {
        if( aList[i].p1 == aList[i+1].p1 )
            swap( aList[i] );

        else if( aList[i].p1 == aList[i+1].p2 )
        {
            swap( aList[i] );
            swap( aList[i+1] );
            ++i;    // skip next one, we swapped i+1 here
        }
    }
}

/**
 * Function isRectangle
 * tests to see if the POINT_PAIRS list makes up a vertically/horizontally
 * oriented rectangle.
 * @return bool - true if there are 4 point pairs making a rectangle.
 */
static bool isRectangle( POINT_PAIRS& aList )
{
    if( aList.size() == 4 )
    {
        for( unsigned i=0;  i<aList.size();  ++i )
        {
            if( i < aList.size()-1 )
                if( aList[i].p2 != aList[i+1].p1 )
                    return false;

            if( aList[i].p1.x != aList[i].p2.x
            &&  aList[i].p1.y != aList[i].p2.y )
                return false;
        }

        return ( aList[0].p1 == aList[3].p2 );
    }
    return false;
}

void SPECCTRA_DB::exportEdges( BOARD* aBoard ) throw( IOError )
{
}

void SPECCTRA_DB::FromBOARD( BOARD* aBoard ) throw( IOError )
{
    TYPE_COLLECTOR          items;
    POINT_PAIRS             ppairs;
    POINT_PAIR              pair;

    if( !pcb )
        pcb = SPECCTRA_DB::MakePCB();

    //-----<unit_descriptor> & <resolution_descriptor>--------------------
    {
        pcb->unit->units = T_mil;
        pcb->resolution->units = T_mil;
        pcb->resolution->value = 100;
    }

    //-----<boundary_descriptor>------------------------------------------
    {
        // get all the DRAWSEGMENTS into 'items', then look for layer == EDGE_N,
        // and those segments comprize the board's perimeter.
        const KICAD_T  scanDRAWSEGMENTS[] = { TYPEDRAWSEGMENT, EOT };
        items.Collect( aBoard, scanDRAWSEGMENTS );

        bool haveEdges = false;
        ppairs.clear();
        for( int i=0;  i<items.GetCount();  ++i )
        {
            DRAWSEGMENT* item = (DRAWSEGMENT*) items[i];

            wxASSERT( item->Type() == TYPEDRAWSEGMENT );

            if( item->GetLayer() == EDGE_N )
            {
                pair.p1 = mapPt( item->m_Start );
                pair.p2 = mapPt( item->m_End );
                pair.item = item;
                ppairs.push_back( pair );
                haveEdges = true;
            }
        }

        if( haveEdges )
        {
            swapEnds( ppairs );

    #if defined(DEBUG)
            for( unsigned i=0;  i<ppairs.size();  ++i )
            {
                POINT_PAIR* p = &ppairs[i];
                p->item->Show( 0, std::cout );
            }
    #endif

            BOUNDARY*   boundary = new BOUNDARY(0);

            if( isRectangle( ppairs ) )
            {
                RECTANGLE*  rect = new RECTANGLE( boundary );
                rect->layer_id = "pcb";

                // opposite corners
                rect->point0 = ppairs[0].p1;
                rect->point1 = ppairs[2].p1;

                boundary->rectangle = rect;
            }
            else
            {
                PATH*  path = new PATH( boundary );

                path->layer_id = "pcb";
                for( unsigned i=0; i<ppairs.size();  ++i )
                {
                    // unless its a closed polygon, this probably won't work,
                    // otherwise it will.
                    path->points.push_back( ppairs[i].p1 );
                }

                boundary->paths.push_back( path );
            }

            pcb->structure->SetBOUNDARY( boundary );
        }
        else
        {
            aBoard->ComputeBoundaryBox();

            BOUNDARY*   boundary = new BOUNDARY(0);
            RECTANGLE*  rect = new RECTANGLE( boundary );

            rect->layer_id = "pcb";

            // opposite corners
            wxPoint bottomRight;
            bottomRight.x = aBoard->m_BoundaryBox.GetRight();
            bottomRight.y = aBoard->m_BoundaryBox.GetBottom();

            rect->point0 = mapPt( aBoard->m_BoundaryBox.GetOrigin() );
            rect->point1 = mapPt( bottomRight );

            boundary->rectangle = rect;

            pcb->structure->SetBOUNDARY( boundary );
        }
    }

    //-----<layer_descriptor>-----------------------------------------------
    {
        // specctra wants top physical layer first, then going down to the
        // bottom most physical layer in physical sequence.
        // @question : why does Kicad not display layers in that order?
        int layerCount = aBoard->GetCopperLayerCount();

        for( int ndx=layerCount-1;  ndx >= 0;  --ndx )
        {
            wxString    layerName = aBoard->GetLayerName( ndx>0 && ndx==layerCount-1 ? LAYER_CMP_N : ndx );
            LAYER*      layer = new LAYER( pcb->structure );

            layer->name = CONV_TO_UTF8( layerName );

            // layer->type =
            pcb->structure->layers.push_back( layer );
        }
    }

    //-----<build the padstack list here, no output>------------------------

    //-----<via_descriptor>-------------------------------------------------
    {
        // Output the vias in the padstack list here, by name
    }

}

}       // namespace DSN

<commit_msg>more specctra export work<commit_after>/*
 * This program source code file is part of KICAD, a free EDA CAD application.
 *
 * Copyright (C) 2007-2008 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
 * Copyright (C) 2007 Kicad Developers, see change_log.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

/*  This source is a complement to specctra.cpp and implements the export to
    specctra dsn file format.  The specification for the grammar of the specctra
    dsn file used to develop this code is given here:
    http://www.autotraxeda.com/docs/SPECCTRA/SPECCTRA.pdf

    Also see the comments at the top of the specctra.cpp file itself.
*/

#include "specctra.h"
#include "collectors.h"

using namespace DSN;

// see wxPcbStruct.h
void WinEDA_PcbFrame::ExportToSPECCTRA( wxCommandEvent& event )
{
    wxString        fullFileName = GetScreen()->m_FileName;
    wxString        std_ext = wxT( ".dsn" );
    wxString        mask    = wxT( "*" ) + std_ext;

    ChangeFileNameExt( fullFileName, std_ext );

    fullFileName = EDA_FileSelector( _( "Specctra DSN file:" ),
                                     wxEmptyString,     /* Chemin par defaut */
                                     fullFileName,      /* nom fichier par defaut */
                                     std_ext,           /* extension par defaut */
                                     mask,              /* Masque d'affichage */
                                     this,
                                     wxFD_SAVE,
                                     FALSE
                                     );
    if( fullFileName == wxEmptyString )
        return;

    SPECCTRA_DB     db;

    db.SetPCB( SPECCTRA_DB::MakePCB() );

    try
    {
        db.FromBOARD( m_Pcb );
        db.ExportPCB(  fullFileName, true );

        // if an exception is thrown by FromBOARD or Export(), then
        // ~SPECCTRA_DB() will close the file.
    }
    catch ( IOError ioe )
    {
        DisplayError( this, ioe.errorText );
        return;
    }

    // @todo display a message saying the export is complete.
}

namespace DSN {

struct POINT_PAIR
{
    POINT       p1;         ///< start
    POINT       p2;         ///< end
    BOARD_ITEM* item;       ///< the item which has these points, TRACK or DRAWSEGMENT
};
typedef std::vector<POINT_PAIR>     POINT_PAIRS;

static inline void swap( POINT_PAIR& pair )
{
    POINT temp = pair.p1;
    pair.p1 = pair.p2;
    pair.p2 = temp;
}

/**
 * Function mapPt
 * converts a Kicad point into a DSN file point.  Kicad's BOARD coordinates
 * are in deci-mils  (i.e. 1/10,000th of an inch) and we are exporting in units
 * of mils, so we have to divide by 10.
 */
static POINT mapPt( const wxPoint& pt )
{
    POINT ret;
    ret.x = pt.x / 10.0;
    ret.y = -pt.y /10.0;      // make y negative, since it is increasing going down.
    return ret;
}

/**
 * Function swapEnds
 * will swap ends of any POINT_PAIR in the POINT_PAIRS list in order to
 * make the consecutive POINT_PAIRs be "connected" at their ends.
 */
static void swapEnds( POINT_PAIRS& aList )
{
    POINT   temp;

    if( aList.size() <= 1 )
        return;

    for( unsigned i=0;  i<aList.size();  ++i )
    {
        if( aList[i].p1 == aList[i+1].p1 )
            swap( aList[i] );

        else if( aList[i].p1 == aList[i+1].p2 )
        {
            swap( aList[i] );
            swap( aList[i+1] );
            ++i;    // skip next one, we swapped i+1 here
        }
    }
}

/**
 * Function isRectangle
 * tests to see if the POINT_PAIRS list makes up a vertically/horizontally
 * oriented rectangle.
 * @return bool - true if there are 4 point pairs making a rectangle.
 */
static bool isRectangle( POINT_PAIRS& aList )
{
    if( aList.size() == 4 )
    {
        for( unsigned i=0;  i<aList.size();  ++i )
        {
            if( i < aList.size()-1 )
                if( aList[i].p2 != aList[i+1].p1 )
                    return false;

            if( aList[i].p1.x != aList[i].p2.x
            &&  aList[i].p1.y != aList[i].p2.y )
                return false;
        }

        return ( aList[0].p1 == aList[3].p2 );
    }
    return false;
}

void SPECCTRA_DB::exportEdges( BOARD* aBoard ) throw( IOError )
{
}

void SPECCTRA_DB::FromBOARD( BOARD* aBoard ) throw( IOError )
{
    TYPE_COLLECTOR          items;
    POINT_PAIRS             ppairs;
    POINT_PAIR              pair;

    if( !pcb )
        pcb = SPECCTRA_DB::MakePCB();

    //-----<unit_descriptor> & <resolution_descriptor>--------------------
    {
        pcb->unit->units = T_mil;
        pcb->resolution->units = T_mil;
        pcb->resolution->value = 100;
    }

    //-----<boundary_descriptor>------------------------------------------
    {
        // get all the DRAWSEGMENTS into 'items', then look for layer == EDGE_N,
        // and those segments comprize the board's perimeter.
        static const KICAD_T  scanDRAWSEGMENTS[] = { TYPEDRAWSEGMENT, EOT };
        items.Collect( aBoard, scanDRAWSEGMENTS );

        bool haveEdges = false;
        ppairs.clear();
        for( int i=0;  i<items.GetCount();  ++i )
        {
            DRAWSEGMENT* item = (DRAWSEGMENT*) items[i];

            wxASSERT( item->Type() == TYPEDRAWSEGMENT );

            if( item->GetLayer() == EDGE_N )
            {
                pair.p1 = mapPt( item->m_Start );
                pair.p2 = mapPt( item->m_End );
                pair.item = item;
                ppairs.push_back( pair );
                haveEdges = true;
            }
        }

        if( haveEdges )
        {
            swapEnds( ppairs );

    #if defined(DEBUG)
            for( unsigned i=0;  i<ppairs.size();  ++i )
            {
                POINT_PAIR* p = &ppairs[i];
                p->item->Show( 0, std::cout );
            }
    #endif

            BOUNDARY*   boundary = new BOUNDARY(0);

            if( isRectangle( ppairs ) )
            {
                RECTANGLE*  rect = new RECTANGLE( boundary );
                rect->layer_id = "pcb";

                // opposite corners
                rect->point0 = ppairs[0].p1;
                rect->point1 = ppairs[2].p1;

                boundary->rectangle = rect;
            }
            else
            {
                PATH*  path = new PATH( boundary );

                path->layer_id = "pcb";
                for( unsigned i=0; i<ppairs.size();  ++i )
                {
                    // unless its a closed polygon, this probably won't work,
                    // otherwise it will.
                    path->points.push_back( ppairs[i].p1 );
                }

                boundary->paths.push_back( path );
            }

            pcb->structure->SetBOUNDARY( boundary );
        }
        else
        {
            aBoard->ComputeBoundaryBox();

            BOUNDARY*   boundary = new BOUNDARY(0);
            RECTANGLE*  rect = new RECTANGLE( boundary );

            rect->layer_id = "pcb";

            // opposite corners
            wxPoint bottomRight;
            bottomRight.x = aBoard->m_BoundaryBox.GetRight();
            bottomRight.y = aBoard->m_BoundaryBox.GetBottom();

            rect->point0 = mapPt( aBoard->m_BoundaryBox.GetOrigin() );
            rect->point1 = mapPt( bottomRight );

            boundary->rectangle = rect;

            pcb->structure->SetBOUNDARY( boundary );
        }
    }

    //-----<layer_descriptor>-----------------------------------------------
    {
        // specctra wants top physical layer first, then going down to the
        // bottom most physical layer in physical sequence.
        // @question : why does Kicad not display layers in that order?
        int layerCount = aBoard->GetCopperLayerCount();

        for( int ndx=layerCount-1;  ndx >= 0;  --ndx )
        {
            wxString    layerName = aBoard->GetLayerName( ndx>0 && ndx==layerCount-1 ? LAYER_CMP_N : ndx );
            LAYER*      layer = new LAYER( pcb->structure );

            layer->name = CONV_TO_UTF8( layerName );

            // layer->type =
            pcb->structure->layers.push_back( layer );
        }
    }

    //-----<zone containers become planes>--------------------------------------------
    {
        static const KICAD_T  scanZONEs[] = { TYPEZONE_CONTAINER, EOT };
        items.Collect( aBoard, scanZONEs );

        for( int i=0;  i<items.GetCount();  ++i )
        {
            ZONE_CONTAINER* item = (ZONE_CONTAINER*) items[i];

            wxString        layerName = aBoard->GetLayerName( item->GetLayer() );
            COPPER_PLANE*   plane = new COPPER_PLANE( pcb->structure );
            PATH*           polygon = new PATH( plane, T_polygon );

            plane->path = polygon;
            plane->name = CONV_TO_UTF8( item->m_Netname );

            polygon->layer_id = CONV_TO_UTF8( layerName );

            int count = item->m_Poly->corner.size();
            for( int j=0; j<count; ++j )
            {
                wxPoint   point( item->m_Poly->corner[j].x, item->m_Poly->corner[j].y );

                polygon->points.push_back( mapPt(point) );
            }

            pcb->structure->planes.push_back( plane );
        }
    }

    //-----<build the padstack list here, no output>------------------------
    {
        // get all the DRAWSEGMENTS into 'items', then look for layer == EDGE_N,
        // and those segments comprize the board's perimeter.
        static const KICAD_T  scanPADnVIAs[] = { TYPEPAD, TYPEVIA, EOT };
        items.Collect( aBoard, scanPADnVIAs );

        for( int i=0;  i<items.GetCount();  ++i )
        {
//            items[i]->Show( 0, std::cout );
        }
    }

    //-----<via_descriptor>-------------------------------------------------
    {
        // Output the vias in the padstack list here, by name
    }

}

}       // namespace DSN

<|endoftext|>


<commit_before>// Copyright (c) 2016 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#ifndef PEGTL_INTERNAL_EOL_IMPL_HH
#define PEGTL_INTERNAL_EOL_IMPL_HH

#include <utility>

#include "../eol_mode.hh"

namespace pegtl
{
   namespace internal
   {
      using eol_pair = std::pair< bool, unsigned char >;

      template< eol_mode EOL > struct eol_impl;

      template<> struct eol_impl< eol_mode::LF_ONLY >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 1 ) };
            if ( p.second ) {
               if ( in.peek_char() == '\n' ) {
                  in.bump_to_next_line();
                  p.first = true;
               }
            }
            return p;
         }
      };

      template<> struct eol_impl< eol_mode::CR_ONLY >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 1 ) };
            if ( p.second ) {
               if ( in.peek_char() == '\r' ) {
                  in.bump_to_next_line();
                  p.first = true;
               }
            }
            return p;
         }
      };

      template<> struct eol_impl< eol_mode::CRLF_ONLY >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 2 ) };
            if ( p.second > 1 ) {
               if ( ( in.peek_char() == '\r' ) && ( in.peek_char( 1 ) == '\n' ) ) {
                  in.bump_to_next_line( 2 );
                  p.first = true;
               }
            }
            return p;
         }
      };

      template<> struct eol_impl< eol_mode::LF_WITH_CRLF >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 2 ) };
            if ( p.second ) {
               const auto a = in.peek_char();
               if ( a == '\n' ) {
                  in.bump_to_next_line();
                  p.first = true;
               }
               else if ( ( a == '\r' ) && ( p.second > 1 ) && ( in.peek_char( 1 ) == '\n' ) ) {
                  in.bump_to_next_line( 2 );
                  p.first = true;
               }
            }
            return p;
         }
      };

      template<> struct eol_impl< eol_mode::CR_WITH_CRLF >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 2 ) };
            if ( p.second ) {
               if ( in.peek_char() == '\r' ) {
                  in.bump_to_next_line( 1 + ( ( p.second > 1 ) && ( in.peek_char( 1 ) == '\n' ) ) );
                  p.first = true;
               }
            }
            return p;
         }
      };

   } // namespace internal

} // namespace pegtl

#endif
<commit_msg>Fix EOL handling<commit_after>// Copyright (c) 2016 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#ifndef PEGTL_INTERNAL_EOL_IMPL_HH
#define PEGTL_INTERNAL_EOL_IMPL_HH

#include <utility>

#include "../eol_mode.hh"

namespace pegtl
{
   namespace internal
   {
      using eol_pair = std::pair< bool, std::size_t >;

      template< eol_mode EOL > struct eol_impl;

      template<> struct eol_impl< eol_mode::LF_ONLY >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 1 ) };
            if ( p.second ) {
               if ( in.peek_char() == '\n' ) {
                  in.bump_to_next_line();
                  p.first = true;
               }
            }
            return p;
         }
      };

      template<> struct eol_impl< eol_mode::CR_ONLY >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 1 ) };
            if ( p.second ) {
               if ( in.peek_char() == '\r' ) {
                  in.bump_to_next_line();
                  p.first = true;
               }
            }
            return p;
         }
      };

      template<> struct eol_impl< eol_mode::CRLF_ONLY >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 2 ) };
            if ( p.second > 1 ) {
               if ( ( in.peek_char() == '\r' ) && ( in.peek_char( 1 ) == '\n' ) ) {
                  in.bump_to_next_line( 2 );
                  p.first = true;
               }
            }
            return p;
         }
      };

      template<> struct eol_impl< eol_mode::LF_WITH_CRLF >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 2 ) };
            if ( p.second ) {
               const auto a = in.peek_char();
               if ( a == '\n' ) {
                  in.bump_to_next_line();
                  p.first = true;
               }
               else if ( ( a == '\r' ) && ( p.second > 1 ) && ( in.peek_char( 1 ) == '\n' ) ) {
                  in.bump_to_next_line( 2 );
                  p.first = true;
               }
            }
            return p;
         }
      };

      template<> struct eol_impl< eol_mode::CR_WITH_CRLF >
      {
         template< typename Input >
         static eol_pair match( Input & in )
         {
            eol_pair p = { false, in.size( 2 ) };
            if ( p.second ) {
               if ( in.peek_char() == '\r' ) {
                  in.bump_to_next_line( 1 + ( ( p.second > 1 ) && ( in.peek_char( 1 ) == '\n' ) ) );
                  p.first = true;
               }
            }
            return p;
         }
      };

   } // namespace internal

} // namespace pegtl

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <set>

#include <fast_hash.hpp>
#include <stl_io.hpp>

using namespace std;
using namespace utils;

using Bucket = list<string>;

vector<string> generate_keys(size_t N) {

  vector<string> keys(N);

  for (size_t i = 0; i < N; ++i) {
    stringstream s;
    s << "key-" << i;
    keys[i] = s.str();
  }

  return keys;
}

/**
 * Greedy algorithm to find salts for perfect hashing.
 *
 * Notes:
 * - could leave some buckets with > 1 items
 * - minimum salt size?
 */
vector<int> find_H(const vector<string>& keys) {

  size_t N = keys.size();
  vector<int> H(N);
  vector<Bucket> buckets(N);

  // Hash to buckets
  for (size_t i = 0; i < N; ++i) {
    size_t h0 = fasthash64(keys[i]) % N;
    buckets[h0].push_back(keys[i]);
  }

  // Find salts
  sort(buckets.begin(), buckets.end(),
       [](const Bucket& b1, const Bucket& b2) { return b1.size() > b2.size(); });

  size_t M = numeric_limits<size_t>::max();
  size_t last = 0;
  set<size_t> free;
  size_t n = 0;
  generate_n(inserter(free, free.end()), N, [&]() { return n++;});

  cout << buckets << endl;

  for (Bucket bucket : buckets) {
    if (bucket.size() <= 1) break;
    ++last;
    set<size_t> slots;
    size_t salt = 1;
    size_t h0 = fasthash64(bucket.front()) % N;
    cout << "Bucket: " << bucket << " @ " << h0 << endl;
    for (; salt < M && slots.size() < bucket.size(); ++salt) {
      cout << "\tTrying salt: " << salt << endl;
      cout << "\t\tfree: " << free << " slots: " << slots << endl;
      for (auto key : bucket) {
        size_t h1 = fasthash64(key, salt) % N;
        if (free.find(h1) == free.end()) {
          cout << "\t\tkey: " << key << " slot: " << h1 << " - already occupied" << endl;
          free.insert(slots.begin(), slots.end()); // backtrack
          slots.clear();
          break;
        } else {
          slots.insert(h1);
          free.erase(h1);
          cout << "\t\tkey: " << key << " taking slot: " << h1 << endl;
          cout << "\t\tfree: " << free << " slots: " << slots << endl;
        }
      }
    }
    if (slots.size() == bucket.size()) {
      size_t h0 = fasthash64(bucket.front()) % N;
      H[h0] = (int) salt-1;
      cout << "\tGood salt: " << (salt-1) << " stored at: " << h0 << endl;
    } else {
      cout << "\tInfeasible!" << endl;
    }
  }

  // Handle size 1 buckets if any
  for (size_t i = last; i < buckets.size(); ++i) {
    if (buckets[i].empty()) break;
    cout << "Size 1 bucket: " << buckets[i] << endl;
    size_t h0 = fasthash64(buckets[i].front()) % N;
    int f = (int) *free.begin();
    free.erase(*free.begin());
    H[h0] = -f - 1;
    cout << "\t@ " << f << endl;
    cout << "\tfree: " << free << endl;
  }

  return H;
}

size_t p_hash(const string& key, const vector<int>& H) {
  size_t h0 = fasthash64(key) % H.size();
  return (size_t) (H[h0] < 0 ? (size_t) - H[h0] - 1 : fasthash64(key, (size_t) H[h0])) % H.size();
}

void test_perfect_hash() {

  size_t N = 20;
  vector<string> keys = generate_keys(N);
  vector<int> H = find_H(keys);

  // test
  set<size_t> results;
  for (string key : keys) {
    size_t h = p_hash(key, H);
    cout << "key: " << key << " -> " << h << endl;
    if (results.count(h)) {
      cout << "Collision seen " << key << " @ " << h << endl;
      exit(-9);
    }
    results.insert(h);
  }
  cout << "Test successful - no collision" << endl;
}

int main() {

  test_perfect_hash();
  return 0;
}<commit_msg>More tests for perfect hash<commit_after>#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <set>

#include <fast_hash.hpp>
#include <stl_io.hpp>

using namespace std;
using namespace utils;

using Bucket = list<string>;

vector<string> generate_keys(size_t N) {

  vector<string> keys(N);

  for (size_t i = 0; i < N; ++i) {
    stringstream s;
    s << "key-" << i;
    keys[i] = s.str();
  }

  return keys;
}

/**
 * Greedy algorithm to find salts for perfect hashing.
 *
 * Notes:
 * - could leave some buckets with > 1 items
 * - minimum salt size?
 */
vector<int> find_H(const vector<string>& keys, bool _debug_algo =false) {

  size_t N = keys.size();
  vector<int> H(N);
  vector<Bucket> buckets(N);

  // Hash to buckets
  for (size_t i = 0; i < N; ++i) {
    size_t h0 = fasthash64(keys[i]) % N;
    buckets[h0].push_back(keys[i]);
  }

  // Find salts
  sort(buckets.begin(), buckets.end(),
       [](const Bucket& b1, const Bucket& b2) { return b1.size() > b2.size(); });

  size_t M = numeric_limits<size_t>::max();
  size_t last = 0;
  set<size_t> free;
  size_t n = 0;
  generate_n(inserter(free, free.end()), N, [&]() { return n++;});

  if (_debug_algo) cout << buckets << endl;

  for (Bucket bucket : buckets) {
    if (bucket.size() <= 1) break;
    ++last;
    set<size_t> slots;
    size_t salt = 1;
    size_t h0 = fasthash64(bucket.front()) % N;
    if (_debug_algo) cout << "Bucket: " << bucket << " @ " << h0 << endl;
    for (; salt < M && slots.size() < bucket.size(); ++salt) {
      if (_debug_algo) cout << "\tTrying salt: " << salt << endl;
      if (_debug_algo) cout << "\t\tfree: " << free << " slots: " << slots << endl;
      for (auto key : bucket) {
        size_t h1 = fasthash64(key, salt) % N;
        if (free.find(h1) == free.end()) {
          if (_debug_algo) cout << "\t\tkey: " << key << " slot: " << h1 << " - already occupied" << endl;
          free.insert(slots.begin(), slots.end()); // backtrack
          slots.clear();
          break;
        } else {
          slots.insert(h1);
          free.erase(h1);
          if (_debug_algo) cout << "\t\tkey: " << key << " taking slot: " << h1 << endl;
          if (_debug_algo) cout << "\t\tfree: " << free << " slots: " << slots << endl;
        }
      }
    }
    if (slots.size() == bucket.size()) {
      size_t h0 = fasthash64(bucket.front()) % N;
      H[h0] = (int) salt-1;
      if (_debug_algo) cout << "\tGood salt: " << (salt-1) << " stored at: " << h0 << endl;
    } else {
      if (_debug_algo) cout << "\tInfeasible!" << endl;
    }
  }

  // Handle size 1 buckets if any
  for (size_t i = last; i < buckets.size(); ++i) {
    if (buckets[i].empty()) break;
    if (_debug_algo) cout << "Size 1 bucket: " << buckets[i] << endl;
    size_t h0 = fasthash64(buckets[i].front()) % N;
    int f = (int) *free.begin();
    free.erase(*free.begin());
    H[h0] = -f - 1;
    if (_debug_algo) cout << "\t@ " << f << endl;
    if (_debug_algo) cout << "\tfree: " << free << endl;
  }

  return H;
}

size_t p_hash(const string& key, const vector<int>& H) {
  size_t h0 = fasthash64(key) % H.size();
  return (size_t) (H[h0] < 0 ? (size_t) - H[h0] - 1 : fasthash64(key, (size_t) H[h0])) % H.size();
}

void test_perfect_hash() {

  size_t M = 1000, N = 1000;

  for (size_t i = 0; i < M; ++i) {
    vector<string> keys = generate_keys(N);
    vector<int> H = find_H(keys);

    set<size_t> results;
    for (string key : keys) {
      size_t h = p_hash(key, H);
      if (results.count(h)) {
        cout << "Collision seen " << key << " @ " << h << endl;
        exit(-9);
      }
      results.insert(h);
    }
    cout << "Test successful " << i << " - no collision" << endl;
  }
}

int main() {

  test_perfect_hash();
  return 0;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: d_token.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 15:21:01 $
 *
 *  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 CSI_DSAPI_D_TOKEN_HXX
#define CSI_DSAPI_D_TOKEN_HXX

// BASE CLASSES
#include <ary_i/ci_text2.hxx>
#include <ary_i/ci_atag2.hxx>

namespace ary
{
namespace inf
{
    class DocumentationDisplay;
}
}

namespace csi
{
namespace dsapi
{

using ary::inf::DocumentationDisplay;

class DT_Dsapi : public ary::inf::DocuToken
{
  public:
    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const  = 0;
    virtual bool        IsWhiteOnly() const;
};

class DT_TextToken : public DT_Dsapi
{
  public:
    explicit            DT_TextToken(
                            const char *        i_sText )
                                                :   sText(i_sText) {}
    explicit            DT_TextToken(
                            const String &      i_sText )
                                                :   sText(i_sText) {}
    virtual             ~DT_TextToken();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const char *        GetText() const         { return sText; }
    const String &      GetTextStr() const      { return sText; }

    String &            Access_Text()           { return sText; }

    virtual bool        IsWhiteOnly() const;

  private:
    String              sText;
};

class DT_White : public DT_Dsapi
{
  public:
                        DT_White() {}
    virtual             ~DT_White();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    virtual bool        IsWhiteOnly() const;
};

class DT_MLTag : public DT_Dsapi
{
  public:
    enum E_Kind
    {
        k_unknown = 0,
        k_begin,
        k_end,
        k_single
    };
};

class DT_MupType : public DT_MLTag
{
  public:
    explicit            DT_MupType(             /// Constructor for End-Tag
                            bool                )   /// Must be there, but is not evaluated.
                                                :   bIsBegin(false) {}
    explicit            DT_MupType(             /// Constructor for Begin-Tag
                            const String &      i_sScope )
                                                :   sScope(i_sScope), bIsBegin(true) {}
    virtual             ~DT_MupType();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const String  &     Scope() const           { return sScope; }
    bool                IsBegin() const         { return bIsBegin; }

  private:
    String              sScope;
    bool                bIsBegin;
};

class DT_MupMember : public DT_MLTag
{
  public:
    explicit            DT_MupMember(           /// Constructor for End-Tag
                            bool                )   /// Must be there, but is not evaluated.
                                                :   bIsBegin(false) {}
                        DT_MupMember(           /// Constructor for Begin-Tag
                            const String &      i_sScope )
                                                :   sScope(i_sScope), bIsBegin(true) {}
    virtual             ~DT_MupMember();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const String  &     Scope() const           { return sScope; }
    bool                IsBegin() const         { return bIsBegin; }

  private:
    String              sScope;
    bool                bIsBegin;
};

class DT_MupConst : public DT_Dsapi
{
  public:
                        DT_MupConst(
                            const char *        i_sConstText )
                                                :   sConstText(i_sConstText) {}
    virtual             ~DT_MupConst();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const char *        GetText() const         { return sConstText; }

  private:
    String              sConstText;             /// Without HTML.
};

class DT_Style : public DT_MLTag
{
  public:
                        DT_Style(
                            const char *        i_sPlainHtmlTag,
                            bool                i_bNewLine )
                                                : sText(i_sPlainHtmlTag), bNewLine(i_bNewLine) {}
    virtual             ~DT_Style();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const char *        GetText() const         { return sText; }
    bool                IsStartOfNewLine() const
                                                { return bNewLine; }
  private:
    String              sText;                  /// With HTML.
    E_Kind              eKind;
    bool                bNewLine;
};

class DT_EOL : public DT_Dsapi
{
  public:
                        DT_EOL() {}
    virtual             ~DT_EOL();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    virtual bool        IsWhiteOnly() const;
};

class DT_AtTag : public ary::inf::AtTag2
{
  public:
    void                AddToken(
                            DYN ary::inf::DocuToken &
                                                let_drToken )
                                                {   aText.AddToken(let_drToken); }
    void                SetName(
                            const char *        i_sName )
                                                { sTitle = i_sName; }

  protected:
                        DT_AtTag(
                            const char *        i_sTitle )
                                                :   ary::inf::AtTag2(i_sTitle) {}
};

class DT_StdAtTag : public DT_AtTag
{
  public:
    explicit            DT_StdAtTag(
                            const char *        i_sTitle )
                                                :   DT_AtTag(i_sTitle) {}
    virtual             ~DT_StdAtTag();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
};

class DT_SeeAlsoAtTag : public DT_AtTag
{
  public:
                        DT_SeeAlsoAtTag()       :   DT_AtTag("") {}
    virtual             ~DT_SeeAlsoAtTag();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const String  &     LinkText() const        { return sTitle; }  // Missbrauch von sTitle
};

class DT_ParameterAtTag : public DT_AtTag
{
  public:
                        DT_ParameterAtTag()     :   DT_AtTag("") {}
    virtual             ~DT_ParameterAtTag();

    void                SetTitle(
                            const char *        i_sTitle );
    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
};

class DT_SinceAtTag : public DT_AtTag
{
  public:
                        DT_SinceAtTag()     :   DT_AtTag("Since version") {}
    virtual             ~DT_SinceAtTag();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
};

}   // namespace dsapi
}   // namespace csi

#endif

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

#ifndef CSI_DSAPI_D_TOKEN_HXX
#define CSI_DSAPI_D_TOKEN_HXX

// BASE CLASSES
#include <ary_i/ci_text2.hxx>
#include <ary_i/ci_atag2.hxx>

namespace ary
{
namespace inf
{
    class DocumentationDisplay;
}
}

namespace csi
{
namespace dsapi
{

using ary::inf::DocumentationDisplay;

class DT_Dsapi : public ary::inf::DocuToken
{
  public:
    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const  = 0;
    virtual bool        IsWhiteOnly() const;
};

class DT_TextToken : public DT_Dsapi
{
  public:
    explicit            DT_TextToken(
                            const char *        i_sText )
                                                :   sText(i_sText) {}
    explicit            DT_TextToken(
                            const String &      i_sText )
                                                :   sText(i_sText) {}
    virtual             ~DT_TextToken();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const char *        GetText() const         { return sText; }
    const String &      GetTextStr() const      { return sText; }

    String &            Access_Text()           { return sText; }

    virtual bool        IsWhiteOnly() const;

  private:
    String              sText;
};

class DT_White : public DT_Dsapi
{
  public:
                        DT_White() {}
    virtual             ~DT_White();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    virtual bool        IsWhiteOnly() const;
};

class DT_MLTag : public DT_Dsapi
{
  public:
    enum E_Kind
    {
        k_unknown = 0,
        k_begin,
        k_end,
        k_single
    };
};

class DT_MupType : public DT_MLTag
{
  public:
    explicit            DT_MupType(             /// Constructor for End-Tag
                            bool                )   /// Must be there, but is not evaluated.
                                                :   bIsBegin(false) {}
    explicit            DT_MupType(             /// Constructor for Begin-Tag
                            const String &      i_sScope )
                                                :   sScope(i_sScope), bIsBegin(true) {}
    virtual             ~DT_MupType();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const String  &     Scope() const           { return sScope; }
    bool                IsBegin() const         { return bIsBegin; }

  private:
    String              sScope;
    bool                bIsBegin;
};

class DT_MupMember : public DT_MLTag
{
  public:
    explicit            DT_MupMember(           /// Constructor for End-Tag
                            bool                )   /// Must be there, but is not evaluated.
                                                :   bIsBegin(false) {}
                        DT_MupMember(           /// Constructor for Begin-Tag
                            const String &      i_sScope )
                                                :   sScope(i_sScope), bIsBegin(true) {}
    virtual             ~DT_MupMember();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const String  &     Scope() const           { return sScope; }
    bool                IsBegin() const         { return bIsBegin; }

  private:
    String              sScope;
    bool                bIsBegin;
};

class DT_MupConst : public DT_Dsapi
{
  public:
                        DT_MupConst(
                            const char *        i_sConstText )
                                                :   sConstText(i_sConstText) {}
    virtual             ~DT_MupConst();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const char *        GetText() const         { return sConstText; }

  private:
    String              sConstText;             /// Without HTML.
};

class DT_Style : public DT_MLTag
{
  public:
                        DT_Style(
                            const char *        i_sPlainHtmlTag,
                            bool                i_bNewLine )
                                                : sText(i_sPlainHtmlTag), bNewLine(i_bNewLine) {}
    virtual             ~DT_Style();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const char *        GetText() const         { return sText; }
    bool                IsStartOfNewLine() const
                                                { return bNewLine; }
  private:
    String              sText;                  /// With HTML.
    E_Kind              eKind;
    bool                bNewLine;
};

class DT_EOL : public DT_Dsapi
{
  public:
                        DT_EOL() {}
    virtual             ~DT_EOL();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    virtual bool        IsWhiteOnly() const;
};

class DT_AtTag : public ary::inf::AtTag2
{
  public:
    void                AddToken(
                            DYN ary::inf::DocuToken &
                                                let_drToken )
                                                {   aText.AddToken(let_drToken); }
    void                SetName(
                            const char *        i_sName )
                                                { sTitle = i_sName; }

  protected:
                        DT_AtTag(
                            const char *        i_sTitle )
                                                :   ary::inf::AtTag2(i_sTitle) {}
};

class DT_StdAtTag : public DT_AtTag
{
  public:
    explicit            DT_StdAtTag(
                            const char *        i_sTitle )
                                                :   DT_AtTag(i_sTitle) {}
    virtual             ~DT_StdAtTag();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
};

class DT_SeeAlsoAtTag : public DT_AtTag
{
  public:
                        DT_SeeAlsoAtTag()       :   DT_AtTag("") {}
    virtual             ~DT_SeeAlsoAtTag();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
    const String  &     LinkText() const        { return sTitle; }  // Missbrauch von sTitle
};

class DT_ParameterAtTag : public DT_AtTag
{
  public:
                        DT_ParameterAtTag()     :   DT_AtTag("") {}
    virtual             ~DT_ParameterAtTag();

    void                SetTitle(
                            const char *        i_sTitle );
    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
};

class DT_SinceAtTag : public DT_AtTag
{
  public:
                        DT_SinceAtTag()     :   DT_AtTag("Since version") {}
    virtual             ~DT_SinceAtTag();

    virtual void        DisplayAt(
                            DocumentationDisplay &
                                                o_rDisplay ) const;
};

}   // namespace dsapi
}   // namespace csi

#endif

<|endoftext|>