<commit_before>#include "Logger.h"

#include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <ctime>

/* static */ Logger& Logger::GetDefaultLogger()
{
	static Logger defaultLogger{ std::string("rendeer.log"), true };
	return defaultLogger;
}

/* static */ std::string Logger::GetStateDescription(bool variable)
{
	return (variable) ? "enabled" : "disabled";
}

Logger::Logger()
{
}

Logger::Logger(std::string logFilePath, bool logToTerminal)
	: terminalOutputEnabled{ logToTerminal }
{
	// Set up log file output stream
	try
	{
		logFileStream.reset(new std::ofstream(logFilePath.c_str()));
		logFileStream->exceptions(std::ofstream::failbit);
	}
	catch (std::ios_base::failure& failure)
	{
		std::cout
			<< "Error: could not open log file with name: \""
			<< logFilePath << "\" (error code " << failure.code() << "). "
			<< "Reason: " << failure.what() << "."
		<< std::endl;
	}
}

Logger::~Logger()
{
}

void Logger::SetTerminalOutputEnabled(bool enabled)
{
	this->terminalOutputEnabled = enabled;
}

void Logger::SetPreferredLineLength(int length)
{
	this->preferredLineLength = length;
}

void Logger::LogHeading(std::string heading) const
{
	LogHorizontalDivider('=');
	Log(heading);
	LogHorizontalDivider('=');
}

void Logger::LogSubheading(std::string subheading) const
{
	std::stringstream formattedSubheading;

	int subheadingLength = static_cast<int>(subheading.length());
	int remainingLength = preferredLineLength - subheadingLength;
	if (remainingLength > 0)
	{
		int paddingOnEachSide = remainingLength / 2 - 1;
		std::string padding = GenerateHorizontalDivider('-', paddingOnEachSide);

		formattedSubheading
			<< padding << " "
			<< subheading
			<< " " << padding;
	}

	LogEmptyLine();
	Log(formattedSubheading.str());
}

void Logger::Log(std::string message) const
{
	if (terminalOutputEnabled)
	{
		std::cout << message << std::endl;
	}

	if (logFileStream)
	{
		(*logFileStream) << message << std::endl;
	}
}

void Logger::LogHorizontalDivider(char charToUse) const
{
	std::string divider = GenerateHorizontalDivider(charToUse, this->preferredLineLength);
	Log(divider);
}

void Logger::LogEmptyLine() const
{
	Log("");
}

void Logger::LogTimestamp() const
{
	// TODO: When a timer exists, also measure milliseconds, etc.
	time_t currentTime = time(0);
	tm *localTime = localtime(&currentTime);

	std::stringstream timestream;
	timestream
		<< "Current time: "
		<< std::setfill('0') << std::setw(2) << (localTime->tm_hour) << ":"
		<< std::setfill('0') << std::setw(2) << (localTime->tm_min) << ":"
		<< std::setfill('0') << std::setw(2) << (localTime->tm_sec);

	Log(timestream.str());
}

std::string Logger::GenerateHorizontalDivider(char charToUse, int length) const
{
	assert(length >= 0);

	std::stringstream divider;

	int charactersLeft = length;
	while (charactersLeft-- > 0)
	{
		divider << charToUse;
	}

	return divider.str();
}

<commit_msg>Fix LogSubheading padding error<commit_after>#include "Logger.h"

#include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <ctime>

/* static */ Logger& Logger::GetDefaultLogger()
{
	static Logger defaultLogger{ std::string("rendeer.log"), true };
	return defaultLogger;
}

/* static */ std::string Logger::GetStateDescription(bool variable)
{
	return (variable) ? "enabled" : "disabled";
}

Logger::Logger()
{
}

Logger::Logger(std::string logFilePath, bool logToTerminal)
	: terminalOutputEnabled{ logToTerminal }
{
	// Set up log file output stream
	try
	{
		logFileStream.reset(new std::ofstream(logFilePath.c_str()));
		logFileStream->exceptions(std::ofstream::failbit);
	}
	catch (std::ios_base::failure& failure)
	{
		std::cout
			<< "Error: could not open log file with name: \""
			<< logFilePath << "\" (error code " << failure.code() << "). "
			<< "Reason: " << failure.what() << "."
		<< std::endl;
	}
}

Logger::~Logger()
{
}

void Logger::SetTerminalOutputEnabled(bool enabled)
{
	this->terminalOutputEnabled = enabled;
}

void Logger::SetPreferredLineLength(int length)
{
	this->preferredLineLength = length;
}

void Logger::LogHeading(std::string heading) const
{
	LogHorizontalDivider('=');
	Log(heading);
	LogHorizontalDivider('=');
}

void Logger::LogSubheading(std::string subheading) const
{
	std::stringstream formattedSubheading;

	int subheadingLength = static_cast<int>(subheading.length());
	int remainingLength = preferredLineLength - subheadingLength;
	if (remainingLength > 0)
	{
		const char paddingChar = '-';
		int paddingOnEachSide = remainingLength / 2;

		// Subtract one from padding, since there is a space as padding as well
		std::string paddingLeft = GenerateHorizontalDivider(paddingChar, paddingOnEachSide - 1);
		std::string paddingRight = paddingLeft;

		// If the subheading has an uneven length, add one extra padding character to one side
		if (subheadingLength % 2 == 0)
		{
			paddingRight += paddingChar;
		}

		formattedSubheading
			<< paddingLeft << " "
			<< subheading
			<< " " << paddingRight;
	}

	LogEmptyLine();
	Log(formattedSubheading.str());
}

void Logger::Log(std::string message) const
{
	if (terminalOutputEnabled)
	{
		std::cout << message << std::endl;
	}

	if (logFileStream)
	{
		(*logFileStream) << message << std::endl;
	}
}

void Logger::LogHorizontalDivider(char charToUse) const
{
	std::string divider = GenerateHorizontalDivider(charToUse, this->preferredLineLength);
	Log(divider);
}

void Logger::LogEmptyLine() const
{
	Log("");
}

void Logger::LogTimestamp() const
{
	// TODO: When a timer exists, also measure milliseconds, etc.
	time_t currentTime = time(0);
	tm *localTime = localtime(&currentTime);

	std::stringstream timestream;
	timestream
		<< "Current time: "
		<< std::setfill('0') << std::setw(2) << (localTime->tm_hour) << ":"
		<< std::setfill('0') << std::setw(2) << (localTime->tm_min) << ":"
		<< std::setfill('0') << std::setw(2) << (localTime->tm_sec);

	Log(timestream.str());
}

std::string Logger::GenerateHorizontalDivider(char charToUse, int length) const
{
	assert(length >= 0);

	std::stringstream divider;

	int charactersLeft = length;
	while (charactersLeft-- > 0)
	{
		divider << charToUse;
	}

	return divider.str();
}

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Canvas.h"

#include "Kernel.h"

#include <cstring>

namespace scv {

#define PI_2 6.28318530717958
Canvas::Canvas(const scv::Point &p1, const scv::Point &p2) : Component(p1, p2) {
   setType(Component::CANVAS);
}

void Canvas::display()
{
   static Kernel *kernel = Kernel::getInstance();
   static Scissor *scissor = Scissor::getInstance();

   update();

   if (_isVisible == false) return;

   Point currPosition = getAbsolutePosition();

   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   gluOrtho2D(0, getWidth(), getHeight(), 0);

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();

   glViewport(currPosition.x, kernel->getHeight() - (getHeight() + currPosition.y), getWidth(), getHeight());

   scissor->pushScissor(getScissor());
   glPushAttrib(GL_ALL_ATTRIB_BITS);

   glClearColor(1.f, 1.f, 1.f, 1.f);
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

   glDisable(GL_TEXTURE_2D);

   render();

   glPopAttrib();

   scissor->popScissor();

   glDisable(GL_DEPTH_TEST);
   glDisable(GL_LIGHTING);

   if (glUseProgram) glUseProgram(0);

   kernel->applyDefaultTransformMatrix();
}

void Canvas::point(int x, int y)
{
   glBegin(GL_POINTS);
      glVertex2d(x, y);
   glEnd();
}

void Canvas::line( int x1, int y1, int x2, int y2 )
{
   glBegin(GL_LINES);
      glVertex2d(x1, y1);
      glVertex2d(x2, y2);
   glEnd();
}

void Canvas::rect( int x1, int y1, int x2, int y2 )
{
   glBegin(GL_LINE_LOOP);
      glVertex2d(x1, y1);
      glVertex2d(x1, y2);
      glVertex2d(x2, y2);
      glVertex2d(x2, y1);
   glEnd();
}

void Canvas::rectFill( int x1, int y1, int x2, int y2 )
{
   glBegin(GL_QUADS);
      glVertex2d(x1, y1);
      glVertex2d(x1, y2);
      glVertex2d(x2, y2);
      glVertex2d(x2, y1);
   glEnd();
}

void Canvas::polygon(float vx[], float vy[], int elems)
{
   int cont;
   glBegin(GL_LINE_LOOP);
      for(cont=0; cont<elems; cont++)
      {
         glVertex2d(vx[cont], vy[cont]);
      }
   glEnd();

}

void Canvas::polygonFill(float vx[], float vy[], int elems)
{
   int cont;
   glBegin(GL_POLYGON);
      for(cont=0; cont<elems; cont++)
      {
         glVertex2d(vx[cont], vy[cont]);
      }
   glEnd();

}

void Canvas::text(int x, int y, const char *t)
{
    int tam = strlen(t);
    int c;

    for(c=0; c<tam; c++)
    {
      glRasterPos2i(x + c*10, y);
      glutBitmapCharacter(GLUT_BITMAP_8_BY_13, t[c]);
    }
}

void Canvas::clear(float r, float g, float b)
{
   glClearColor( r, g, b, 1 );
}

void Canvas::circle( int x, int y, int raio, int div )
{
   double ang, x1, y1;
   double inc = PI_2/div;
   glBegin(GL_LINE_LOOP);
      for(ang=0; ang<6.27; ang+=inc)
      {
         x1 = (cos(ang)*raio);
         y1 = (sin(ang)*raio);
         glVertex2d(x1+x, y1+y);
      }
   glEnd();
}

void Canvas::circleFill( int x, int y, int raio, int div )
{
   double ang, x1, y1;
   double inc = PI_2/div;
   glBegin(GL_POLYGON);
      for(ang=0; ang<6.27; ang+=inc)
      {
         x1 = (cos(ang)*raio);
         y1 = (sin(ang)*raio);
         glVertex2d(x1+x, y1+y);
      }
   glEnd();
}

void Canvas::color(float r, float g, float b)
{
   glColor3d(r, g, b  );
}

} // namespace scv
<commit_msg>operacoes relativas a render de imagens<commit_after>#include "stdafx.h"
#include "Canvas.h"

#include "Kernel.h"

#include <cstring>

namespace scv {

#define PI_2 6.28318530717958
Canvas::Canvas(const scv::Point &p1, const scv::Point &p2) : Component(p1, p2) {
   setType(Component::CANVAS);
}

void Canvas::display()
{
   static Kernel *kernel = Kernel::getInstance();
   static Scissor *scissor = Scissor::getInstance();

   update();

   if (_isVisible == false) return;

   Point currPosition = getAbsolutePosition();

   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   gluOrtho2D(0, getWidth(), getHeight(), 0);

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();

   glViewport(currPosition.x, kernel->getHeight() - (getHeight() + currPosition.y), getWidth(), getHeight());

   scissor->pushScissor(getScissor());
   glPushAttrib(GL_ALL_ATTRIB_BITS);

   glClearColor(1.f, 1.f, 1.f, 1.f);
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

   //removido - Pozzer
   //para permitir desenhar linhas e outros objetos sem textura.
   //o unico elemento que usa textura eh a classe Image, que agora habilita a textura a cada render()
   //e retorna ao estado inicial apos a execucao. glPushAttrib ()
   glDisable(GL_TEXTURE_2D);

   render();

   glPopAttrib();

   scissor->popScissor();

   glDisable(GL_DEPTH_TEST);
   glDisable(GL_LIGHTING);

   if (glUseProgram) glUseProgram(0);

   kernel->applyDefaultTransformMatrix();
}

void Canvas::point(int x, int y)
{
   glBegin(GL_POINTS);
      glVertex2d(x, y);
   glEnd();
}

void Canvas::line( int x1, int y1, int x2, int y2 )
{
   glBegin(GL_LINES);
      glVertex2d(x1, y1);
      glVertex2d(x2, y2);
   glEnd();
}

void Canvas::rect( int x1, int y1, int x2, int y2 )
{
   glBegin(GL_LINE_LOOP);
      glVertex2d(x1, y1);
      glVertex2d(x1, y2);
      glVertex2d(x2, y2);
      glVertex2d(x2, y1);
   glEnd();
}

void Canvas::rectFill( int x1, int y1, int x2, int y2 )
{
   glBegin(GL_QUADS);
      glVertex2d(x1, y1);
      glVertex2d(x1, y2);
      glVertex2d(x2, y2);
      glVertex2d(x2, y1);
   glEnd();
}

void Canvas::polygon(float vx[], float vy[], int elems)
{
   int cont;
   glBegin(GL_LINE_LOOP);
      for(cont=0; cont<elems; cont++)
      {
         glVertex2d(vx[cont], vy[cont]);
      }
   glEnd();

}

void Canvas::polygonFill(float vx[], float vy[], int elems)
{
   int cont;
   glBegin(GL_POLYGON);
      for(cont=0; cont<elems; cont++)
      {
         glVertex2d(vx[cont], vy[cont]);
      }
   glEnd();

}

void Canvas::text(int x, int y, const char *t)
{
    int tam = strlen(t);
    int c;

    for(c=0; c<tam; c++)
    {
      glRasterPos2i(x + c*10, y);
      glutBitmapCharacter(GLUT_BITMAP_8_BY_13, t[c]);
    }
}

void Canvas::clear(float r, float g, float b)
{
   glClearColor( r, g, b, 1 );
}

void Canvas::circle( int x, int y, int raio, int div )
{
   double ang, x1, y1;
   double inc = PI_2/div;
   glBegin(GL_LINE_LOOP);
      for(ang=0; ang<6.27; ang+=inc)
      {
         x1 = (cos(ang)*raio);
         y1 = (sin(ang)*raio);
         glVertex2d(x1+x, y1+y);
      }
   glEnd();
}

void Canvas::circleFill( int x, int y, int raio, int div )
{
   double ang, x1, y1;
   double inc = PI_2/div;
   glBegin(GL_POLYGON);
      for(ang=0; ang<6.27; ang+=inc)
      {
         x1 = (cos(ang)*raio);
         y1 = (sin(ang)*raio);
         glVertex2d(x1+x, y1+y);
      }
   glEnd();
}

void Canvas::color(float r, float g, float b)
{
   glColor3d(r, g, b  );
}

} // namespace scv
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

/*! \file ospray/common/Thread.h \brief Abstraction for a Thread object */

#include "Thread.h"
// embree
# include "common/sys/thread.h"

namespace ospray {

  void ospray_Thread_runThread(void *arg)
  {
    Thread *t = (Thread *)arg;
    if (t->desiredThreadID >= 0)
      embree::setAffinity(t->desiredThreadID);

    t->run();
  }

  void Thread::join()
  {
    embree::join(tid);
  }

  /*!  start thread execution */
  void Thread::start(int threadID)
  {
    desiredThreadID = threadID;
    this->tid = embree::createThread(&ospray_Thread_runThread,this);
  }

}

<commit_msg>double-checking affinity<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

/*! \file ospray/common/Thread.h \brief Abstraction for a Thread object */

#include "Thread.h"
// embree
# include "common/sys/thread.h"

namespace ospray {

  void ospray_Thread_runThread(void *arg)
  {
    Thread *t = (Thread *)arg;
    if (t->desiredThreadID >= 0) {
      printf("pinning to thread %i\n",t->desiredThreadID);
      embree::setAffinity(t->desiredThreadID);
    }

    t->run();
  }

  void Thread::join()
  {
    embree::join(tid);
  }

  /*!  start thread execution */
  void Thread::start(int threadID)
  {
    desiredThreadID = threadID;
    this->tid = embree::createThread(&ospray_Thread_runThread,this);
  }

}

<|endoftext|>


<commit_before>/*
  Q Light Controller Plus
  previewcontext.cpp

  Copyright (c) Massimo Callegari

  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <QQmlContext>
#include <QQuickItem>

#include "previewcontext.h"
#include "doc.h"

PreviewContext::PreviewContext(QQuickView *view, Doc *doc, QString name, QObject *parent)
    : QObject(parent)
    , m_view(view)
    , m_mainView(view)
    , m_doc(doc)
    , m_name(name)
    , m_title(name)
    , m_page(0)
    , m_enabled(false)
    , m_detached(false)
{
    //connect(m_doc, &Doc::loaded, this, &PreviewContext::slotRefreshView);
}

QString PreviewContext::contextResource() const
{
    return m_resource;
}

void PreviewContext::setContextResource(QString res)
{
    m_resource = res;
}

void PreviewContext::enableContext(bool enable)
{
    m_enabled = enable;
}

bool PreviewContext::isEnabled()
{
    return m_enabled;
}

void PreviewContext::setUniverseFilter(quint32 universeFilter)
{
    m_universeFilter = universeFilter;
}

QQuickView *PreviewContext::view()
{
    return m_view;
}

QQuickItem *PreviewContext::contextItem()
{
    return m_contextItem;
}

void PreviewContext::setContextItem(QQuickItem *item)
{
    m_contextItem = item;
}

QString PreviewContext::name() const
{
    return m_name;
}

QString PreviewContext::contextTitle() const
{
    return m_title;
}

void PreviewContext::setContextTitle(QString title)
{
    m_title = title;
}

int PreviewContext::contextPage() const
{
    return m_page;
}

void PreviewContext::setContextPage(int page)
{
    m_page = page;
}

bool PreviewContext::detached() const
{
    return m_detached;
}

void PreviewContext::setDetached(bool detached)
{
    if (m_detached == detached)
        return;

    if (detached == true)
    {
        /** Create a new Quick View, as a true separate window */
        ContextQuickView *cqView = new ContextQuickView();
        m_view = cqView;
        connect(cqView, &ContextQuickView::keyPressed, this, &PreviewContext::keyPressed);
        connect(cqView, &ContextQuickView::keyReleased, this, &PreviewContext::keyReleased);

        /** Copy all the global properties of the main context into the detached one.
         *  This is a bit ugly, but I guess it is a downside of the QML programming */
        m_view->rootContext()->setContextProperty("qlcplus", m_mainView->rootContext()->contextProperty("qlcplus"));
        m_view->rootContext()->setContextProperty("screenPixelDensity", m_mainView->rootContext()->contextProperty("screenPixelDensity"));
        m_view->rootContext()->setContextProperty("ioManager", m_mainView->rootContext()->contextProperty("ioManager"));
        m_view->rootContext()->setContextProperty("fixtureBrowser", m_mainView->rootContext()->contextProperty("fixtureBrowser"));
        m_view->rootContext()->setContextProperty("fixtureManager", m_mainView->rootContext()->contextProperty("fixtureManager"));
        m_view->rootContext()->setContextProperty("fixtureGroupEditor", m_mainView->rootContext()->contextProperty("fixtureGroupEditor"));
        m_view->rootContext()->setContextProperty("functionManager", m_mainView->rootContext()->contextProperty("functionManager"));
        m_view->rootContext()->setContextProperty("contextManager", m_mainView->rootContext()->contextProperty("contextManager"));
        m_view->rootContext()->setContextProperty("virtualConsole", m_mainView->rootContext()->contextProperty("virtualConsole"));
        m_view->rootContext()->setContextProperty("showManager", m_mainView->rootContext()->contextProperty("showManager"));
        m_view->rootContext()->setContextProperty("actionManager", m_mainView->rootContext()->contextProperty("actionManager"));
        m_view->rootContext()->setContextProperty("View2D", m_mainView->rootContext()->contextProperty("View2D"));

        /** Set the fundamental properties to allow the detached context to properly load */
        m_view->rootContext()->setContextProperty("viewSource", contextResource());
        m_view->rootContext()->setContextProperty("contextName", name());
        m_view->rootContext()->setContextProperty("contextPage", contextPage());

        /** Finally, load the context wrapper and show it on the screen */
        m_view->setSource(QUrl("qrc:/WindowLoader.qml"));

        m_view->setTitle(contextTitle());
        m_view->setIcon(QIcon(":/qlcplus.svg"));

        m_view->setGeometry(0, 0, 800, 600);
        m_view->show();

        connect(m_view, SIGNAL(closing(QQuickCloseEvent*)), this, SLOT(slotWindowClosing()));
    }
    else
    {
        ContextQuickView *cqView = qobject_cast<ContextQuickView *>(m_view);
        disconnect(cqView, &ContextQuickView::keyPressed, this, &PreviewContext::keyPressed);
        disconnect(cqView, &ContextQuickView::keyReleased, this, &PreviewContext::keyReleased);
        m_view->deleteLater();
        m_view = m_mainView;
    }

    m_detached = detached;
}

void PreviewContext::handleKeyEvent(QKeyEvent *e, bool pressed)
{
    Q_UNUSED(e)
    Q_UNUSED(pressed)
}

void PreviewContext::slotWindowClosing()
{
    QMetaObject::invokeMethod(m_view->rootObject(), "closeWindow", Qt::AutoConnection);
}

void PreviewContext::slotRefreshView()
{

}

void ContextQuickView::keyPressEvent(QKeyEvent *e)
{
    emit keyPressed(e);
    QQuickView::keyPressEvent(e);
}

void ContextQuickView::keyReleaseEvent(QKeyEvent *e)
{
    emit keyReleased(e);
    QQuickView::keyReleaseEvent(e);
}
<commit_msg>qmlui: copy 3d view reference also to a detached context<commit_after>/*
  Q Light Controller Plus
  previewcontext.cpp

  Copyright (c) Massimo Callegari

  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <QQmlContext>
#include <QQuickItem>

#include "previewcontext.h"
#include "doc.h"

PreviewContext::PreviewContext(QQuickView *view, Doc *doc, QString name, QObject *parent)
    : QObject(parent)
    , m_view(view)
    , m_mainView(view)
    , m_doc(doc)
    , m_name(name)
    , m_title(name)
    , m_page(0)
    , m_enabled(false)
    , m_detached(false)
{
    //connect(m_doc, &Doc::loaded, this, &PreviewContext::slotRefreshView);
}

QString PreviewContext::contextResource() const
{
    return m_resource;
}

void PreviewContext::setContextResource(QString res)
{
    m_resource = res;
}

void PreviewContext::enableContext(bool enable)
{
    m_enabled = enable;
}

bool PreviewContext::isEnabled()
{
    return m_enabled;
}

void PreviewContext::setUniverseFilter(quint32 universeFilter)
{
    m_universeFilter = universeFilter;
}

QQuickView *PreviewContext::view()
{
    return m_view;
}

QQuickItem *PreviewContext::contextItem()
{
    return m_contextItem;
}

void PreviewContext::setContextItem(QQuickItem *item)
{
    m_contextItem = item;
}

QString PreviewContext::name() const
{
    return m_name;
}

QString PreviewContext::contextTitle() const
{
    return m_title;
}

void PreviewContext::setContextTitle(QString title)
{
    m_title = title;
}

int PreviewContext::contextPage() const
{
    return m_page;
}

void PreviewContext::setContextPage(int page)
{
    m_page = page;
}

bool PreviewContext::detached() const
{
    return m_detached;
}

void PreviewContext::setDetached(bool detached)
{
    if (m_detached == detached)
        return;

    if (detached == true)
    {
        /** Create a new Quick View, as a true separate window */
        ContextQuickView *cqView = new ContextQuickView();
        m_view = cqView;
        connect(cqView, &ContextQuickView::keyPressed, this, &PreviewContext::keyPressed);
        connect(cqView, &ContextQuickView::keyReleased, this, &PreviewContext::keyReleased);

        /** Copy all the global properties of the main context into the detached one.
         *  This is a bit ugly, but I guess it is a downside of the QML programming */
        m_view->rootContext()->setContextProperty("qlcplus", m_mainView->rootContext()->contextProperty("qlcplus"));
        m_view->rootContext()->setContextProperty("screenPixelDensity", m_mainView->rootContext()->contextProperty("screenPixelDensity"));
        m_view->rootContext()->setContextProperty("ioManager", m_mainView->rootContext()->contextProperty("ioManager"));
        m_view->rootContext()->setContextProperty("fixtureBrowser", m_mainView->rootContext()->contextProperty("fixtureBrowser"));
        m_view->rootContext()->setContextProperty("fixtureManager", m_mainView->rootContext()->contextProperty("fixtureManager"));
        m_view->rootContext()->setContextProperty("fixtureGroupEditor", m_mainView->rootContext()->contextProperty("fixtureGroupEditor"));
        m_view->rootContext()->setContextProperty("functionManager", m_mainView->rootContext()->contextProperty("functionManager"));
        m_view->rootContext()->setContextProperty("contextManager", m_mainView->rootContext()->contextProperty("contextManager"));
        m_view->rootContext()->setContextProperty("virtualConsole", m_mainView->rootContext()->contextProperty("virtualConsole"));
        m_view->rootContext()->setContextProperty("showManager", m_mainView->rootContext()->contextProperty("showManager"));
        m_view->rootContext()->setContextProperty("actionManager", m_mainView->rootContext()->contextProperty("actionManager"));
        m_view->rootContext()->setContextProperty("View2D", m_mainView->rootContext()->contextProperty("View2D"));
        m_view->rootContext()->setContextProperty("View3D", m_mainView->rootContext()->contextProperty("View3D"));

        /** Set the fundamental properties to allow the detached context to properly load */
        m_view->rootContext()->setContextProperty("viewSource", contextResource());
        m_view->rootContext()->setContextProperty("contextName", name());
        m_view->rootContext()->setContextProperty("contextPage", contextPage());

        /** Finally, load the context wrapper and show it on the screen */
        m_view->setSource(QUrl("qrc:/WindowLoader.qml"));

        m_view->setTitle(contextTitle());
        m_view->setIcon(QIcon(":/qlcplus.svg"));

        m_view->setGeometry(0, 0, 800, 600);
        m_view->show();

        connect(m_view, SIGNAL(closing(QQuickCloseEvent*)), this, SLOT(slotWindowClosing()));
    }
    else
    {
        ContextQuickView *cqView = qobject_cast<ContextQuickView *>(m_view);
        disconnect(cqView, &ContextQuickView::keyPressed, this, &PreviewContext::keyPressed);
        disconnect(cqView, &ContextQuickView::keyReleased, this, &PreviewContext::keyReleased);
        m_view->deleteLater();
        m_view = m_mainView;
    }

    m_detached = detached;
}

void PreviewContext::handleKeyEvent(QKeyEvent *e, bool pressed)
{
    Q_UNUSED(e)
    Q_UNUSED(pressed)
}

void PreviewContext::slotWindowClosing()
{
    QMetaObject::invokeMethod(m_view->rootObject(), "closeWindow", Qt::AutoConnection);
}

void PreviewContext::slotRefreshView()
{

}

void ContextQuickView::keyPressEvent(QKeyEvent *e)
{
    emit keyPressed(e);
    QQuickView::keyPressEvent(e);
}

void ContextQuickView::keyReleaseEvent(QKeyEvent *e)
{
    emit keyReleased(e);
    QQuickView::keyReleaseEvent(e);
}
<|endoftext|>


<commit_before>/*
 * FILE: NUMTSN.cpp
 *
 * @author: Arafat Hasan Jenin <opendoor.arafat[at]gmail[dot]com>
 *
 * LINK:
 *
 * DATE CREATED: 31-01-19 01:38:08 (+06)
 * LAST MODIFIED:
 *
 * VERDICT: Almost Accepted
 *
 * DEVELOPMENT HISTORY:
 * Date         Version     Description
 * --------------------------------------------------------------------
 * 31-01-19     1.0         Deleted code is debugged code.
 *
 *               _/  _/_/_/_/  _/      _/  _/_/_/  _/      _/
 *              _/  _/        _/_/    _/    _/    _/_/    _/
 *             _/  _/_/_/    _/  _/  _/    _/    _/  _/  _/
 *      _/    _/  _/        _/    _/_/    _/    _/    _/_/
 *       _/_/    _/_/_/_/  _/      _/  _/_/_/  _/      _/
 */

///////////////////////////////////////////////////////////////////////

#include <iostream>
#include <climits>
#include <cmath>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <utility>
#include <sstream>
#include <algorithm>
#include <stack>
#include <set>
#include <list>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <deque>
#include <vector>
#include <tuple>
#include <stdint.h> //uint32_t
#include <functional>
#include <bitset>
#include <unistd.h> // unsigned int sleep(unsigned int seconds);

using namespace std;

typedef long long           ll;
typedef double              lf;
typedef long double         llf;
typedef unsigned long long  ull;
typedef pair<int, int>      pii;
typedef vector<pii>         vpii;
typedef vector<int>         vi;
typedef vector<long long>   vl;

#define _USE_MATH_DEFINES

#define forr(i, a, b)   for (__typeof (a) i = (a); i <= (b); i++)
#define rof(i, b, a)    for (__typeof (a) i = (b); i >= (a); i--)
#define rep(i, n)       for (__typeof (n) i = 0; i < (n); i++)
#define forit(i, s)     for (__typeof ((s).end()) i = (s).begin(); i != (s).end(); ++i)
#define all(ar)         ar.begin(), ar.end()
#define fill(a, val)    memset((a), (val), sizeof((a)))
#define clr(a)          memset((a), 0, sizeof((a)))
#define sz(a)           (int) a.size()

#define pb              push_back

#ifndef ONLINE_JUDGE
    #define nl              cerr << '\n'
    #define sp              cerr << ' '
    #define ckk             cerr << "###############\n"
    #define debug1(x)       cerr << #x << ": " << (x) << '\n'
    #define debug2(x, y)    cerr << #x << ": " << (x) << '\t' << #y << ": " << (y) << '\n'
    #define debug3(x, y, z) cerr << #x << ": " << (x) << '\t' << #y << ": " << (y) << '\t' << #z << ": " << (z) << '\n'
#else
    #define nl
    #define sp
    #define ckk
    #define debug1(x)
    #define debug2(x, y)
    #define debug3(x, y, z)
#endif

#define PI              acos(-1.0)
#define INF             0x7fffffff
#define MOD             1000000007
#define EPS             1e-7
#define MAX             10000007 //1e7+7

////////////////////////// START HERE //////////////////////////

vector<int> aNum, bNum;
string a, b;

ll digitDP (int idx, int 3cnt, int 6cnt, int 9cnt, bool isSmall) {
    if (idx == (int) b.size()) return (3cnt == 6cnt and 6cnt == 9cnt);

    if (idx < (int) a.size()) return 0;

    ll res = 0;
}

ll call (string a, string b) {
    rep (i, a.size()) a[i] -= '0';
    rep (i, b.size()) b[i] -= '0';
    return digitDP (0, 0, 0, 0, 0);
}

int main() {
    ios_base::sync_with_stdio (false); cin.tie (0); cout.tie (0);
    int t;
    cin >> t;

    cout < < "asdf";
    while (t--) {
        cin >> a >> b;
        cout << call (a, b) << endl;
    }

    return 0;
}
<commit_msg>01-02-2019<commit_after>/*
 * FILE: NUMTSN.cpp
 *
 * @author: Arafat Hasan Jenin <opendoor.arafat[at]gmail[dot]com>
 *
 * LINK:
 *
 * DATE CREATED: 31-01-19 01:38:08 (+06)
 * LAST MODIFIED:
 *
 * VERDICT: Almost Accepted
 *
 * DEVELOPMENT HISTORY:
 * Date         Version     Description
 * --------------------------------------------------------------------
 * 31-01-19     1.0         Deleted code is debugged code.
 *
 *               _/  _/_/_/_/  _/      _/  _/_/_/  _/      _/
 *              _/  _/        _/_/    _/    _/    _/_/    _/
 *             _/  _/_/_/    _/  _/  _/    _/    _/  _/  _/
 *      _/    _/  _/        _/    _/_/    _/    _/    _/_/
 *       _/_/    _/_/_/_/  _/      _/  _/_/_/  _/      _/
 */

///////////////////////////////////////////////////////////////////////

#include <iostream>
#include <climits>
#include <cmath>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <utility>
#include <sstream>
#include <algorithm>
#include <stack>
#include <set>
#include <list>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <deque>
#include <vector>
#include <tuple>
#include <stdint.h> //uint32_t
#include <functional>
#include <bitset>
#include <unistd.h> // unsigned int sleep(unsigned int seconds);

using namespace std;

typedef long long           ll;
typedef double              lf;
typedef long double         llf;
typedef unsigned long long  ull;
typedef pair<int, int>      pii;
typedef vector<pii>         vpii;
typedef vector<int>         vi;
typedef vector<long long>   vl;

#define _USE_MATH_DEFINES

#define forr(i, a, b)   for (__typeof (a) i = (a); i <= (b); i++)
#define rof(i, b, a)    for (__typeof (a) i = (b); i >= (a); i--)
#define rep(i, n)       for (__typeof (n) i = 0; i < (n); i++)
#define forit(i, s)     for (__typeof ((s).end()) i = (s).begin(); i != (s).end(); ++i)
#define all(ar)         ar.begin(), ar.end()
#define fill(a, val)    memset((a), (val), sizeof((a)))
#define clr(a)          memset((a), 0, sizeof((a)))
#define sz(a)           (int) a.size()

#define pb              push_back

#ifndef ONLINE_JUDGE
    #define nl              cerr << '\n'
    #define sp              cerr << ' '
    #define ckk             cerr << "###############\n"
    #define debug1(x)       cerr << #x << ": " << (x) << '\n'
    #define debug2(x, y)    cerr << #x << ": " << (x) << '\t' << #y << ": " << (y) << '\n'
    #define debug3(x, y, z) cerr << #x << ": " << (x) << '\t' << #y << ": " << (y) << '\t' << #z << ": " << (z) << '\n'
#else
    #define nl
    #define sp
    #define ckk
    #define debug1(x)
    #define debug2(x, y)
    #define debug3(x, y, z)
#endif

#define PI              acos(-1.0)
#define INF             0x7fffffff
#define MOD             1000000007
#define EPS             1e-7
#define MAX             10000007 //1e7+7

////////////////////////// START HERE //////////////////////////

vector<int> aNum, bNum;
string a, b;

ll digitDP (int idx, int 3cnt, int 6cnt, int 9cnt, bool isSmall) {
    if (idx == (int) b.size()) return (3cnt == 6cnt and 6cnt == 9cnt);

    if (idx < (int) a.size()) return 0;

    ll res = 0;
}

ll call (string a, string b) {
    rep (i, a.size()) a[i] -= '0';
    rep (i, b.size()) b[i] -= '0';
    return digitDP (0, 0, 0, 0, 0);
}

int main() {
    ios_base::sync_with_stdio (false); cin.tie (0); cout.tie (0);
    int t;
    cin >> t;

    while (t--) {
        cin >> a >> b;
        cout << call (a, b) << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>// Author: Enrico Guiraud, Danilo Piparo CERN  9/2017

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

#ifndef ROOT_RTRIVIALTDS
#define ROOT_RTRIVIALTDS

#include "ROOT/RDF/RInterface.hxx"
#include "ROOT/RDataSource.hxx"

namespace ROOT {

namespace RDF {

class RTrivialDS final : public ROOT::RDF::RDataSource {
private:
   unsigned int fNSlots = 0U;
   ULong64_t fSize = 0ULL;
   bool fSkipEvenEntries = false;
   std::vector<std::pair<ULong64_t, ULong64_t>> fEntryRanges;
   std::vector<std::string> fColNames{"col0"};
   std::vector<ULong64_t> fCounter;
   std::vector<ULong64_t *> fCounterAddr;
   std::vector<void *> GetColumnReadersImpl(std::string_view name, const std::type_info &);

protected:
   std::string AsString() { return "trivial data source"; };

public:
   RTrivialDS(ULong64_t size, bool skipEvenEntries = false);
   // This ctor produces a data-source that returns infinite entries
   RTrivialDS();
   ~RTrivialDS();
   const std::vector<std::string> &GetColumnNames() const;
   bool HasColumn(std::string_view colName) const;
   std::string GetTypeName(std::string_view) const;
   std::vector<std::pair<ULong64_t, ULong64_t>> GetEntryRanges();
   bool SetEntry(unsigned int slot, ULong64_t entry);
   void SetNSlots(unsigned int nSlots);
   void Initialise();
   std::string GetLabel();
};

// Make a RDF wrapping a RTrivialDS with the specified amount of entries
RInterface<RDFDetail::RLoopManager, RTrivialDS> MakeTrivialDataFrame(ULong64_t size, bool skipEvenEntries = false);
// Make a RDF wrapping a RTrivialDS with infinite entries
RInterface<RDFDetail::RLoopManager, RTrivialDS> MakeTrivialDataFrame();

} // ns RDF

} // ns ROOT

#endif
<commit_msg>[DF][NFC] Make normal comment doxygen comment<commit_after>// Author: Enrico Guiraud, Danilo Piparo CERN  9/2017

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

#ifndef ROOT_RTRIVIALTDS
#define ROOT_RTRIVIALTDS

#include "ROOT/RDF/RInterface.hxx"
#include "ROOT/RDataSource.hxx"

namespace ROOT {

namespace RDF {

class RTrivialDS final : public ROOT::RDF::RDataSource {
private:
   unsigned int fNSlots = 0U;
   ULong64_t fSize = 0ULL;
   bool fSkipEvenEntries = false;
   std::vector<std::pair<ULong64_t, ULong64_t>> fEntryRanges;
   std::vector<std::string> fColNames{"col0"};
   std::vector<ULong64_t> fCounter;
   std::vector<ULong64_t *> fCounterAddr;
   std::vector<void *> GetColumnReadersImpl(std::string_view name, const std::type_info &);

protected:
   std::string AsString() { return "trivial data source"; };

public:
   RTrivialDS(ULong64_t size, bool skipEvenEntries = false);
   /// This ctor produces a data-source that returns infinite entries
   RTrivialDS();
   ~RTrivialDS();
   const std::vector<std::string> &GetColumnNames() const;
   bool HasColumn(std::string_view colName) const;
   std::string GetTypeName(std::string_view) const;
   std::vector<std::pair<ULong64_t, ULong64_t>> GetEntryRanges();
   bool SetEntry(unsigned int slot, ULong64_t entry);
   void SetNSlots(unsigned int nSlots);
   void Initialise();
   std::string GetLabel();
};

// Make a RDF wrapping a RTrivialDS with the specified amount of entries
RInterface<RDFDetail::RLoopManager, RTrivialDS> MakeTrivialDataFrame(ULong64_t size, bool skipEvenEntries = false);
// Make a RDF wrapping a RTrivialDS with infinite entries
RInterface<RDFDetail::RLoopManager, RTrivialDS> MakeTrivialDataFrame();

} // ns RDF

} // ns ROOT

#endif
<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>

#include <evm2wasm.h>

using namespace std;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
        return 1;
    }

    bool wast = false;
    if (argc == 3) {
        wast = (string(argv[2]) == "--wast");
        if (!wast) {
            cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
            return 1;
        }
    }

    ifstream input(argv[1]);
    if (!input.is_open()) {
        cerr << "File not found: " << argv[1] << endl;
        return 1;
    }

    string str(
        (std::istreambuf_iterator<char>(input)),
        std::istreambuf_iterator<char>()
    );

    if (wast) {
        cout << evm2wasm::evmhex2wast(str) << endl;
    } else {
        cout << evm2wasm::evmhex2wasm(str) << endl;
    }

    return 0;
}
<commit_msg>Clean input to evm2wasm CLI from any whitespace<commit_after>#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <algorithm>

#include <evm2wasm.h>

using namespace std;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
        return 1;
    }

    bool wast = false;
    if (argc == 3) {
        wast = (string(argv[2]) == "--wast");
        if (!wast) {
            cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
            return 1;
        }
    }

    ifstream input(argv[1]);
    if (!input.is_open()) {
        cerr << "File not found: " << argv[1] << endl;
        return 1;
    }

    string str(
        (std::istreambuf_iterator<char>(input)),
        std::istreambuf_iterator<char>()
    );

    // clean input of any whitespace (including space and new lines)
    str.erase(remove_if(str.begin(), str.end(), [](unsigned char x){return std::isspace(x);}), str.end());

    if (wast) {
        cout << evm2wasm::evmhex2wast(str) << endl;
    } else {
        cout << evm2wasm::evmhex2wasm(str) << endl;
    }

    return 0;
}
<|endoftext|>


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

  FILE    laszippertest.cpp

  CONTENTS

    This tool reads and writes point data in the LAS 1.X format compressed
    or uncompressed to test the laszipper and lasunzipper interfaces.

  PROGRAMMERS:

    martin.isenburg@gmail.com

  COPYRIGHT:

    (c) 2010-2011, Martin Isenburg, LASSO - tools to catch reality

    This is free software; you can redistribute and/or modify it under the
    terms of the GNU Lesser General Licence as published by the Free Software
    Foundation. See the COPYING file for more information.

    This software is distributed WITHOUT ANY WARRANTY and without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  CHANGE HISTORY:

    14 January 2011 -- mpg@flaxen.com adds randomness and commandline controls
    10 January 2011 -- licensing change for LGPL release and liblas integration
    13 December 2010 -- created to test the remodularized laszip compressor

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

#include "laszipper.hpp"
#include "lasunzipper.hpp"

#ifdef LZ_WIN32_VC6
#include <fstream.h>
#else
#include <istream>
#include <fstream>
using namespace std;
#endif

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

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

static double taketime()
{
  return (double)(clock())/CLOCKS_PER_SEC;
}

//---------------------------------------------------------------------------
// abstractions for doing I/O, which support VC6 streams, modern streams, and FILE*

class OStream
{
public:
  OStream(bool use_iostream, const char* filename) :
    m_use_iostream(use_iostream),
    m_filename(filename),
    ofile(NULL),
    streamo(NULL)
  {
    if (m_use_iostream)
    {
#ifdef LZ_WIN32_VC6
      ofb.open(filename, ios::out);
      ofb.setmode(filebuf::binary);
      streamo = new ostream(&ofb);
#else
      streamo = new ofstream();
      streamo->open(filename, std::ios::out | std::ios::binary );
#endif
    }
    else
    {
      ofile = fopen(filename, "wb");
    }
  };

  ~OStream()
  {
    if (m_use_iostream)
    {
      delete streamo;
#ifdef LZ_WIN32_VC6
      ofb.close();
#endif
    }
    else
    {
      if (ofile)
        fclose(ofile);
    }
  };

  bool m_use_iostream;
  const char* m_filename;
  FILE* ofile;
  filebuf ofb;
#ifdef LZ_WIN32_VC6
  ostream* streamo;
#else
  ofstream* streamo;
#endif
};

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

struct IStream
{
public:
  IStream(bool use_iostream, const char* filename) :
    m_use_iostream(use_iostream),
    m_filename(filename),
    ifile(NULL),
    streami(NULL)
  {
    if (m_use_iostream)
    {
#ifdef LZ_WIN32_VC6
      ifb.open(filename, ios::in);
      ifb.setmode(filebuf::binary);
      streami = new istream(&ifb);
#else
      streami = new ifstream();
      streami->open(filename, std::ios::in | std::ios::binary);
#endif
    }
    else
    {
      ifile = fopen(filename, "rb");
    }
  };

  ~IStream()
  {
    if (m_use_iostream)
    {
      delete streami;
#ifdef LZ_WIN32_VC6
      ifb.close();
#endif
    }
    else
    {
      if (ifile)
        fclose(ifile);
    }
  };

  bool m_use_iostream;
  const char* m_filename;
  FILE* ifile;
  filebuf ifb;
#ifdef LZ_WIN32_VC6
  istream* streami;
#else
  ifstream* streami;
#endif
};

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

#define NUM_ITEMS 5

class PointData
{
public:
  PointData()
  {
    num_items = NUM_ITEMS;

    items[0].type = LASitem::POINT10;
    items[0].size = 20;
    items[0].version = 0;

    items[1].type = LASitem::GPSTIME11;
    items[1].size = 8;
    items[1].version = 0;

    items[2].type = LASitem::RGB12;
    items[2].size = 6;
    items[2].version = 0;

    items[3].type = LASitem::WAVEPACKET13;
    items[3].size = 29;
    items[3].version = 0;

    items[4].type = LASitem::BYTE;
    items[4].size = 7;
    items[4].version = 0;

    unsigned int i;

    // compute the point size
    point_size = 0;
    for (i = 0; i < num_items; i++) point_size += items[i].size;

    // create the point data
    unsigned int point_offset = 0;
    point = new unsigned char*[num_items];
    point_data = new unsigned char[point_size];
    for (i = 0; i < num_items; i++)
    {
      point[i] = &(point_data[point_offset]);
      point_offset += items[i].size;
    }

    return;
  }

  ~PointData()
  {
    delete[] point;
    delete[] point_data;
    return;
  }

  unsigned int num_items;
  LASitem items[NUM_ITEMS];
  unsigned int point_size;
  unsigned char* point_data;
  unsigned char** point;
};

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

class Settings
{
public:
  Settings(unsigned int num_pts, bool random, bool use_stream) :
    num_points(num_pts),
    use_random(random),
    use_iostream(use_stream)
  {
    logfile = fopen("zippertest.log","w");
    return;
  }

  ~Settings()
  {
    fclose(logfile);
    return;
  }

  unsigned num_points;
  bool use_random;
  unsigned int seed;
  bool use_iostream;
  FILE* logfile;
};

static Settings* settings = NULL; // singleton

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

static void log(const char* format, ...)
{
  va_list args;

  va_start(args, format);
  vfprintf(stderr, format, args);
  va_end(args);
  fflush(stderr);

  va_start(args, format);
  vfprintf(settings->logfile, format, args);
  va_end(args);
  fflush(settings->logfile);

  return;
}

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

static LASzipper* make_zipper(LASzip* laszip)
{
  LASzipper* zipper = new LASzipper();
  int stat = zipper->setup(laszip);
  if (stat != 0)
  {
    log("ERROR: could not make laszipper\n");
    exit(1);
  }
  return zipper;
}

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

static void open_zipper(LASzipper* zipper, OStream* ost)
{
  int stat = 0;
  if (ost->m_use_iostream)
    stat = zipper->open(*ost->streamo);
  else
    stat = zipper->open(ost->ofile);
  if (stat != 0)
  {
    log("ERROR: could not open laszipper with %s\n", ost->m_filename);
    exit(1);
  }
}

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

static LASunzipper* make_unzipper(LASzip* laszip)
{
  LASunzipper* unzipper = new LASunzipper();
  int stat = unzipper->setup(laszip);
  if (stat != 0)
  {
    log("ERROR: could not make lasunzipper\n");
    exit(1);
  }
  return unzipper;
}

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

static void open_unzipper(LASunzipper* unzipper, IStream* ist)
{
  int stat = 0;
  if (ist->m_use_iostream)
    stat = unzipper->open(*ist->streami);
  else
    stat = unzipper->open(ist->ifile);
  if (stat != 0)
  {
    log("ERROR: could not open laszipper with %s\n", ist->m_filename);
    exit(1);
  }
}

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

static void write_points(LASzipper* zipper, PointData& data)
{
  if (zipper==NULL) // range coder test
    return;

  double start_time, end_time;
  unsigned char c;
  unsigned int i,j;
  unsigned int num_bytes;

  // the two branches of this IF are the same, except for the use of a random number;
  // we keep the random case separate, so that we can get fastest timing tests w/o random data
  if (settings->use_random)
  {
    srand(settings->seed);
    start_time = taketime();
    c = rand() % 256;
    for (i = 0; i < settings->num_points; i++)
    {
      for (j = 0; j < data.point_size; j++)
      {
        data.point_data[j] = c;
        c = rand() % 256;
      }
      zipper->write(data.point);
    }
    num_bytes = zipper->close();
    end_time = taketime();
  }
  else
  {
    start_time = taketime();
    c = 0;
    for (i = 0; i < settings->num_points; i++)
    {
      for (j = 0; j < data.point_size; j++)
      {
        data.point_data[j] = c;
        c++;
      }
      zipper->write(data.point);
    }
    num_bytes = zipper->close();
    end_time = taketime();
  }

  log("laszipper wrote %u bytes in %g seconds\n", num_bytes, end_time-start_time);

  return;
}

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

static void read_points(LASunzipper* unzipper, PointData& data)
{
  if (unzipper==NULL) // range coder test
    return;

  unsigned char c;
  unsigned int i,j;
  unsigned int num_errors, num_bytes;
  double start_time, end_time;

  start_time = taketime();
  num_errors = 0;

  if (settings->use_random)
  {
    srand(settings->seed);
    c = rand() % 256;
    for (i = 0; i < settings->num_points; i++)
    {
      unzipper->read(data.point);
      for (j = 0; j < data.point_size; j++)
      {
        if (data.point_data[j] != c)
        {
          log("%d %d %d != %d\n", i, j, data.point_data[j], c);
          num_errors++;
          if (num_errors > 20) break;
        }
        c = rand() % 256;
      }
      if (num_errors > 20) break;
    }
    num_bytes = unzipper->close();
    end_time = taketime();
  }
  else
  {
    c = 0;
    for (i = 0; i < settings->num_points; i++)
    {
      unzipper->read(data.point);
      for (j = 0; j < data.point_size; j++)
      {
        if (data.point_data[j] != c)
        {
          log("%d %d %d != %d\n", i, j, data.point_data[j], c);
          num_errors++;
          if (num_errors > 20) break;
        }
        c++;
      }
      if (num_errors > 20) break;
    }
    num_bytes = unzipper->close();
    end_time = taketime();
  }

  if (num_errors)
  {
    log("ERROR: with lasunzipper %d\n", num_errors);
    getc(stdin);
  }
  else
  {
    log("SUCCESS: lasunzipper read %u bytes in %g seconds\n", num_bytes, end_time-start_time);
  }

  return;
}

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

static void run_test(const char* filename, PointData& data, unsigned short compressor, unsigned short requested_version=0, unsigned short chunk_size=0)
{
  LASzip laszip;
  laszip.setup(data.num_items, data.items, compressor);
  if (requested_version) laszip.request_version(requested_version);
  if (chunk_size) laszip.set_chunk_size(chunk_size);

  LASzipper* laszipper = make_zipper(&laszip);
  OStream* ost = new OStream(settings->use_iostream, filename);
  open_zipper(laszipper, ost);
  write_points(laszipper, data);
  delete laszipper;
  delete ost;

  LASunzipper* lasunzipper = make_unzipper(&laszip);
  IStream* ist = new IStream(settings->use_iostream, filename);
  open_unzipper(lasunzipper, ist);
  read_points(lasunzipper, data);
  delete lasunzipper;
  delete ist;

  return;
}

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

int main(int argc, char *argv[])
{
  unsigned int num_points = 100000;
  bool use_iostream = false;
  bool run_forever = false;
  bool use_random = false;
  unsigned int user_seed = (unsigned int)time(NULL);

  for (int i=1; i<argc; i++)
  {
    const char* p = argv[i];
    if (strcmp(p,"-n")==0)
    {
      ++i;
      num_points = atoi(argv[i]);
    }
    else if (strcmp(p,"-s")==0)
    {
      use_iostream = true;
    }
    else if (strcmp(p,"-f")==0)
    {
      run_forever = true;
    }
    else if (strcmp(p,"-r")==0)
    {
      use_random = true;
    }
    else if (strcmp(p,"-x")==0)
    {
      ++i;
      user_seed = atoi(argv[i]);
    }
    else
    {
      fprintf(stderr, "Usage   ziptest [-n NUMBER] [-s] [-f] [-r]\n");
      fprintf(stderr, "   -n    number of points to process (default   100000)\n");
      fprintf(stderr, "   -s    use C++ stream I/O (default   use FILE* I/O)\n");
      fprintf(stderr, "   -f    run forever (default   run just one pass)\n");
      fprintf(stderr, "   -r    use random input data (default   use fixed data)\n");
      fprintf(stderr, "   -x    set random seed, instead of current time (default: use time)\n");
      exit(1);
    }
  }

  settings = new Settings(num_points, use_random, use_iostream);

  log("Settings:\n");
  log("  num_points=%u, use_iostream=%s, run_forever=%s, use_random=%s, user_seed=%d\n",
    num_points, use_iostream?"true":"false", run_forever?"true":"false", use_random?"true":"false", user_seed);

  settings->seed = user_seed;

  unsigned int run = 1;
  do
  {
  PointData data;

  // use a seed based on the current time
  if (run_forever && settings->use_random)
  {
    settings->seed = (unsigned int)time(NULL);
    log("Seed: %u\n", settings->seed);
  }

  run_test("test1.lax", data, LASZIP_COMPRESSOR_NONE);
  run_test("test2.lax", data, LASZIP_COMPRESSOR_DEFAULT);
  run_test("test3.lax", data, LASZIP_COMPRESSOR_DEFAULT, 2);
  run_test("test4.lax", data, LASZIP_COMPRESSOR_CHUNKED);
  run_test("test5.lax", data, LASZIP_COMPRESSOR_CHUNKED, 2);
  log("Finished %u runs\n\n", run);
  ++run;
  } while (run_forever);

  return 0;
}
<commit_msg>example with packing/unpacking of VLR<commit_after>/*
===============================================================================

  FILE    laszippertest.cpp

  CONTENTS

    This tool reads and writes point data in the LAS 1.X format compressed
    or uncompressed to test the laszipper and lasunzipper interfaces.

  PROGRAMMERS:

    martin.isenburg@gmail.com

  COPYRIGHT:

    (c) 2010-2011, Martin Isenburg, LASSO - tools to catch reality

    This is free software; you can redistribute and/or modify it under the
    terms of the GNU Lesser General Licence as published by the Free Software
    Foundation. See the COPYING file for more information.

    This software is distributed WITHOUT ANY WARRANTY and without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  CHANGE HISTORY:

    14 January 2011 -- mpg@flaxen.com adds randomness and commandline controls
    10 January 2011 -- licensing change for LGPL release and liblas integration
    13 December 2010 -- created to test the remodularized laszip compressor

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

#include "laszipper.hpp"
#include "lasunzipper.hpp"

#ifdef LZ_WIN32_VC6
#include <fstream.h>
#else
#include <istream>
#include <fstream>
using namespace std;
#endif

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

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

static double taketime()
{
  return (double)(clock())/CLOCKS_PER_SEC;
}

//---------------------------------------------------------------------------
// abstractions for doing I/O, which support VC6 streams, modern streams, and FILE*

class OStream
{
public:
  OStream(bool use_iostream, const char* filename) :
    m_use_iostream(use_iostream),
    m_filename(filename),
    ofile(NULL),
    streamo(NULL)
  {
    if (m_use_iostream)
    {
#ifdef LZ_WIN32_VC6
      ofb.open(filename, ios::out);
      ofb.setmode(filebuf::binary);
      streamo = new ostream(&ofb);
#else
      streamo = new ofstream();
      streamo->open(filename, std::ios::out | std::ios::binary );
#endif
    }
    else
    {
      ofile = fopen(filename, "wb");
    }
  };

  ~OStream()
  {
    if (m_use_iostream)
    {
      delete streamo;
#ifdef LZ_WIN32_VC6
      ofb.close();
#endif
    }
    else
    {
      if (ofile)
        fclose(ofile);
    }
  };

  bool m_use_iostream;
  const char* m_filename;
  FILE* ofile;
  filebuf ofb;
#ifdef LZ_WIN32_VC6
  ostream* streamo;
#else
  ofstream* streamo;
#endif
};

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

struct IStream
{
public:
  IStream(bool use_iostream, const char* filename) :
    m_use_iostream(use_iostream),
    m_filename(filename),
    ifile(NULL),
    streami(NULL)
  {
    if (m_use_iostream)
    {
#ifdef LZ_WIN32_VC6
      ifb.open(filename, ios::in);
      ifb.setmode(filebuf::binary);
      streami = new istream(&ifb);
#else
      streami = new ifstream();
      streami->open(filename, std::ios::in | std::ios::binary);
#endif
    }
    else
    {
      ifile = fopen(filename, "rb");
    }
  };

  ~IStream()
  {
    if (m_use_iostream)
    {
      delete streami;
#ifdef LZ_WIN32_VC6
      ifb.close();
#endif
    }
    else
    {
      if (ifile)
        fclose(ifile);
    }
  };

  bool m_use_iostream;
  const char* m_filename;
  FILE* ifile;
  filebuf ifb;
#ifdef LZ_WIN32_VC6
  istream* streami;
#else
  ifstream* streami;
#endif
};

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

#define NUM_ITEMS 5

class PointData
{
public:
  PointData()
  {
    num_items = NUM_ITEMS;

    items[0].type = LASitem::POINT10;
    items[0].size = 20;
    items[0].version = 0;

    items[1].type = LASitem::GPSTIME11;
    items[1].size = 8;
    items[1].version = 0;

    items[2].type = LASitem::RGB12;
    items[2].size = 6;
    items[2].version = 0;

    items[3].type = LASitem::WAVEPACKET13;
    items[3].size = 29;
    items[3].version = 0;

    items[4].type = LASitem::BYTE;
    items[4].size = 7;
    items[4].version = 0;

    unsigned int i;

    // compute the point size
    point_type = 5;
    point_size = 0;
    for (i = 0; i < num_items; i++) point_size += items[i].size;

    // create the point data
    unsigned int point_offset = 0;
    point = new unsigned char*[num_items];
    point_data = new unsigned char[point_size];
    for (i = 0; i < num_items; i++)
    {
      point[i] = &(point_data[point_offset]);
      point_offset += items[i].size;
    }

    return;
  }

  ~PointData()
  {
    delete[] point;
    delete[] point_data;
    return;
  }

  unsigned int num_items;
  LASitem items[NUM_ITEMS];
  unsigned char point_type;
  unsigned short point_size;
  unsigned char* point_data;
  unsigned char** point;
};

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

class Settings
{
public:
  Settings(unsigned int num_pts, bool random, bool use_stream) :
    num_points(num_pts),
    use_random(random),
    use_iostream(use_stream)
  {
    logfile = fopen("zippertest.log","w");
    return;
  }

  ~Settings()
  {
    fclose(logfile);
    return;
  }

  unsigned num_points;
  bool use_random;
  unsigned int seed;
  bool use_iostream;
  FILE* logfile;
};

static Settings* settings = NULL; // singleton

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

static void log(const char* format, ...)
{
  va_list args;

  va_start(args, format);
  vfprintf(stderr, format, args);
  va_end(args);
  fflush(stderr);

  va_start(args, format);
  vfprintf(settings->logfile, format, args);
  va_end(args);
  fflush(settings->logfile);

  return;
}

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

static LASzipper* make_zipper(LASzip* laszip)
{
  LASzipper* zipper = new LASzipper();
  int stat = zipper->setup(laszip);
  if (stat != 0)
  {
    log("ERROR: could not make laszipper\n");
    exit(1);
  }
  return zipper;
}

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

static void open_zipper(LASzipper* zipper, OStream* ost)
{
  int stat = 0;
  if (ost->m_use_iostream)
    stat = zipper->open(*ost->streamo);
  else
    stat = zipper->open(ost->ofile);
  if (stat != 0)
  {
    log("ERROR: could not open laszipper with %s\n", ost->m_filename);
    exit(1);
  }
}

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

static LASunzipper* make_unzipper(const LASzip* laszip)
{
  LASunzipper* unzipper = new LASunzipper();
  int stat = unzipper->setup(laszip);
  if (stat != 0)
  {
    log("ERROR: could not make lasunzipper\n");
    exit(1);
  }
  return unzipper;
}

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

static void open_unzipper(LASunzipper* unzipper, IStream* ist)
{
  int stat = 0;
  if (ist->m_use_iostream)
    stat = unzipper->open(*ist->streami);
  else
    stat = unzipper->open(ist->ifile);
  if (stat != 0)
  {
    log("ERROR: could not open laszipper with %s\n", ist->m_filename);
    exit(1);
  }
}

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

static void write_points(LASzipper* zipper, PointData& data)
{
  if (zipper==NULL) // range coder test
    return;

  double start_time, end_time;
  unsigned char c;
  unsigned int i,j;
  unsigned int num_bytes;

  // the two branches of this IF are the same, except for the use of a random number;
  // we keep the random case separate, so that we can get fastest timing tests w/o random data
  if (settings->use_random)
  {
    srand(settings->seed);
    start_time = taketime();
    c = rand() % 256;
    for (i = 0; i < settings->num_points; i++)
    {
      for (j = 0; j < data.point_size; j++)
      {
        data.point_data[j] = c;
        c = rand() % 256;
      }
      zipper->write(data.point);
    }
    num_bytes = zipper->close();
    end_time = taketime();
  }
  else
  {
    start_time = taketime();
    c = 0;
    for (i = 0; i < settings->num_points; i++)
    {
      for (j = 0; j < data.point_size; j++)
      {
        data.point_data[j] = c;
        c++;
      }
      zipper->write(data.point);
    }
    num_bytes = zipper->close();
    end_time = taketime();
  }

  log("laszipper wrote %u bytes in %g seconds\n", num_bytes, end_time-start_time);

  return;
}

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

static void read_points(LASunzipper* unzipper, PointData& data)
{
  if (unzipper==NULL) // range coder test
    return;

  unsigned char c;
  unsigned int i,j;
  unsigned int num_errors, num_bytes;
  double start_time, end_time;

  start_time = taketime();
  num_errors = 0;

  if (settings->use_random)
  {
    srand(settings->seed);
    c = rand() % 256;
    for (i = 0; i < settings->num_points; i++)
    {
      unzipper->read(data.point);
      for (j = 0; j < data.point_size; j++)
      {
        if (data.point_data[j] != c)
        {
          log("%d %d %d != %d\n", i, j, data.point_data[j], c);
          num_errors++;
          if (num_errors > 20) break;
        }
        c = rand() % 256;
      }
      if (num_errors > 20) break;
    }
    num_bytes = unzipper->close();
    end_time = taketime();
  }
  else
  {
    c = 0;
    for (i = 0; i < settings->num_points; i++)
    {
      unzipper->read(data.point);
      for (j = 0; j < data.point_size; j++)
      {
        if (data.point_data[j] != c)
        {
          log("%d %d %d != %d\n", i, j, data.point_data[j], c);
          num_errors++;
          if (num_errors > 20) break;
        }
        c++;
      }
      if (num_errors > 20) break;
    }
    num_bytes = unzipper->close();
    end_time = taketime();
  }

  if (num_errors)
  {
    log("ERROR: with lasunzipper %d\n", num_errors);
    getc(stdin);
  }
  else
  {
    log("SUCCESS: lasunzipper read %u bytes in %g seconds\n", num_bytes, end_time-start_time);
  }

  return;
}

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

static void run_test(const char* filename, PointData& data, unsigned short compressor, unsigned short requested_version=0, unsigned short chunk_size=0)
{
  LASzip laszip;
  laszip.setup(data.num_items, data.items, compressor);
  if (requested_version) laszip.request_version(requested_version);
  if (chunk_size) laszip.set_chunk_size(chunk_size);

  LASzipper* laszipper = make_zipper(&laszip);
  // only now (that the version numbers were set) can we pack laszip
  unsigned char* bytes;
  int num;
  laszip.pack(bytes, num);
  OStream* ost = new OStream(settings->use_iostream, filename);
  open_zipper(laszipper, ost);
  write_points(laszipper, data);
  delete laszipper;
  delete ost;

  // copy VLR to laszip
  LASzip laszip_dec;
  laszip_dec.unpack(bytes, num);
  LASunzipper* lasunzipper = make_unzipper(&laszip_dec);
  IStream* ist = new IStream(settings->use_iostream, filename);
  open_unzipper(lasunzipper, ist);
  read_points(lasunzipper, data);
  delete lasunzipper;
  delete ist;

  return;
}

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

int main(int argc, char *argv[])
{
  unsigned int num_points = 100000;
  bool use_iostream = false;
  bool run_forever = false;
  bool use_random = false;
  unsigned int user_seed = (unsigned int)time(NULL);

  for (int i=1; i<argc; i++)
  {
    const char* p = argv[i];
    if (strcmp(p,"-n")==0)
    {
      ++i;
      num_points = atoi(argv[i]);
    }
    else if (strcmp(p,"-s")==0)
    {
      use_iostream = true;
    }
    else if (strcmp(p,"-f")==0)
    {
      run_forever = true;
    }
    else if (strcmp(p,"-r")==0)
    {
      use_random = true;
    }
    else if (strcmp(p,"-x")==0)
    {
      ++i;
      user_seed = atoi(argv[i]);
    }
    else
    {
      fprintf(stderr, "Usage   ziptest [-n NUMBER] [-s] [-f] [-r]\n");
      fprintf(stderr, "   -n    number of points to process (default   100000)\n");
      fprintf(stderr, "   -s    use C++ stream I/O (default   use FILE* I/O)\n");
      fprintf(stderr, "   -f    run forever (default   run just one pass)\n");
      fprintf(stderr, "   -r    use random input data (default   use fixed data)\n");
      fprintf(stderr, "   -x    set random seed, instead of current time (default: use time)\n");
      exit(1);
    }
  }

  settings = new Settings(num_points, use_random, use_iostream);

  log("Settings:\n");
  log("  num_points=%u, use_iostream=%s, run_forever=%s, use_random=%s, user_seed=%d\n",
    num_points, use_iostream?"true":"false", run_forever?"true":"false", use_random?"true":"false", user_seed);

  settings->seed = user_seed;

  unsigned int run = 1;
  do
  {
  PointData data;

  // use a seed based on the current time
  if (run_forever && settings->use_random)
  {
    settings->seed = (unsigned int)time(NULL);
    log("Seed: %u\n", settings->seed);
  }

  run_test("test1.lax", data, LASZIP_COMPRESSOR_NONE);
  run_test("test2.lax", data, LASZIP_COMPRESSOR_DEFAULT);
  run_test("test3.lax", data, LASZIP_COMPRESSOR_DEFAULT, 2);
  run_test("test4.lax", data, LASZIP_COMPRESSOR_CHUNKED);
  run_test("test5.lax", data, LASZIP_COMPRESSOR_CHUNKED, 2);
  log("Finished %u runs\n\n", run);
  ++run;
  } while (run_forever);

  return 0;
}
<|endoftext|>


<commit_before>#ifndef _UNTOOLS_UCBLOCKBYTES_HXX
#define _UNTOOLS_UCBLOCKBYTES_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef INCLUDED_UNOTOOLSDLLAPI_H
#include "unotools/unotoolsdllapi.h"
#endif

#include <vos/thread.hxx>
#include <vos/conditn.hxx>
#include <vos/mutex.hxx>
#include <tools/stream.hxx>
#include <tools/link.hxx>
#include <tools/errcode.hxx>
#include <tools/datetime.hxx>

namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace task
            {
                class XInteractionHandler;
            }
            namespace io
            {
                class XStream;
                class XInputStream;
                class XOutputStream;
                class XSeekable;
            }
            namespace ucb
            {
                class XContent;
            }
            namespace beans
            {
                struct PropertyValue;
            }
        }
    }
};

namespace utl
{
SV_DECL_REF( UcbLockBytes )

class UcbLockBytesHandler : public SvRefBase
{
    sal_Bool        m_bActive;
public:
    enum LoadHandlerItem
    {
        DATA_AVAILABLE,
        DONE,
        CANCEL
    };

                    UcbLockBytesHandler()
                        : m_bActive( sal_True )
                    {}

    virtual void    Handle( LoadHandlerItem nWhich, UcbLockBytesRef xLockBytes ) = 0;
    void            Activate( BOOL bActivate = sal_True ) { m_bActive = bActivate; }
    sal_Bool        IsActive() const { return m_bActive; }
};

SV_DECL_IMPL_REF( UcbLockBytesHandler )

#define NS_UNO ::com::sun::star::uno
#define NS_IO ::com::sun::star::io
#define NS_UCB ::com::sun::star::ucb
#define NS_BEANS ::com::sun::star::beans
#define NS_TASK ::com::sun::star::task

class UNOTOOLS_DLLPUBLIC UcbLockBytes : public virtual SvLockBytes
{
    vos::OCondition         m_aInitialized;
    vos::OCondition         m_aTerminated;
    vos::OMutex             m_aMutex;

    String                  m_aContentType;
    String                  m_aRealURL;
    DateTime                m_aExpireDate;

    NS_UNO::Reference < NS_IO::XInputStream >  m_xInputStream;
    NS_UNO::Reference < NS_IO::XOutputStream > m_xOutputStream;
    NS_UNO::Reference < NS_IO::XSeekable >     m_xSeekable;
    void*                   m_pCommandThread; // is alive only for compatibility reasons
    UcbLockBytesHandlerRef  m_xHandler;

    sal_uInt32              m_nRead;
    sal_uInt32              m_nSize;
    ErrCode                 m_nError;

    sal_Bool                m_bTerminated : 1;
    sal_Bool                m_bDontClose : 1;
    sal_Bool                m_bStreamValid : 1;

    DECL_LINK(              DataAvailHdl, void * );

                            UcbLockBytes( UcbLockBytesHandler* pHandler=NULL );
protected:
    virtual                 ~UcbLockBytes (void);

public:
                            // properties: Referer, PostMimeType
    static UcbLockBytesRef  CreateLockBytes( const NS_UNO::Reference < NS_UCB::XContent >& xContent,
                                            const ::rtl::OUString& rReferer,
                                            const ::rtl::OUString& rMediaType,
                                            const NS_UNO::Reference < NS_IO::XInputStream >& xPostData,
                                            const NS_UNO::Reference < NS_TASK::XInteractionHandler >& xInter,
                                            UcbLockBytesHandler* pHandler=0 );

    static UcbLockBytesRef  CreateLockBytes( const NS_UNO::Reference < NS_UCB::XContent >& xContent,
                                            const NS_UNO::Sequence < NS_BEANS::PropertyValue >& rProps,
                                            StreamMode eMode,
                                            const NS_UNO::Reference < NS_TASK::XInteractionHandler >& xInter,
                                            UcbLockBytesHandler* pHandler=0 );

    static UcbLockBytesRef  CreateInputLockBytes( const NS_UNO::Reference < NS_IO::XInputStream >& xContent );
    static UcbLockBytesRef  CreateLockBytes( const NS_UNO::Reference < NS_IO::XStream >& xContent );

    // SvLockBytes
    virtual void            SetSynchronMode (BOOL bSynchron);
    virtual ErrCode         ReadAt ( ULONG nPos, void *pBuffer, ULONG nCount, ULONG *pRead) const;
    virtual ErrCode         WriteAt ( ULONG, const void*, ULONG, ULONG *pWritten);
    virtual ErrCode         Flush (void) const;
    virtual ErrCode         SetSize (ULONG);
    virtual ErrCode         Stat ( SvLockBytesStat *pStat, SvLockBytesStatFlag) const;

    void                    SetError( ErrCode nError )
                            { m_nError = nError; }

    ErrCode                 GetError() const
                            { return m_nError; }

    void                    Cancel(); // is alive only for compatibility reasons

    // the following properties are available when and after the first DataAvailable callback has been executed
    String                  GetContentType() const;
    String                  GetRealURL() const;
    DateTime                GetExpireDate() const;

    // calling this method delegates the responsibility to call closeinput to the caller!
    NS_UNO::Reference < NS_IO::XInputStream > getInputStream();
    NS_UNO::Reference < NS_IO::XStream > getStream();

#if _SOLAR__PRIVATE
    sal_Bool                setInputStream_Impl( const NS_UNO::Reference < NS_IO::XInputStream > &rxInputStream,
                                                 sal_Bool bSetXSeekable = sal_True );
    sal_Bool                setStream_Impl( const NS_UNO::Reference < NS_IO::XStream > &rxStream );
    void                    terminate_Impl (void);

    NS_UNO::Reference < NS_IO::XInputStream > getInputStream_Impl() const
                            {
                                vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
                                return m_xInputStream;
                            }

    NS_UNO::Reference < NS_IO::XOutputStream > getOutputStream_Impl() const
                            {
                                vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
                                return m_xOutputStream;
                            }

    NS_UNO::Reference < NS_IO::XSeekable > getSeekable_Impl() const
                            {
                                vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
                                return m_xSeekable;
                            }

    sal_Bool                hasInputStream_Impl() const
                            {
                                vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
                                return m_xInputStream.is();
                            }

    void                    setDontClose_Impl()
                            { m_bDontClose = sal_True; }

    void                    SetContentType_Impl( const String& rType ) { m_aContentType = rType; }
    void                    SetRealURL_Impl( const String& rURL )  { m_aRealURL = rURL; }
    void                    SetExpireDate_Impl( const DateTime& rDateTime )  { m_aExpireDate = rDateTime; }
    void                    SetStreamValid_Impl();
#endif
};

SV_IMPL_REF( UcbLockBytes );

};

#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.24.46); FILE MERGED 2005/10/27 10:51:10 pl 1.24.46.1: #i55991# removed warnings for solaris platform<commit_after>#ifndef _UNTOOLS_UCBLOCKBYTES_HXX
#define _UNTOOLS_UCBLOCKBYTES_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef INCLUDED_UNOTOOLSDLLAPI_H
#include "unotools/unotoolsdllapi.h"
#endif

#include <vos/thread.hxx>
#include <vos/conditn.hxx>
#include <vos/mutex.hxx>
#include <tools/stream.hxx>
#include <tools/link.hxx>
#include <tools/errcode.hxx>
#include <tools/datetime.hxx>

namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace task
            {
                class XInteractionHandler;
            }
            namespace io
            {
                class XStream;
                class XInputStream;
                class XOutputStream;
                class XSeekable;
            }
            namespace ucb
            {
                class XContent;
            }
            namespace beans
            {
                struct PropertyValue;
            }
        }
    }
}

namespace utl
{
SV_DECL_REF( UcbLockBytes )

class UcbLockBytesHandler : public SvRefBase
{
    sal_Bool        m_bActive;
public:
    enum LoadHandlerItem
    {
        DATA_AVAILABLE,
        DONE,
        CANCEL
    };

                    UcbLockBytesHandler()
                        : m_bActive( sal_True )
                    {}

    virtual void    Handle( LoadHandlerItem nWhich, UcbLockBytesRef xLockBytes ) = 0;
    void            Activate( BOOL bActivate = sal_True ) { m_bActive = bActivate; }
    sal_Bool        IsActive() const { return m_bActive; }
};

SV_DECL_IMPL_REF( UcbLockBytesHandler )

#define NS_UNO ::com::sun::star::uno
#define NS_IO ::com::sun::star::io
#define NS_UCB ::com::sun::star::ucb
#define NS_BEANS ::com::sun::star::beans
#define NS_TASK ::com::sun::star::task

class UNOTOOLS_DLLPUBLIC UcbLockBytes : public virtual SvLockBytes
{
    vos::OCondition         m_aInitialized;
    vos::OCondition         m_aTerminated;
    vos::OMutex             m_aMutex;

    String                  m_aContentType;
    String                  m_aRealURL;
    DateTime                m_aExpireDate;

    NS_UNO::Reference < NS_IO::XInputStream >  m_xInputStream;
    NS_UNO::Reference < NS_IO::XOutputStream > m_xOutputStream;
    NS_UNO::Reference < NS_IO::XSeekable >     m_xSeekable;
    void*                   m_pCommandThread; // is alive only for compatibility reasons
    UcbLockBytesHandlerRef  m_xHandler;

    sal_uInt32              m_nRead;
    sal_uInt32              m_nSize;
    ErrCode                 m_nError;

    sal_Bool                m_bTerminated : 1;
    sal_Bool                m_bDontClose : 1;
    sal_Bool                m_bStreamValid : 1;

    DECL_LINK(              DataAvailHdl, void * );

                            UcbLockBytes( UcbLockBytesHandler* pHandler=NULL );
protected:
    virtual                 ~UcbLockBytes (void);

public:
                            // properties: Referer, PostMimeType
    static UcbLockBytesRef  CreateLockBytes( const NS_UNO::Reference < NS_UCB::XContent >& xContent,
                                            const ::rtl::OUString& rReferer,
                                            const ::rtl::OUString& rMediaType,
                                            const NS_UNO::Reference < NS_IO::XInputStream >& xPostData,
                                            const NS_UNO::Reference < NS_TASK::XInteractionHandler >& xInter,
                                            UcbLockBytesHandler* pHandler=0 );

    static UcbLockBytesRef  CreateLockBytes( const NS_UNO::Reference < NS_UCB::XContent >& xContent,
                                            const NS_UNO::Sequence < NS_BEANS::PropertyValue >& rProps,
                                            StreamMode eMode,
                                            const NS_UNO::Reference < NS_TASK::XInteractionHandler >& xInter,
                                            UcbLockBytesHandler* pHandler=0 );

    static UcbLockBytesRef  CreateInputLockBytes( const NS_UNO::Reference < NS_IO::XInputStream >& xContent );
    static UcbLockBytesRef  CreateLockBytes( const NS_UNO::Reference < NS_IO::XStream >& xContent );

    // SvLockBytes
    virtual void            SetSynchronMode (BOOL bSynchron);
    virtual ErrCode         ReadAt ( ULONG nPos, void *pBuffer, ULONG nCount, ULONG *pRead) const;
    virtual ErrCode         WriteAt ( ULONG, const void*, ULONG, ULONG *pWritten);
    virtual ErrCode         Flush (void) const;
    virtual ErrCode         SetSize (ULONG);
    virtual ErrCode         Stat ( SvLockBytesStat *pStat, SvLockBytesStatFlag) const;

    void                    SetError( ErrCode nError )
                            { m_nError = nError; }

    ErrCode                 GetError() const
                            { return m_nError; }

    void                    Cancel(); // is alive only for compatibility reasons

    // the following properties are available when and after the first DataAvailable callback has been executed
    String                  GetContentType() const;
    String                  GetRealURL() const;
    DateTime                GetExpireDate() const;

    // calling this method delegates the responsibility to call closeinput to the caller!
    NS_UNO::Reference < NS_IO::XInputStream > getInputStream();
    NS_UNO::Reference < NS_IO::XStream > getStream();

#if _SOLAR__PRIVATE
    sal_Bool                setInputStream_Impl( const NS_UNO::Reference < NS_IO::XInputStream > &rxInputStream,
                                                 sal_Bool bSetXSeekable = sal_True );
    sal_Bool                setStream_Impl( const NS_UNO::Reference < NS_IO::XStream > &rxStream );
    void                    terminate_Impl (void);

    NS_UNO::Reference < NS_IO::XInputStream > getInputStream_Impl() const
                            {
                                vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
                                return m_xInputStream;
                            }

    NS_UNO::Reference < NS_IO::XOutputStream > getOutputStream_Impl() const
                            {
                                vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
                                return m_xOutputStream;
                            }

    NS_UNO::Reference < NS_IO::XSeekable > getSeekable_Impl() const
                            {
                                vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
                                return m_xSeekable;
                            }

    sal_Bool                hasInputStream_Impl() const
                            {
                                vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
                                return m_xInputStream.is();
                            }

    void                    setDontClose_Impl()
                            { m_bDontClose = sal_True; }

    void                    SetContentType_Impl( const String& rType ) { m_aContentType = rType; }
    void                    SetRealURL_Impl( const String& rURL )  { m_aRealURL = rURL; }
    void                    SetExpireDate_Impl( const DateTime& rDateTime )  { m_aExpireDate = rDateTime; }
    void                    SetStreamValid_Impl();
#endif
};

SV_IMPL_REF( UcbLockBytes );

}

#endif
<|endoftext|>


<commit_before>// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "verilog/formatting/comment_controls.h"

#include <iostream>
#include <vector>

#include "absl/strings/match.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "common/strings/comment_utils.h"
#include "common/util/logging.h"
#include "verilog/parser/verilog_parser.h"
#include "verilog/parser/verilog_token_enum.h"

namespace verilog {
namespace formatter {

void SetRange(std::vector<bool>* disable_set, int start, int end) {
  CHECK_GE(start, 0);
  CHECK_LE(start, end);
  if (end > disable_set->size()) {
    disable_set->resize(end, false);
  }
  for (int i = start; i < end; ++i) {
    (*disable_set)[i] = true;
  }
}

std::vector<bool> DisableFormattingRanges(
    absl::string_view text, const verible::TokenSequence& tokens) {
  static constexpr absl::string_view kTrigger = "verilog_format:";
  static const auto kDelimiters = strings::delimiter::AnyOf(" \t");
  static constexpr int kNullOffset = -1;
  const verible::TokenInfo::Context context(
      text,
      [](std::ostream& stream, int e) { stream << verilog_symbol_name(e); });

  // By default, no text ranges are formatter-disabled.
  int begin_disable_offset = kNullOffset;
  std::vector<bool> disable_set(text.length(), false);
  for (const auto& token : tokens) {
    VLOG(2) << verible::TokenWithContext{token, context};
    switch (token.token_enum) {
      case TK_COMMENT_BLOCK:
      case TK_EOL_COMMENT: {
        // Focus on the space-delimited tokens in the comment text.
        auto commands = verible::StripCommentAndSpacePadding(token.text);
        if (absl::ConsumePrefix(&commands, kTrigger)) {
          const std::vector<absl::string_view> comment_tokens(
              absl::StrSplit(commands, kDelimiters, absl::SkipEmpty()));
          if (!comment_tokens.empty()) {
            // "off" marks the start of a disabling range.
            // "on" marks the end of disabling range.
            if (comment_tokens.front() == "off") {
              if (begin_disable_offset == kNullOffset) {
                begin_disable_offset = token.left(text);
              }  // else ignore
            } else if (comment_tokens.front() == "on") {
              if (begin_disable_offset != kNullOffset) {
                const int end_disable_offset = token.right(text);
                SetRange(&disable_set, begin_disable_offset,
                         end_disable_offset);
                begin_disable_offset = kNullOffset;
              }  // else ignore
            }
          }
        }
        break;
      }
      default:
        break;
    }
  }
  // If the disabling interval remains open, close it (to end-of-buffer).
  if (begin_disable_offset != kNullOffset) {
    SetRange(&disable_set, begin_disable_offset, text.length());
  }
  return disable_set;
}

bool ContainsRange(const std::vector<bool>& intervals, int start, int end) {
  CHECK_GE(start, 0);
  CHECK_LE(start, end);
  if (start == end) return true;  // degenerate case
  if (end > intervals.size()) return false;
  for (int i = start; i < end; ++i) {
    if (!intervals[i]) return false;
  }
  return true;
}

}  // namespace formatter
}  // namespace verilog
<commit_msg>Fix compilation.<commit_after>// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "verilog/formatting/comment_controls.h"

#include <iostream>
#include <vector>

#include "absl/strings/match.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "common/strings/comment_utils.h"
#include "common/util/logging.h"
#include "verilog/parser/verilog_parser.h"
#include "verilog/parser/verilog_token_enum.h"

namespace verilog {
namespace formatter {

void SetRange(std::vector<bool>* disable_set, int start, int end) {
  CHECK_GE(start, 0);
  CHECK_LE(start, end);
  if (end > static_cast<int>(disable_set->size())) {
    disable_set->resize(end, false);
  }
  for (int i = start; i < end; ++i) {
    (*disable_set)[i] = true;
  }
}

std::vector<bool> DisableFormattingRanges(
    absl::string_view text, const verible::TokenSequence& tokens) {
  static constexpr absl::string_view kTrigger = "verilog_format:";
  static const auto kDelimiters = absl::ByAnyChar(" \t");
  static constexpr int kNullOffset = -1;
  const verible::TokenInfo::Context context(
      text,
      [](std::ostream& stream, int e) { stream << verilog_symbol_name(e); });

  // By default, no text ranges are formatter-disabled.
  int begin_disable_offset = kNullOffset;
  std::vector<bool> disable_set(text.length(), false);
  for (const auto& token : tokens) {
    VLOG(2) << verible::TokenWithContext{token, context};
    switch (token.token_enum) {
      case TK_COMMENT_BLOCK:
      case TK_EOL_COMMENT: {
        // Focus on the space-delimited tokens in the comment text.
        auto commands = verible::StripCommentAndSpacePadding(token.text);
        if (absl::ConsumePrefix(&commands, kTrigger)) {
          const std::vector<absl::string_view> comment_tokens(
              absl::StrSplit(commands, kDelimiters, absl::SkipEmpty()));
          if (!comment_tokens.empty()) {
            // "off" marks the start of a disabling range.
            // "on" marks the end of disabling range.
            if (comment_tokens.front() == "off") {
              if (begin_disable_offset == kNullOffset) {
                begin_disable_offset = token.left(text);
              }  // else ignore
            } else if (comment_tokens.front() == "on") {
              if (begin_disable_offset != kNullOffset) {
                const int end_disable_offset = token.right(text);
                SetRange(&disable_set, begin_disable_offset,
                         end_disable_offset);
                begin_disable_offset = kNullOffset;
              }  // else ignore
            }
          }
        }
        break;
      }
      default:
        break;
    }
  }
  // If the disabling interval remains open, close it (to end-of-buffer).
  if (begin_disable_offset != kNullOffset) {
    SetRange(&disable_set, begin_disable_offset, text.length());
  }
  return disable_set;
}

bool ContainsRange(const std::vector<bool>& intervals, int start, int end) {
  CHECK_GE(start, 0);
  CHECK_LE(start, end);
  if (start == end) return true;  // degenerate case
  if (end > static_cast<int>(intervals.size())) return false;
  for (int i = start; i < end; ++i) {
    if (!intervals[i]) return false;
  }
  return true;
}

}  // namespace formatter
}  // namespace verilog
<|endoftext|>