<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

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

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

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

#include <Core/Algorithms/DataIO/EigenMatrixFromScirunAsciiFormatConverter.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <boost/timer.hpp>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Algorithms/Base/AlgorithmBase.h>

using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Utility;
using namespace SCIRun::Core::Algorithms::DataIO::internal;

namespace
{
  template <typename T>
  std::vector<T> parseLineOfNumbers(const std::string& line)
  {
    std::istringstream stream(line);
    std::vector<T> numbers((std::istream_iterator<T>(stream)), (std::istream_iterator<T>()));

    return numbers;
  }

  bool fileContainsString(const std::string& filename, const std::string& str)
  {
    std::ifstream input(filename.c_str());
    std::string line;

    while (std::getline(input, line))
    {
      auto index = line.find(str);
      if (index != std::string::npos && line.find('\0') > index)
        return true;
    }

    return false;
  }
}

EigenMatrixFromScirunAsciiFormatConverter::EigenMatrixFromScirunAsciiFormatConverter(const ProgressReporter* reporter) : reporter_(reporter)
{
}

MatrixHandle EigenMatrixFromScirunAsciiFormatConverter::make(const std::string& matFile)
{
  if (reporter_)
    reporter_->update_progress(0.01);
  if (fileContainsString(matFile, "DenseMatrix"))
    return makeDense(matFile);
  if (fileContainsString(matFile, "SparseRowMatrix"))
    return makeSparse(matFile);
  if (fileContainsString(matFile, "ColumnMatrix"))
    return makeColumn(matFile);

  //TODO: no access to error(), need alternative for logging this exception
  BOOST_THROW_EXCEPTION(AlgorithmInputException() << ErrorMessage("Unknown SCIRun matrix format"));
}

SparseRowMatrixHandle EigenMatrixFromScirunAsciiFormatConverter::makeSparse(const std::string& matFile)
{
  SparseData data = convertRaw(parseSparseMatrixString(getMatrixContentsLine(readFile(matFile)).get()).get());
  if (reporter_)
    reporter_->update_progress(0.7);
  SparseRowMatrixHandle mat(new SparseRowMatrix(data.get<0>(), data.get<1>()));

  typedef Eigen::Triplet<double> T;
  std::vector<T> tripletList;
  {
    const Indices& rowAcc = data.get<3>();
    const Indices& cols = data.get<4>();
    const Data& values = data.get<5>();
    size_t estimation_of_entries = values.size();
    tripletList.reserve(estimation_of_entries);

    int count = 0;
    int nextRow;
    for (int r = 0; r < mat->rows(); ++r)
    {
      //if (reporter_ && (r % 1000 == 1))
      //{
      //  reporter_->update_progress(0.7 + (0.3*((double)r / mat->rows())));
      //}

      nextRow = rowAcc[r+1];
      while (count < nextRow)
      {
        //(*dm)[r][columns_[count]]=data_[count];
        tripletList.push_back(T(r, cols[count], values[count]));
        count++;
      }
    }
  }

  mat->setFromTriplets(tripletList.begin(), tripletList.end());
  mat->makeCompressed();
  if (reporter_)
    reporter_->update_progress(1);
  return mat;
}

boost::optional<std::string> EigenMatrixFromScirunAsciiFormatConverter::getMatrixContentsLine(const std::string& matStr)
{
  if (reporter_)
    reporter_->update_progress(0.2);

  std::istringstream reader(matStr);
  std::string line;
  while(std::getline(reader, line))
  {
    if (line.length() > 2 && isdigit(line[0]))
      return line;
  }
  return boost::optional<std::string>();
}

std::string EigenMatrixFromScirunAsciiFormatConverter::readFile(const std::string& filename)
{
  std::ifstream matFile(filename.c_str());
  std::string matStr((std::istreambuf_iterator<char>(matFile)),
    std::istreambuf_iterator<char>());
  if (reporter_)
    reporter_->update_progress(0.1);
  return matStr;
}

DenseMatrixHandle EigenMatrixFromScirunAsciiFormatConverter::makeDense(const std::string& matFile)
{
  DenseData data = convertRaw(parseDenseMatrixString(getMatrixContentsLine(readFile(matFile)).get()).get());
  DenseMatrixHandle mat(new DenseMatrix(data.get<0>(), data.get<1>()));

  auto values = data.get<2>().begin();
  for (int i = 0; i < mat->rows(); ++i)
    for (int j = 0; j < mat->cols(); ++j)
      (*mat)(i,j) = *values++;

  return mat;
}

DenseColumnMatrixHandle EigenMatrixFromScirunAsciiFormatConverter::makeColumn(const std::string& matFile)
{
  DenseData data = convertRaw(parseColumnMatrixString(getMatrixContentsLine(readFile(matFile)).get()).get());
  DenseColumnMatrixHandle mat(new DenseColumnMatrix(data.get<0>()));

  auto values = data.get<2>().begin();
  for (int i = 0; i < mat->rows(); ++i)
      (*mat)(i) = *values++;

  return mat;
}

boost::optional<EigenMatrixFromScirunAsciiFormatConverter::RawDenseData> EigenMatrixFromScirunAsciiFormatConverter::parseDenseMatrixString(const std::string& matString)
{
  boost::regex r("(\\d+) (\\d+) \\{0 (.*)\\}\\}");
  boost::smatch what;
  regex_match(matString, what, r);
  if (what.size() == 4)
  {
    return boost::make_tuple(what[1].str(), what[2].str(), what[3].str());
  }
  return boost::optional<RawDenseData>();
}

boost::optional<EigenMatrixFromScirunAsciiFormatConverter::RawDenseData> EigenMatrixFromScirunAsciiFormatConverter::parseColumnMatrixString(const std::string& matString)
{
  boost::regex r("(\\d+) (.*)\\}");
  boost::smatch what;
  regex_match(matString, what, r);
  if (what.size() == 3)
  {
    return boost::make_tuple(what[1].str(), std::string("1"), what[2].str());
  }
  return boost::optional<RawDenseData>();
}

EigenMatrixFromScirunAsciiFormatConverter::DenseData EigenMatrixFromScirunAsciiFormatConverter::convertRaw(const RawDenseData& data)
{
  return boost::make_tuple(
    boost::lexical_cast<int>(data.get<0>()),
    boost::lexical_cast<int>(data.get<1>()),
    parseLineOfNumbers<double>(data.get<2>()));
}

boost::optional<EigenMatrixFromScirunAsciiFormatConverter::RawSparseData> EigenMatrixFromScirunAsciiFormatConverter::parseSparseMatrixString(const std::string& matString)
{
  boost::regex r("(\\d+) (\\d+) (\\d+) \\{8 (.*)\\}\\{8 (.*)\\}\\{(.*)\\}\\}");
  boost::smatch what;
  regex_match(matString, what, r);
  if (what.size() == 7)
  {
    if (reporter_)
      reporter_->update_progress(0.4);
    return boost::make_tuple(what[1].str(), what[2].str(), what[3].str(), what[4].str(), what[5].str(), what[6].str());
  }
  return boost::optional<RawSparseData>();
}

EigenMatrixFromScirunAsciiFormatConverter::SparseData EigenMatrixFromScirunAsciiFormatConverter::convertRaw(const RawSparseData& data)
{
  if (reporter_)
    reporter_->update_progress(0.5);
  return boost::make_tuple(
    boost::lexical_cast<int>(data.get<0>()),
    boost::lexical_cast<int>(data.get<1>()),
    boost::lexical_cast<int>(data.get<2>()),
    parseLineOfNumbers<int>(data.get<3>()),
    parseLineOfNumbers<int>(data.get<4>()),
    parseLineOfNumbers<double>(data.get<5>()));
}
<commit_msg>Move utility function to Core/Utils library.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

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

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

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

#include <boost/timer.hpp>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>

#include <iostream>
#include <fstream>
#include <streambuf>

#include <Core/Algorithms/DataIO/EigenMatrixFromScirunAsciiFormatConverter.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Algorithms/Base/AlgorithmBase.h>
#include <Core/Utils/FileUtil.h>
#include <Core/Utils/StringUtil.h>

using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Utility;
using namespace SCIRun::Core::Algorithms::DataIO::internal;

EigenMatrixFromScirunAsciiFormatConverter::EigenMatrixFromScirunAsciiFormatConverter(const ProgressReporter* reporter) : reporter_(reporter)
{
}

MatrixHandle EigenMatrixFromScirunAsciiFormatConverter::make(const std::string& matFile)
{
  if (reporter_)
    reporter_->update_progress(0.01);
  if (fileContainsString(matFile, "DenseMatrix"))
    return makeDense(matFile);
  if (fileContainsString(matFile, "SparseRowMatrix"))
    return makeSparse(matFile);
  if (fileContainsString(matFile, "ColumnMatrix"))
    return makeColumn(matFile);

  //TODO: no access to error(), need alternative for logging this exception
  BOOST_THROW_EXCEPTION(AlgorithmInputException() << ErrorMessage("Unknown SCIRun matrix format"));
}

SparseRowMatrixHandle EigenMatrixFromScirunAsciiFormatConverter::makeSparse(const std::string& matFile)
{
  SparseData data = convertRaw(parseSparseMatrixString(getMatrixContentsLine(readFile(matFile)).get()).get());
  if (reporter_)
    reporter_->update_progress(0.7);
  SparseRowMatrixHandle mat(new SparseRowMatrix(data.get<0>(), data.get<1>()));

  typedef Eigen::Triplet<double> T;
  std::vector<T> tripletList;
  {
    const Indices& rowAcc = data.get<3>();
    const Indices& cols = data.get<4>();
    const Data& values = data.get<5>();
    size_t estimation_of_entries = values.size();
    tripletList.reserve(estimation_of_entries);

    int count = 0;
    int nextRow;
    for (int r = 0; r < mat->rows(); ++r)
    {
      //if (reporter_ && (r % 1000 == 1))
      //{
      //  reporter_->update_progress(0.7 + (0.3*((double)r / mat->rows())));
      //}

      nextRow = rowAcc[r+1];
      while (count < nextRow)
      {
        //(*dm)[r][columns_[count]]=data_[count];
        tripletList.push_back(T(r, cols[count], values[count]));
        count++;
      }
    }
  }

  mat->setFromTriplets(tripletList.begin(), tripletList.end());
  mat->makeCompressed();
  if (reporter_)
    reporter_->update_progress(1);
  return mat;
}

boost::optional<std::string> EigenMatrixFromScirunAsciiFormatConverter::getMatrixContentsLine(const std::string& matStr)
{
  if (reporter_)
    reporter_->update_progress(0.2);

  std::istringstream reader(matStr);
  std::string line;
  while(std::getline(reader, line))
  {
    if (line.length() > 2 && isdigit(line[0]))
      return line;
  }
  return boost::optional<std::string>();
}

std::string EigenMatrixFromScirunAsciiFormatConverter::readFile(const std::string& filename)
{
  std::ifstream matFile(filename.c_str());
  std::string matStr((std::istreambuf_iterator<char>(matFile)),
    std::istreambuf_iterator<char>());
  if (reporter_)
    reporter_->update_progress(0.1);
  return matStr;
}

DenseMatrixHandle EigenMatrixFromScirunAsciiFormatConverter::makeDense(const std::string& matFile)
{
  DenseData data = convertRaw(parseDenseMatrixString(getMatrixContentsLine(readFile(matFile)).get()).get());
  DenseMatrixHandle mat(new DenseMatrix(data.get<0>(), data.get<1>()));

  auto values = data.get<2>().begin();
  for (int i = 0; i < mat->rows(); ++i)
    for (int j = 0; j < mat->cols(); ++j)
      (*mat)(i,j) = *values++;

  return mat;
}

DenseColumnMatrixHandle EigenMatrixFromScirunAsciiFormatConverter::makeColumn(const std::string& matFile)
{
  DenseData data = convertRaw(parseColumnMatrixString(getMatrixContentsLine(readFile(matFile)).get()).get());
  DenseColumnMatrixHandle mat(new DenseColumnMatrix(data.get<0>()));

  auto values = data.get<2>().begin();
  for (int i = 0; i < mat->rows(); ++i)
      (*mat)(i) = *values++;

  return mat;
}

boost::optional<EigenMatrixFromScirunAsciiFormatConverter::RawDenseData> EigenMatrixFromScirunAsciiFormatConverter::parseDenseMatrixString(const std::string& matString)
{
  boost::regex r("(\\d+) (\\d+) \\{0 (.*)\\}\\}");
  boost::smatch what;
  regex_match(matString, what, r);
  if (what.size() == 4)
  {
    return boost::make_tuple(what[1].str(), what[2].str(), what[3].str());
  }
  return boost::optional<RawDenseData>();
}

boost::optional<EigenMatrixFromScirunAsciiFormatConverter::RawDenseData> EigenMatrixFromScirunAsciiFormatConverter::parseColumnMatrixString(const std::string& matString)
{
  boost::regex r("(\\d+) (.*)\\}");
  boost::smatch what;
  regex_match(matString, what, r);
  if (what.size() == 3)
  {
    return boost::make_tuple(what[1].str(), std::string("1"), what[2].str());
  }
  return boost::optional<RawDenseData>();
}

EigenMatrixFromScirunAsciiFormatConverter::DenseData EigenMatrixFromScirunAsciiFormatConverter::convertRaw(const RawDenseData& data)
{
  return boost::make_tuple(
    boost::lexical_cast<int>(data.get<0>()),
    boost::lexical_cast<int>(data.get<1>()),
    parseLineOfNumbers<double>(data.get<2>()));
}

boost::optional<EigenMatrixFromScirunAsciiFormatConverter::RawSparseData> EigenMatrixFromScirunAsciiFormatConverter::parseSparseMatrixString(const std::string& matString)
{
  boost::regex r("(\\d+) (\\d+) (\\d+) \\{8 (.*)\\}\\{8 (.*)\\}\\{(.*)\\}\\}");
  boost::smatch what;
  regex_match(matString, what, r);
  if (what.size() == 7)
  {
    if (reporter_)
      reporter_->update_progress(0.4);
    return boost::make_tuple(what[1].str(), what[2].str(), what[3].str(), what[4].str(), what[5].str(), what[6].str());
  }
  return boost::optional<RawSparseData>();
}

EigenMatrixFromScirunAsciiFormatConverter::SparseData EigenMatrixFromScirunAsciiFormatConverter::convertRaw(const RawSparseData& data)
{
  if (reporter_)
    reporter_->update_progress(0.5);
  return boost::make_tuple(
    boost::lexical_cast<int>(data.get<0>()),
    boost::lexical_cast<int>(data.get<1>()),
    boost::lexical_cast<int>(data.get<2>()),
    parseLineOfNumbers<int>(data.get<3>()),
    parseLineOfNumbers<int>(data.get<4>()),
    parseLineOfNumbers<double>(data.get<5>()));
}
<|endoftext|>


<commit_before><commit_msg>json: use std::unique_ptr to hold owned objects<commit_after><|endoftext|>


<commit_before>#include <QtGui/QApplication>

#include "robotsGeneratorPlugin.h"
#include "nxtOSEK/nxtOSEKRobotGenerator.h"

Q_EXPORT_PLUGIN2(robotsGeneratorPlugin, robots::generator::RobotsGeneratorPlugin)

using namespace qReal;
using namespace robots::generator;

RobotsGeneratorPlugin::RobotsGeneratorPlugin()
		: mGenerateCodeAction(NULL)
		, mFlashRobotAction(NULL)
		, mUploadProgramAction(NULL)
		, mNxtToolsPresent(false)
{
	mAppTranslator.load(":/robotsGenerator_" + QLocale::system().name());
	QApplication::installTranslator(&mAppTranslator);
	checkNxtTools();
}

RobotsGeneratorPlugin::~RobotsGeneratorPlugin()
{
	delete mFlashTool;
}

void RobotsGeneratorPlugin::init(PluginConfigurator const &configurator)
{
	mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
	mRepoControlApi = &configurator.repoControlInterface();

	mFlashTool = new NxtFlashTool(mMainWindowInterface->errorReporter());
}

QList<ActionInfo> RobotsGeneratorPlugin::actions()
{
	mGenerateCodeAction.setText(tr("Generate code"));
	ActionInfo generateCodeActionInfo(&mGenerateCodeAction, "generators", "tools");
	connect(&mGenerateCodeAction, SIGNAL(triggered()), this, SLOT(generateRobotSourceCode()));

	mFlashRobotAction.setText(tr("Flash robot"));
	ActionInfo flashRobotActionInfo(&mFlashRobotAction, "generators", "tools");
	connect(&mFlashRobotAction, SIGNAL(triggered()), this, SLOT(flashRobot()));

	mUploadProgramAction.setText(tr("Upload program"));
	ActionInfo uploadProgramActionInfo(&mUploadProgramAction, "generators", "tools");
	connect(&mUploadProgramAction, SIGNAL(triggered()), this, SLOT(uploadProgram()));

	checkNxtTools();

	/*
	/// Set tabs, unused at the opening, enabled
	QList<ActionInfo> unusedAtTheOpeningTab;
	unusedAtTheOpeningTab << generateCodeActionInfo;
	changeActiveTab(unusedAtTheOpeningTab, false);
	*/
	return QList<ActionInfo>() << generateCodeActionInfo << flashRobotActionInfo
			<< uploadProgramActionInfo;
}

void RobotsGeneratorPlugin::changeActiveTab(QList<ActionInfo> const &info, bool const &trigger)
{
	foreach (ActionInfo const &actionInfo, info) {
			actionInfo.action()->setEnabled(trigger);
	}
}

void RobotsGeneratorPlugin::generateRobotSourceCode()
{
	robots::generator::NxtOSEKRobotGenerator gen(mMainWindowInterface->activeDiagram(),
			 *mRepoControlApi,
			 *mMainWindowInterface->errorReporter());
	gen.generate();
	if (mMainWindowInterface->errorReporter()->wereErrors()) {
		return;
	}
	mMainWindowInterface->errorReporter()->clearErrors();
	QFile file("nxt-tools/example0/example0.c");
	QTextStream *inStream = NULL;
	if (!file.isOpen() && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
		inStream = new QTextStream(&file);
	}

	if (inStream) {
		mMainWindowInterface->showInTextEditor("example0", inStream->readAll());
	}
}

void RobotsGeneratorPlugin::flashRobot()
{
	if (!mNxtToolsPresent) {
		mMainWindowInterface->errorReporter()->addError(tr("flash.sh not found. Make sure it is present in QReal installation directory"));
	} else {
		mFlashTool->flashRobot();
	}
}

void RobotsGeneratorPlugin::uploadProgram()
{
	if (!mNxtToolsPresent) {
		mMainWindowInterface->errorReporter()->addError(tr("upload.sh not found. Make sure it is present in QReal installation directory"));
	} else {
		generateRobotSourceCode();
		mFlashTool->uploadProgram();
	}
}

void RobotsGeneratorPlugin::checkNxtTools()
{
	QDir dir(qApp->applicationDirPath());
	if (!QDir().exists(dir.absolutePath() + "/nxt-tools")) {
		mNxtToolsPresent = false;
	} else {
		dir.cd(dir.absolutePath() + "/nxt-tools");

		QDir gnuarm(dir.absolutePath() + "/gnuarm");
		QDir nexttool(dir.absolutePath() + "/nexttool");
		QDir nxtOSEK(dir.absolutePath() + "/nxtOSEK");

#ifdef Q_OS_WIN
		QFile flash(dir.absolutePath() + "/flash.bat");
		QFile upload1(dir.absolutePath() + "/upload.bat");
		QFile upload2(dir.absolutePath() + "/upload.sh");

		mNxtToolsPresent = gnuarm.exists() && nexttool.exists() && nxtOSEK.exists() && flash.exists() && upload1.exists() && upload2.exists();
#else
		QDir libnxt(dir.absolutePath() + "/libnxt");
		QFile flash(dir.absolutePath() + "/flash.sh");
		QFile upload(dir.absolutePath() + "/upload.sh");

		mNxtToolsPresent = gnuarm.exists() && libnxt.exists() && nexttool.exists() && nxtOSEK.exists() && flash.exists() && upload.exists();
#endif
	}

	mUploadProgramAction.setVisible(mNxtToolsPresent);
	mFlashRobotAction.setVisible(mNxtToolsPresent);
}
<commit_msg>fixed bug: open tab for generation code<commit_after>#include <QtGui/QApplication>

#include "robotsGeneratorPlugin.h"
#include "nxtOSEK/nxtOSEKRobotGenerator.h"

Q_EXPORT_PLUGIN2(robotsGeneratorPlugin, robots::generator::RobotsGeneratorPlugin)

using namespace qReal;
using namespace robots::generator;

RobotsGeneratorPlugin::RobotsGeneratorPlugin()
        : mGenerateCodeAction(NULL)
        , mFlashRobotAction(NULL)
        , mUploadProgramAction(NULL)
        , mNxtToolsPresent(false)
{
    mAppTranslator.load(":/robotsGenerator_" + QLocale::system().name());
    QApplication::installTranslator(&mAppTranslator);
    checkNxtTools();
}

RobotsGeneratorPlugin::~RobotsGeneratorPlugin()
{
    delete mFlashTool;
}

void RobotsGeneratorPlugin::init(PluginConfigurator const &configurator)
{
    mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
    mRepoControlApi = &configurator.repoControlInterface();

    mFlashTool = new NxtFlashTool(mMainWindowInterface->errorReporter());
}

QList<ActionInfo> RobotsGeneratorPlugin::actions()
{
    mGenerateCodeAction.setText(tr("Generate code"));
    ActionInfo generateCodeActionInfo(&mGenerateCodeAction, "generators", "tools");
    connect(&mGenerateCodeAction, SIGNAL(triggered()), this, SLOT(generateRobotSourceCode()));

    mFlashRobotAction.setText(tr("Flash robot"));
    ActionInfo flashRobotActionInfo(&mFlashRobotAction, "generators", "tools");
    connect(&mFlashRobotAction, SIGNAL(triggered()), this, SLOT(flashRobot()));

    mUploadProgramAction.setText(tr("Upload program"));
    ActionInfo uploadProgramActionInfo(&mUploadProgramAction, "generators", "tools");
    connect(&mUploadProgramAction, SIGNAL(triggered()), this, SLOT(uploadProgram()));

    checkNxtTools();

    /*
    /// Set tabs, unused at the opening, enabled
    QList<ActionInfo> unusedAtTheOpeningTab;
    unusedAtTheOpeningTab << generateCodeActionInfo;
    changeActiveTab(unusedAtTheOpeningTab, false);
    */
    return QList<ActionInfo>() << generateCodeActionInfo << flashRobotActionInfo
            << uploadProgramActionInfo;
}

void RobotsGeneratorPlugin::changeActiveTab(QList<ActionInfo> const &info, bool const &trigger)
{
    foreach (ActionInfo const &actionInfo, info) {
            actionInfo.action()->setEnabled(trigger);
    }
}

void RobotsGeneratorPlugin::generateRobotSourceCode()
{
    robots::generator::NxtOSEKRobotGenerator gen(mMainWindowInterface->activeDiagram(),
             *mRepoControlApi,
             *mMainWindowInterface->errorReporter());
    mMainWindowInterface->errorReporter()->clearErrors();
    gen.generate();
    if (mMainWindowInterface->errorReporter()->wereErrors()) {
        return;
    }

    QFile file("nxt-tools/example0/example0.c");
    QTextStream *inStream = NULL;
    if (!file.isOpen() && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        inStream = new QTextStream(&file);
    }

    if (inStream) {
        mMainWindowInterface->showInTextEditor("example0", inStream->readAll());
    }
}

void RobotsGeneratorPlugin::flashRobot()
{
    if (!mNxtToolsPresent) {
        mMainWindowInterface->errorReporter()->addError(tr("flash.sh not found. Make sure it is present in QReal installation directory"));
    } else {
        mFlashTool->flashRobot();
    }
}

void RobotsGeneratorPlugin::uploadProgram()
{
    if (!mNxtToolsPresent) {
        mMainWindowInterface->errorReporter()->addError(tr("upload.sh not found. Make sure it is present in QReal installation directory"));
    } else {
        generateRobotSourceCode();
        mFlashTool->uploadProgram();
    }
}

void RobotsGeneratorPlugin::checkNxtTools()
{
    QDir dir(qApp->applicationDirPath());
    if (!QDir().exists(dir.absolutePath() + "/nxt-tools")) {
        mNxtToolsPresent = false;
    } else {
        dir.cd(dir.absolutePath() + "/nxt-tools");

        QDir gnuarm(dir.absolutePath() + "/gnuarm");
        QDir nexttool(dir.absolutePath() + "/nexttool");
        QDir nxtOSEK(dir.absolutePath() + "/nxtOSEK");

#ifdef Q_OS_WIN
        QFile flash(dir.absolutePath() + "/flash.bat");
        QFile upload1(dir.absolutePath() + "/upload.bat");
        QFile upload2(dir.absolutePath() + "/upload.sh");

        mNxtToolsPresent = gnuarm.exists() && nexttool.exists() && nxtOSEK.exists() && flash.exists() && upload1.exists() && upload2.exists();
#else
        QDir libnxt(dir.absolutePath() + "/libnxt");
        QFile flash(dir.absolutePath() + "/flash.sh");
        QFile upload(dir.absolutePath() + "/upload.sh");

        mNxtToolsPresent = gnuarm.exists() && libnxt.exists() && nexttool.exists() && nxtOSEK.exists() && flash.exists() && upload.exists();
#endif
    }

    mUploadProgramAction.setVisible(mNxtToolsPresent);
    mFlashRobotAction.setVisible(mNxtToolsPresent);
}
<|endoftext|>


<commit_before>// Copyright (C) 2004, by
//
// Carlo Wood, Run on IRC <carlo@alinoe.com>
// RSA-1024 0x624ACAD5 1997-01-26                    Sign & Encrypt
// Fingerprint16 = 32 EC A7 B6 AC DB 65 A6  F6 F6 55 DD 1C DC FF 61
//
// This file may be distributed under the terms of the Q Public License
// version 1.0 as appearing in the file LICENSE.QPL included in the
// packaging of this file.
//
#include "sys.h"
#include <iostream>

#include "debug.h"
#include "Singleton.h"

#undef ERROR1		// Forgetting the friend_Instance in singleton class.
#undef ERROR2		// Using Global instead of Singleton for singleton.
#undef ERROR2a		// Trying to use Global instead of Singleton in order to pass a parameter.
#undef ERROR3		// Instantiating the same Global twice.
#undef ERROR4		// Instantiating the same Singleton twice.   TEST IS BROKEN!?
#undef ERROR5		// Forgetting to instantiate a global Global<> object.
#undef ERROR5a		// Using `instance()' from global constructor.
#undef ERROR5b		// Not instantiating it at all and using `instance()' from main().
#undef ERROR6		// Forgetting to instantiate a global Singleton<> object.
#undef ERROR6a		// But with instantiation through `instantiate()'.
#undef ERROR7		// Forgetting to make constructor of singleton private.
#undef ERROR8		// Forgetting an `instantiate()' inside a global constructor.

#if (defined(ERROR5a) || defined(ERROR5b)) && !defined(ERROR5)
#define ERROR5
#endif
#if defined(ERROR6a) && !defined(ERROR6)
#define ERROR6
#endif
#if defined(ERROR2a) && !defined(ERROR2)
#define ERROR2
#endif

class Foo : public Singleton<Foo> {
  friend_Instance;
private:
  int data;

  Foo(void) : data(1) { }
  ~Foo() { }
  Foo(Foo const& foo) : Singleton<Foo, Foo>(foo) { }

public:
  int get_data(void) const { return data; }
};

class Test {
public:
  Test(int) { }
  Test(void) : j(0) { }
  int j;
};

class GlobalConverterTest2 {
public:
  const char *operator()(int) {
    return "Test2";
  }
};

class Test2 {
  const char *s;
public:
  Test2(const char *s_) : s(s_) { }
  Test2(void) : s("default constructor") { }
  char const* str(void) const { return s; }
};

class Instance { };	// This doesn't confuse the `friend' in the below class.

class Bar : public Singleton<Bar> {
#ifndef ERROR1
  friend_Instance;
#else
  friend class Test;
#endif
private:
  int data;

#ifdef ERROR7
public:
#endif
  Bar(void) : data(2) {
#ifdef ERROR5a
    Global<Test, 2>::instance().j = 9;
#else
#ifndef ERROR5b
    Global<Test, 2>::instantiate().j = 9;		// Ok
#endif
#endif
#ifdef ERROR8
    data = Singleton<Foo>::instance().get_data();
#endif
  }
#ifdef ERROR2a
  Bar(int) { }
#endif
  ~Bar() { }
private:
  Bar(Bar const& bar) : Singleton<Bar>(bar) { }

public:
  int get_data(void) const { return data; }
};

static SingletonInstance<Foo> singletonFoo __attribute__ ((unused));
static Global<Test, 0> globalTest0;
static Global<Test, 1> globalTest1;
#ifndef ERROR5
static Global<Test, 2> globalTest2;
#endif
#ifdef ERROR2
#ifdef ERROR2a
static Global<Bar, -1, GlobalConverterInt> globalBarError;
#else
static Global<Bar, 0, GlobalConverterVoid> globalBarError;
#endif
#else
#ifndef ERROR6
static SingletonInstance<Bar> singletonBar __attribute__ ((unused));
#endif
#endif
#ifdef ERROR3
static Global<Test, 0> test;
#endif
#ifdef ERROR4
static SingletonInstance<Foo> test __attribute__ ((unused));
#endif

namespace {
  static Global<Test2, 0, GlobalConverterTest2> S_dummy_Test2;
}

int main(int UNUSED_ARG(argc), char *UNUSED_ARG(argv)[])
{
  using std::cout;
  using std::endl;

#ifdef ERROR7
  Bar bar;
#endif
#ifdef ERROR6a
  Singleton<Bar>::instantiate();
#endif
#ifdef DEBUGGLOBAL
  GlobalObjectManager::main_entered();
#endif

  // Don't show allocations that are allocated before main()
  //make_all_allocations_invisible_except(NULL);

#ifdef CWDEBUG
  // Select debug channels
  ForAllDebugChannels( while (!debugChannel.is_on()) debugChannel.on() );
  DEBUGCHANNELS::dc::malloc.off();
#endif

  // Write debug output to cout
  Debug( libcw_do.set_ostream(&cout) );

  // Turn debug object on
  Debug( libcw_do.on() );

  // Print channels
  // Debug( list_channels_on(libcw_do) );

  cout << Singleton<Foo>::instance().get_data() << endl;
  cout << Singleton<Bar>::instance().get_data() << endl;
  cout << (void *)&Global<Test, 0>::instance() << endl;
  cout << (void *)&Global<Test, 2>::instance() << endl;
  cout << Global<Test2, 0>::instance().str() << endl;

  Debug( list_allocations_on(libcw_do) );

  return 0;
}
<commit_msg>Removed trailing whitespace.<commit_after>// Copyright (C) 2004, by
//
// Carlo Wood, Run on IRC <carlo@alinoe.com>
// RSA-1024 0x624ACAD5 1997-01-26                    Sign & Encrypt
// Fingerprint16 = 32 EC A7 B6 AC DB 65 A6  F6 F6 55 DD 1C DC FF 61
//
// This file may be distributed under the terms of the Q Public License
// version 1.0 as appearing in the file LICENSE.QPL included in the
// packaging of this file.
//
#include "sys.h"
#include <iostream>

#include "debug.h"
#include "Singleton.h"

#undef ERROR1		// Forgetting the friend_Instance in singleton class.
#undef ERROR2		// Using Global instead of Singleton for singleton.
#undef ERROR2a		// Trying to use Global instead of Singleton in order to pass a parameter.
#undef ERROR3		// Instantiating the same Global twice.
#undef ERROR4		// Instantiating the same Singleton twice.   TEST IS BROKEN!?
#undef ERROR5		// Forgetting to instantiate a global Global<> object.
#undef ERROR5a		// Using `instance()' from global constructor.
#undef ERROR5b		// Not instantiating it at all and using `instance()' from main().
#undef ERROR6		// Forgetting to instantiate a global Singleton<> object.
#undef ERROR6a		// But with instantiation through `instantiate()'.
#undef ERROR7		// Forgetting to make constructor of singleton private.
#undef ERROR8		// Forgetting an `instantiate()' inside a global constructor.

#if (defined(ERROR5a) || defined(ERROR5b)) && !defined(ERROR5)
#define ERROR5
#endif
#if defined(ERROR6a) && !defined(ERROR6)
#define ERROR6
#endif
#if defined(ERROR2a) && !defined(ERROR2)
#define ERROR2
#endif

class Foo : public Singleton<Foo> {
  friend_Instance;
private:
  int data;

  Foo(void) : data(1) { }
  ~Foo() { }
  Foo(Foo const& foo) : Singleton<Foo, Foo>(foo) { }

public:
  int get_data(void) const { return data; }
};

class Test {
public:
  Test(int) { }
  Test(void) : j(0) { }
  int j;
};

class GlobalConverterTest2 {
public:
  const char *operator()(int) {
    return "Test2";
  }
};

class Test2 {
  const char *s;
public:
  Test2(const char *s_) : s(s_) { }
  Test2(void) : s("default constructor") { }
  char const* str(void) const { return s; }
};

class Instance { };	// This doesn't confuse the `friend' in the below class.

class Bar : public Singleton<Bar> {
#ifndef ERROR1
  friend_Instance;
#else
  friend class Test;
#endif
private:
  int data;

#ifdef ERROR7
public:
#endif
  Bar(void) : data(2) {
#ifdef ERROR5a
    Global<Test, 2>::instance().j = 9;
#else
#ifndef ERROR5b
    Global<Test, 2>::instantiate().j = 9;		// Ok
#endif
#endif
#ifdef ERROR8
    data = Singleton<Foo>::instance().get_data();
#endif
  }
#ifdef ERROR2a
  Bar(int) { }
#endif
  ~Bar() { }
private:
  Bar(Bar const& bar) : Singleton<Bar>(bar) { }

public:
  int get_data(void) const { return data; }
};

static SingletonInstance<Foo> singletonFoo __attribute__ ((unused));
static Global<Test, 0> globalTest0;
static Global<Test, 1> globalTest1;
#ifndef ERROR5
static Global<Test, 2> globalTest2;
#endif
#ifdef ERROR2
#ifdef ERROR2a
static Global<Bar, -1, GlobalConverterInt> globalBarError;
#else
static Global<Bar, 0, GlobalConverterVoid> globalBarError;
#endif
#else
#ifndef ERROR6
static SingletonInstance<Bar> singletonBar __attribute__ ((unused));
#endif
#endif
#ifdef ERROR3
static Global<Test, 0> test;
#endif
#ifdef ERROR4
static SingletonInstance<Foo> test __attribute__ ((unused));
#endif

namespace {
  static Global<Test2, 0, GlobalConverterTest2> S_dummy_Test2;
}

int main(int UNUSED_ARG(argc), char *UNUSED_ARG(argv)[])
{
  using std::cout;
  using std::endl;

#ifdef ERROR7
  Bar bar;
#endif
#ifdef ERROR6a
  Singleton<Bar>::instantiate();
#endif
#ifdef DEBUGGLOBAL
  GlobalObjectManager::main_entered();
#endif

  // Don't show allocations that are allocated before main()
  //make_all_allocations_invisible_except(NULL);

#ifdef CWDEBUG
  // Select debug channels
  ForAllDebugChannels( while (!debugChannel.is_on()) debugChannel.on() );
  DEBUGCHANNELS::dc::malloc.off();
#endif

  // Write debug output to cout
  Debug( libcw_do.set_ostream(&cout) );

  // Turn debug object on
  Debug( libcw_do.on() );

  // Print channels
  // Debug( list_channels_on(libcw_do) );

  cout << Singleton<Foo>::instance().get_data() << endl;
  cout << Singleton<Bar>::instance().get_data() << endl;
  cout << (void *)&Global<Test, 0>::instance() << endl;
  cout << (void *)&Global<Test, 2>::instance() << endl;
  cout << Global<Test2, 0>::instance().str() << endl;

  Debug( list_allocations_on(libcw_do) );

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: newdatatype.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 12:00:44 $
 *
 *  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_extensions.hxx"

#ifndef EXTENSIONS_SOURCE_PROPCTRLR_NEWDATATYPE_HXX
#include "newdatatype.hxx"
#endif
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_NEWDATATYPE_HRC
#include "newdatatype.hrc"
#endif

#ifndef _EXTENSIONS_PROPCTRLR_MODULEPRC_HXX_
#include "modulepcr.hxx"
#endif
#ifndef _EXTENSIONS_FORMCTRLR_PROPRESID_HRC_
#include "formresid.hrc"
#endif

/** === begin UNO includes === **/
/** === end UNO includes === **/

//........................................................................
namespace pcr
{
//........................................................................

    //====================================================================
    //= NewDataTypeDialog
    //====================================================================
    //--------------------------------------------------------------------
    NewDataTypeDialog::NewDataTypeDialog( Window* _pParent, const ::rtl::OUString& _rNameBase, const ::std::vector< ::rtl::OUString >& _rProhibitedNames )
        :ModalDialog( _pParent, PcrRes( RID_DLG_NEW_DATA_TYPE ) )
        ,m_aLabel   ( this, ResId( FT_LABEL  ) )
        ,m_aName    ( this, ResId( ED_NAME   ) )
        ,m_aOK      ( this, ResId( PB_OK     ) )
        ,m_aCancel  ( this, ResId( PB_CANCEL ) )
        ,m_aProhibitedNames( _rProhibitedNames.begin(), _rProhibitedNames.end() )
    {
        FreeResource();

        m_aName.SetModifyHdl( LINK( this, NewDataTypeDialog, OnNameModified ) );

        // find an initial name
        // for this, first remove trailing digits
        sal_Int32 nStripUntil = _rNameBase.getLength();
        while ( nStripUntil > 0 )
        {
            sal_Unicode nChar = _rNameBase[ --nStripUntil ];
            if ( ( nChar < '0' ) || ( nChar > '9' ) )
            {
                if ( nChar == ' ' )
                    --nStripUntil;  // strip the space, too
                break;
            }
        }

        String sNameBase( _rNameBase.copy( 0, nStripUntil ? nStripUntil + 1 : 0 ) );
        sNameBase.Append( ' ' );
        String sInitialName;
        sal_Int32 nPostfixNumber = 1;
        do
        {
            ( sInitialName = sNameBase ) += String::CreateFromInt32( nPostfixNumber++ );
        }
        while ( m_aProhibitedNames.find( sInitialName ) != m_aProhibitedNames.end() );

        m_aName.SetText( sInitialName );
        OnNameModified( NULL );
    }

    //--------------------------------------------------------------------
    IMPL_LINK( NewDataTypeDialog, OnNameModified, void*, /*_pNotInterestedIn*/ )
    {
        String sCurrentName = GetName();
        bool bNameIsOK = ( sCurrentName.Len() > 0 )
                      && ( m_aProhibitedNames.find( sCurrentName ) == m_aProhibitedNames.end() );

        m_aOK.Enable( bNameIsOK );

        return 0L;
    }

//........................................................................
} // namespace pcr
//........................................................................

<commit_msg>INTEGRATION: CWS residcleanup (1.6.56); FILE MERGED 2007/02/28 20:46:11 pl 1.6.56.1: #i74635# no more ResMgr fallback<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: newdatatype.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 08:08:17 $
 *
 *  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_extensions.hxx"

#ifndef EXTENSIONS_SOURCE_PROPCTRLR_NEWDATATYPE_HXX
#include "newdatatype.hxx"
#endif
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_NEWDATATYPE_HRC
#include "newdatatype.hrc"
#endif

#ifndef _EXTENSIONS_PROPCTRLR_MODULEPRC_HXX_
#include "modulepcr.hxx"
#endif
#ifndef _EXTENSIONS_FORMCTRLR_PROPRESID_HRC_
#include "formresid.hrc"
#endif

/** === begin UNO includes === **/
/** === end UNO includes === **/

//........................................................................
namespace pcr
{
//........................................................................

    //====================================================================
    //= NewDataTypeDialog
    //====================================================================
    //--------------------------------------------------------------------
    NewDataTypeDialog::NewDataTypeDialog( Window* _pParent, const ::rtl::OUString& _rNameBase, const ::std::vector< ::rtl::OUString >& _rProhibitedNames )
        :ModalDialog( _pParent, PcrRes( RID_DLG_NEW_DATA_TYPE ) )
        ,m_aLabel   ( this, PcrRes( FT_LABEL  ) )
        ,m_aName    ( this, PcrRes( ED_NAME   ) )
        ,m_aOK      ( this, PcrRes( PB_OK     ) )
        ,m_aCancel  ( this, PcrRes( PB_CANCEL ) )
        ,m_aProhibitedNames( _rProhibitedNames.begin(), _rProhibitedNames.end() )
    {
        FreeResource();

        m_aName.SetModifyHdl( LINK( this, NewDataTypeDialog, OnNameModified ) );

        // find an initial name
        // for this, first remove trailing digits
        sal_Int32 nStripUntil = _rNameBase.getLength();
        while ( nStripUntil > 0 )
        {
            sal_Unicode nChar = _rNameBase[ --nStripUntil ];
            if ( ( nChar < '0' ) || ( nChar > '9' ) )
            {
                if ( nChar == ' ' )
                    --nStripUntil;  // strip the space, too
                break;
            }
        }

        String sNameBase( _rNameBase.copy( 0, nStripUntil ? nStripUntil + 1 : 0 ) );
        sNameBase.Append( ' ' );
        String sInitialName;
        sal_Int32 nPostfixNumber = 1;
        do
        {
            ( sInitialName = sNameBase ) += String::CreateFromInt32( nPostfixNumber++ );
        }
        while ( m_aProhibitedNames.find( sInitialName ) != m_aProhibitedNames.end() );

        m_aName.SetText( sInitialName );
        OnNameModified( NULL );
    }

    //--------------------------------------------------------------------
    IMPL_LINK( NewDataTypeDialog, OnNameModified, void*, /*_pNotInterestedIn*/ )
    {
        String sCurrentName = GetName();
        bool bNameIsOK = ( sCurrentName.Len() > 0 )
                      && ( m_aProhibitedNames.find( sCurrentName ) == m_aProhibitedNames.end() );

        m_aOK.Enable( bNameIsOK );

        return 0L;
    }

//........................................................................
} // namespace pcr
//........................................................................

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: testcppuno.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: jl $ $Date: 2000-10-24 09:34:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <windows.h>
#include <comdef.h>
#include <tchar.h>
#include <atlbase.h>
extern CComModule _Module;
#include<atlcom.h>
#include<atlimpl.cpp>

#include <com/sun/star/bridge/ModelDependent.hpp>
#include <com/sun/star/bridge/XBridgeSupplier2.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/script/XInvocation.hpp>
#include <oletest/XCallback.hpp>
#include <rtl/process.h>
#include <com/sun/star/uno/Reference.h>
#include <cppuhelper/servicefactory.hxx>
#include <rtl/string.h>
#pragma hdrstop

CComModule _Module;
BEGIN_OBJECT_MAP(ObjectMap)
END_OBJECT_MAP()

using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::script;
using namespace com::sun::star::bridge;
using namespace com::sun::star::bridge::ModelDependent;
using namespace cppu;
using namespace rtl;
HRESULT doTest();
bool incrementMultidimensionalIndex(sal_Int32 dimensions,
                                                                   const sal_Int32 * parDimensionLengths,
                                                                   sal_Int32 * parMultidimensionalIndex);

int __cdecl _tmain( int argc, _TCHAR * argv[] )
{
    HRESULT hr;
    if( FAILED( hr=CoInitialize(NULL)))
    {
        _tprintf(_T("CoInitialize failed \n"));
        return -1;
    }

    _Module.Init( ObjectMap, GetModuleHandle( NULL));

    if( FAILED(hr=doTest()))
    {
        _com_error err( hr);
        const TCHAR * errMsg= err.ErrorMessage();
        MessageBox( NULL, errMsg, "Test failed", MB_ICONERROR);
    }

    _Module.Term();
    CoUninitialize();
    return 0;
}

HRESULT doTest()
{
    HRESULT hr= S_OK;
    long i,j;
    SAFEARRAY* par;
    CComDispatchDriver disp;
    CComVariant result;
    CComVariant param1;
    CComPtr<IUnknown> spUnkFactory;
    if( SUCCEEDED( spUnkFactory.CoCreateInstance(L"com.sun.star.ServiceManager")))
    {
        disp= spUnkFactory;
        param1= L"oletest.OleTest";
        disp.Invoke1( L"createInstance", &param1, &result);

        disp= result.pdispVal;

        // disp contains now oletest.OleTest

        // one dimensional array
        par= SafeArrayCreateVector( VT_UI1, 0, 5);
        unsigned char arbyte[]= { 1,2,3,4,5};
        for(  i= 0; i < 5;i++)
            hr= SafeArrayPutElement( par, &i, &arbyte[i]);

        result.Clear();
        param1.vt= VT_ARRAY| VT_UI1;
        param1.byref= par;
        disp.Invoke1(L"methodByte", &param1, &result);
        SafeArrayDestroy( par);

        // two dimensional array
        SAFEARRAYBOUND bounds[2];
        bounds[0].cElements= 3;
        bounds[0].lLbound= 0;
        bounds[1].cElements= 2;
        bounds[1].lLbound= 0;
        par= SafeArrayCreate( VT_I4, 2, bounds );

        long index2[2];
        memset( index2, 0, 2 * sizeof( long) );
        long dimLengths[]={3,2};

        long data;
        do
        {
            data= index2[1] * 3 + index2[0] +1;
            SafeArrayPutElement( par, index2, &data);
        }while( incrementMultidimensionalIndex( 2, dimLengths, index2) );

        result.Clear();
        param1.vt= VT_ARRAY | VT_I4;
        param1.byref= par;
        disp.Invoke1(L"methodSequence", &param1, &result);

        SAFEARRAY* arRet= result.parray;

        for( i= 0; i < 2 ; i++)
        {
            CComVariant varx;
            varx.Clear();
            hr= SafeArrayGetElement( arRet, &i, &varx);
            SAFEARRAY* ari= varx.parray;

            for( j= 0; j < 3; j++)
            {
                CComVariant varj;
                varj.Clear();
                hr= SafeArrayGetElement( ari, &j, &varj);
            }

        }
        SafeArrayDestroy( par);

    }

    return hr;
}

// left index is least significant
bool incrementMultidimensionalIndex(sal_Int32 dimensions,
                                              const sal_Int32 * parDimensionLengths,
                                              sal_Int32 * parMultidimensionalIndex)
{
    if( dimensions < 1)
        return sal_False;

    bool ret= sal_True;
    bool carry= sal_True; // to get into the while loop

    sal_Int32 currentDimension= 0; //most significant is 1
    while( carry)
    {
        parMultidimensionalIndex[ currentDimension ]++;
        // if carryover, set index to 0 and handle carry on a level above
        if( parMultidimensionalIndex[ currentDimension] > (parDimensionLengths[ currentDimension] - 1))
            parMultidimensionalIndex[ currentDimension]= 0;
        else
            carry= sal_False;

        currentDimension ++;
        // if dimensions drops below 1 and carry is set than then all indices are 0 again
        // this is signalled by returning sal_False
        if( currentDimension > dimensions - 1 && carry)
        {
            carry= sal_False;
            ret= sal_False;
        }
    }
    return ret;
}<commit_msg>*** empty log message ***<commit_after>/*************************************************************************
 *
 *  $RCSfile: testcppuno.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: jl $ $Date: 2001-12-06 08:35:16 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <windows.h>
#include <comdef.h>
#include <tchar.h>
#include <atlbase.h>
extern CComModule _Module;
#include<atlcom.h>
#include<atlimpl.cpp>

#include <com/sun/star/bridge/ModelDependent.hpp>
#include <com/sun/star/bridge/XBridgeSupplier2.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/script/XInvocation.hpp>
#include <oletest/XCallback.hpp>
#include <rtl/process.h>
#include <com/sun/star/uno/Reference.h>
#include <cppuhelper/servicefactory.hxx>
#include <rtl/string.h>
#pragma hdrstop

CComModule _Module;
BEGIN_OBJECT_MAP(ObjectMap)
END_OBJECT_MAP()

using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::script;
using namespace com::sun::star::bridge;
using namespace com::sun::star::bridge::ModelDependent;
using namespace cppu;
using namespace rtl;
HRESULT doTest();
bool incrementMultidimensionalIndex(sal_Int32 dimensions,
                                                                   const sal_Int32 * parDimensionLengths,
                                                                   sal_Int32 * parMultidimensionalIndex);

int __cdecl _tmain( int argc, _TCHAR * argv[] )
{
    HRESULT hr;
    if( FAILED( hr=CoInitialize(NULL)))
    {
        _tprintf(_T("CoInitialize failed \n"));
        return -1;
    }

    _Module.Init( ObjectMap, GetModuleHandle( NULL));

    if( FAILED(hr=doTest()))
    {
        _com_error err( hr);
        const TCHAR * errMsg= err.ErrorMessage();
        MessageBox( NULL, errMsg, "Test failed", MB_ICONERROR);
    }

    _Module.Term();
    CoUninitialize();
    return 0;
}

HRESULT doTest()
{
    HRESULT hr= S_OK;
    long i,j;
    SAFEARRAY* par;
    CComDispatchDriver disp;
    CComVariant result;
    CComVariant param1;
    CComPtr<IUnknown> spUnkFactory;
    if( SUCCEEDED( spUnkFactory.CoCreateInstance(L"com.sun.star.ServiceManager")))
    {
        disp= spUnkFactory;
        param1= L"oletest.OleTest";
        disp.Invoke1( L"createInstance", &param1, &result);

        disp= result.pdispVal;

        // disp contains now oletest.OleTest

        // one dimensional array
        par= SafeArrayCreateVector( VT_UI1, 0, 5);
        unsigned char arbyte[]= { 1,2,3,4,5};
        for(  i= 0; i < 5;i++)
            hr= SafeArrayPutElement( par, &i, &arbyte[i]);

        result.Clear();
        param1.vt= VT_ARRAY| VT_UI1;
        param1.byref= par;
        disp.Invoke1(L"methodByte", &param1, &result);
        SafeArrayDestroy( par);

        // two dimensional array
        SAFEARRAYBOUND bounds[2];
        // least significant dimension first, Dimension 1
        bounds[0].cElements= 3;
        bounds[0].lLbound= 0;
        // Dimension 2
        bounds[1].cElements= 2;
        bounds[1].lLbound= 0;
        par= SafeArrayCreate( VT_I4, 2, bounds );

        long uBound1;
        long uBound2;
        hr= SafeArrayGetUBound( par, 1, &uBound1);
        hr= SafeArrayGetUBound( par, 2, &uBound2);

        long index2[2];
        memset( index2, 0, 2 * sizeof( long) );
        long dimLengths[]={3,2};

        long data;
        do
        {
            data= index2[1] * 3 + index2[0] +1;
            hr= SafeArrayPutElement( par, index2, &data);
        }while( incrementMultidimensionalIndex( 2, dimLengths, index2) );

        long* pdata;
        long (*dataL)[2][3];
        hr= SafeArrayAccessData( par, (void**)&pdata);
        dataL= (long(*)[2][3])pdata;

        for (long i= 0; i < 2; i ++)
        {
            for(long j= 0; j < 3; j++)
                data= (*dataL)[i][j];
        }
        hr= SafeArrayUnaccessData(par);

        result.Clear();
        param1.vt= VT_ARRAY | VT_I4;
        param1.byref= par;
        disp.Invoke1(L"methodSequence", &param1, &result);

        SAFEARRAY* arRet= result.parray;

        for( i= 0; i < 2 ; i++)
        {
            CComVariant varx;
            varx.Clear();
            hr= SafeArrayGetElement( arRet, &i, &varx);
            SAFEARRAY* ari= varx.parray;

            for( j= 0; j < 3; j++)
            {
                CComVariant varj;
                varj.Clear();
                hr= SafeArrayGetElement( ari, &j, &varj);
            }

        }
        SafeArrayDestroy( par);

    }

    return hr;
}

// left index is least significant
bool incrementMultidimensionalIndex(sal_Int32 dimensions,
                                              const sal_Int32 * parDimensionLengths,
                                              sal_Int32 * parMultidimensionalIndex)
{
    if( dimensions < 1)
        return sal_False;

    bool ret= sal_True;
    bool carry= sal_True; // to get into the while loop

    sal_Int32 currentDimension= 0; //most significant is 1
    while( carry)
    {
        parMultidimensionalIndex[ currentDimension ]++;
        // if carryover, set index to 0 and handle carry on a level above
        if( parMultidimensionalIndex[ currentDimension] > (parDimensionLengths[ currentDimension] - 1))
            parMultidimensionalIndex[ currentDimension]= 0;
        else
            carry= sal_False;

        currentDimension ++;
        // if dimensions drops below 1 and carry is set than then all indices are 0 again
        // this is signalled by returning sal_False
        if( currentDimension > dimensions - 1 && carry)
        {
            carry= sal_False;
            ret= sal_False;
        }
    }
    return ret;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/image_util.hpp>

// stl
#include <cmath>

namespace mapnik {

template <typename T>
void agg_renderer<T>::process(raster_symbolizer const& sym,
                              Feature const& feature,
                              proj_transform const& prj_trans)
{
    raster_ptr const& raster=feature.get_raster();
    if (raster)
    {
        // If there's a colorizer defined, use it to color the raster in-place
        raster_colorizer_ptr colorizer = sym.get_colorizer();
        if (colorizer)
            colorizer->colorize(raster,feature.props());

        box2d<double> ext=t_.forward(raster->ext_);

        int start_x = (int)ext.minx();
        int start_y = (int)ext.miny();
        int end_x = (int)ceil(ext.maxx());
        int end_y = (int)ceil(ext.maxy());
        int raster_width = end_x - start_x;
        int raster_height = end_y - start_y;
        double err_offs_x = ext.minx() - start_x;
        double err_offs_y = ext.miny() - start_y;

        if ( raster_width > 0 && raster_height > 0)
        {
            double scale_factor = ext.width() / raster->data_.width();
            image_data_32 target(raster_width,raster_height);

            if (sym.get_scaling() == "bilinear8"){
                scale_image_bilinear8<image_data_32>(target,raster->data_, err_offs_x, err_offs_y);
            } else if (sym.get_scaling() == "bilinear_old") {
                scale_image_bilinear_old<image_data_32>(target,raster->data_, err_offs_x, err_offs_y);
            } else {
                scaling_method_e scaling_method = get_scaling_method_by_name(sym.get_scaling());
                scale_image_agg<image_data_32>(target,raster->data_, (scaling_method_e)scaling_method, scale_factor, err_offs_x, err_offs_y, sym.calculate_filter_factor());
            }

            if (sym.get_mode() == "normal"){
                if (sym.get_opacity() == 1.0) {
                    pixmap_.set_rectangle_alpha(start_x,start_y,target);
                } else {
                    pixmap_.set_rectangle_alpha2(target,start_x,start_y, sym.get_opacity());
                }
            } else if (sym.get_mode() == "grain_merge"){
                pixmap_.template merge_rectangle<MergeGrain> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "grain_merge2"){
                pixmap_.template merge_rectangle<MergeGrain2> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "multiply"){
                pixmap_.template merge_rectangle<Multiply> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "multiply2"){
                pixmap_.template merge_rectangle<Multiply2> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "divide"){
                pixmap_.template merge_rectangle<Divide> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "divide2"){
                pixmap_.template merge_rectangle<Divide2> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "screen"){
                pixmap_.template merge_rectangle<Screen> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "hard_light"){
                pixmap_.template merge_rectangle<HardLight> (target,start_x,start_y, sym.get_opacity());
            } else {
                if (sym.get_opacity() == 1.0){
                    pixmap_.set_rectangle(start_x,start_y,target);
                } else {
                    pixmap_.set_rectangle_alpha2(target,start_x,start_y, sym.get_opacity());
                }
            }
            // TODO: other modes? (add,diff,sub,...)
        }
    }
}

template void agg_renderer<image_32>::process(raster_symbolizer const&,
                                              Feature const&,
                                              proj_transform const&);

}
<commit_msg>reverted patch which was committed by mistake<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/image_util.hpp>

// stl
#include <cmath>

namespace mapnik {

template <typename T>
void agg_renderer<T>::process(raster_symbolizer const& sym,
                              Feature const& feature,
                              proj_transform const& prj_trans)
{
    raster_ptr const& raster=feature.get_raster();
    if (raster)
    {
        // If there's a colorizer defined, use it to color the raster in-place
        raster_colorizer_ptr colorizer = sym.get_colorizer();
        if (colorizer)
            colorizer->colorize(raster,feature.props());

        box2d<double> ext=t_.forward(raster->ext_);

        int start_x = (int)ext.minx();
        int start_y = (int)ext.miny();
        int end_x = (int)ceil(ext.maxx());
        int end_y = (int)ceil(ext.maxy());
        int raster_width = end_x - start_x;
        int raster_height = end_y - start_y;
        double err_offs_x = ext.minx() - start_x;
        double err_offs_y = ext.miny() - start_y;

        if ( raster_width > 0 && raster_height > 0)
        {
            double scale_factor = ext.width() / raster->data_.width();
            image_data_32 target(raster_width,raster_height);

            if (sym.get_scaling() == "bilinear8"){
                scale_image_bilinear8<image_data_32>(target,raster->data_, err_offs_x, err_offs_y);
            } else {
                scaling_method_e scaling_method = get_scaling_method_by_name(sym.get_scaling());
                scale_image_agg<image_data_32>(target,raster->data_, (scaling_method_e)scaling_method, scale_factor, err_offs_x, err_offs_y, sym.calculate_filter_factor());
            }

            if (sym.get_mode() == "normal"){
                if (sym.get_opacity() == 1.0) {
                    pixmap_.set_rectangle_alpha(start_x,start_y,target);
                } else {
                    pixmap_.set_rectangle_alpha2(target,start_x,start_y, sym.get_opacity());
                }
            } else if (sym.get_mode() == "grain_merge"){
                pixmap_.template merge_rectangle<MergeGrain> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "grain_merge2"){
                pixmap_.template merge_rectangle<MergeGrain2> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "multiply"){
                pixmap_.template merge_rectangle<Multiply> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "multiply2"){
                pixmap_.template merge_rectangle<Multiply2> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "divide"){
                pixmap_.template merge_rectangle<Divide> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "divide2"){
                pixmap_.template merge_rectangle<Divide2> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "screen"){
                pixmap_.template merge_rectangle<Screen> (target,start_x,start_y, sym.get_opacity());
            } else if (sym.get_mode() == "hard_light"){
                pixmap_.template merge_rectangle<HardLight> (target,start_x,start_y, sym.get_opacity());
            } else {
                if (sym.get_opacity() == 1.0){
                    pixmap_.set_rectangle(start_x,start_y,target);
                } else {
                    pixmap_.set_rectangle_alpha2(target,start_x,start_y, sym.get_opacity());
                }
            }
            // TODO: other modes? (add,diff,sub,...)
        }
    }
}

template void agg_renderer<image_32>::process(raster_symbolizer const&,
                                              Feature const&,
                                              proj_transform const&);

}
<|endoftext|>


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

The source code of the Parasol project is made publicly available under the
terms described in the LICENSE.TXT file that is distributed with this package.
Please refer to it for further information on licensing.

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

#include <parasol/main.h>
#include <startup.h>
#include <parasol/modules/core.h>
#include <string.h>

#include "common.h"

CSTRING ProgName      = "Fluid";
CSTRING ProgAuthor    = "Paul Manias";
CSTRING ProgDate      = "November 2018";
CSTRING ProgCopyright = "Copyright Paul Manias © 2000-2018";
LONG   ProgDebug = 0;
FLOAT  ProgCoreVersion = VER_CORE;

extern struct CoreBase *CoreBase;

static CSTRING *glArgs = NULL;
static BYTE glTime = FALSE;
static STRING glProcedure = NULL;
static STRING glTargetFile = NULL;

static const char glHelp[] = {
"Usage: fluid [options...] script.fluid [arg1=v1 arg2=v2 ...]\n\
\n\
Special options are:\n\
\n\
 --procedure [n] The name of a procedure in the script to execute.\n\
 --time          Print the amount of time that it took to execute the program.\n\
 --log-info      Activates run-time log messages at INFO level.\n\
 --log-error     Activates run-time log messages at ERROR level.\n\
 \n\
 If no script file is specified, the script will be parsed from std input after an EOF is received.\n\
 \n\
 All parameters following the script file are passed through as arguments to the program.\n\
 Arrays can be passed in the format key={ value1 value2 }\n"
};

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

static void set_script_args(objScript *Script, CSTRING *Args)
{
   char argbuffer[100];
   STRING argname = argbuffer;

   ULONG i;
   for (i=0; Args[i]; i++) {

      ULONG j = 0, k = 0;
      while (Args[i][k] IS '-') k++;
      while ((Args[i][k]) AND (Args[i][k] != '=') AND (j < sizeof(argbuffer)-10)) {
         argname[j++] = Args[i][k++];
      }
      argname[j] = 0;
      LONG al = j;

      CSTRING value = NULL;
      if (Args[i][j] IS '=') {
         value = Args[i] + j + 1;
      }
      else if (!Args[i+1]) {
         SetVar(Script, argname, "1");
         continue;
      }
      else if ((Args[i+1][0] IS '-') AND (Args[i+1][1] IS '-')) {
         SetVar(Script, argname, "1");
         continue;
      }
      else value = Args[++i];

      if ((value[0] IS '{') AND (value[1] <= 0x20)) {
         // Array definition, e.g. files={ file1.txt file2.txt }
         // This will be converted to files(0)=file.txt files(1)=file2.txt

         i++;
         LONG arg_index = 0;
         while ((Args[i]) AND (Args[i][0] != '}')) {
            StrFormat(argname+al, sizeof(argbuffer)-al, "(%d)", arg_index);
            SetVar(Script, argname, Args[i]);
            arg_index++;
            i++;
         }
         if (!Args[i]) break;
         // Note that the last arg in the array will be the "}" that closes it

         char array_size[16];
         StrCopy(":size", argname+al, sizeof(argbuffer)-al);
         IntToStr(arg_index, array_size, sizeof(array_size));
         SetVar(Script, argname, array_size);
      }
      else SetVar(Script, argname, value);
   }
}

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

static void run_script(objScript *Script)
{
   DOUBLE start_time = (DOUBLE)PreciseTime() / 1000000.0;
   ERROR error;
   if (!(error = acInit(Script))) {
      if (!(error = acActivate(Script))) {
         if (glTime) { // Print the execution time of the script
            DOUBLE end_time = (DOUBLE)PreciseTime() / 1000000.0;
            print("Script executed in %f seconds.\n\n", end_time - start_time);
         }
      }
      else print("Script failed during processing.  Use the --log-error option to examine the failure.");
   }
   else print("Failed to load / initialise the script: %s", GetErrorMsg(error));
}

//****************************************************************************
// Executes the target.

static void exec_source(CSTRING TargetFile, CSTRING Procedure)
{
   CLASSID class_id, subclass;
   ERROR error;
   if ((error = IdentifyFile(TargetFile, "Open", 0, &class_id, &subclass, NULL))) {
      subclass = ID_FLUID;
      class_id = ID_SCRIPT;
   }

   if (subclass != ID_FLUID) return;

   objScript *script;
   if (!NewObject(ID_FLUID, 0, &script)) {
      SetFields(script, FID_Path|TSTR,      TargetFile,
                        FID_Procedure|TSTR, Procedure,
                        TAGEND);

      if (glArgs) set_script_args(script, glArgs);

      run_script(script);
   }
   else print("Internal Failure: Failed to create a new Script object for file processing.");
}

//****************************************************************************
// Process arguments

static ERROR process_args(void)
{
   CSTRING *args;
   LONG i;

   if ((!GetPointer(CurrentTask(), FID_Parameters, &args)) AND (args)) {
      for (i=0; args[i]; i++) {
         if (!StrMatch(args[i], "--help")) {
            // Print help for the user
            print(glHelp);
            return ERR_Terminate;
         }
         else if (!StrMatch(args[i], "--verify")) {
            // Special internal function that checks that the installation is valid, returning 1 if checks pass.

            static CSTRING modules[] = { // These modules must be present for an installation to be valid.
               "display", "document", "fluid", "font", "http", "jpeg", "json", "network", "parc",
               "picture", "surface", "svg", "vector", "widget", "window", "xml"
            };

            struct DirInfo *dir;
            LONG total = 0;
            if (!OpenDir("modules:", RDF_QUALIFY, &dir)) {
               while (!ScanDir(dir)) {
                  struct FileInfo *folder = dir->Info;
                  if (folder->Flags & RDF_FILE) {
                     LONG m;
                     for (m=0; m < ARRAYSIZE(modules); m++) {
                        if (!StrCompare(modules[m], folder->Name, 0, 0)) total++;
                     }
                  }
               }
               CloseDir(dir);
            }

            if (total >= ARRAYSIZE(modules)) print("1");
            return ERR_Terminate;
         }
         else if (!StrMatch(args[i], "--time")) {
            glTime = TRUE;
         }
         else if (!StrMatch(args[i], "--procedure")) {
            if (glProcedure) { FreeMemory(glProcedure); glProcedure = NULL; }

            if (args[i+1]) {
               glProcedure = StrClone(args[i+1]);
               i++;
            }
         }
         else {
            if ((args[i][0] IS '-') AND (args[i][1] IS '-')) {
               glArgs = args + i;
            }
            else {
               // Assume this arg is the target file.

               if (ResolvePath(args[i], RSF_APPROXIMATE, &glTargetFile)) {
                  print("Unable to find file '%s'", args[i]);
                  return ERR_Terminate;
               }

               if (args[i+1]) glArgs = args + i + 1;
            }

            break;
         }
      }
   }

   return ERR_Okay;
}

//****************************************************************************
// Support for stdin

static STRING glScriptBuffer = NULL;
static LONG glScriptBufferSize = 0;
static LONG glScriptBufferLength = 0;
static LONG glScriptReceivedMsg = 0;

static void read_stdin(objTask *Task, APTR Buffer, LONG Size, ERROR Status)
{
   if (Status IS ERR_Finished) {
      SendMessage(0, glScriptReceivedMsg, MSF_WAIT, NULL, 0);
      LogMsg("Input pipe closed.");
      return;
   }

   if (!glScriptBuffer) {
      glScriptBufferSize = Size + 1;
      if (!AllocMemory(glScriptBufferSize, MEM_STRING, &glScriptBuffer, NULL)) {
         CopyMemory(Buffer, glScriptBuffer, glScriptBufferSize);
         glScriptBufferLength = Size;
      }
      else SendMessage(0, MSGID_QUIT, MSF_WAIT, NULL, 0);
   }
   else if (glScriptBufferLength + Size >= glScriptBufferSize-1) {
      LONG inc = (Size < 4096) ? 4096 : Size;
      if (!ReallocMemory(glScriptBuffer, glScriptBufferSize + inc, &glScriptBuffer, NULL)) {
         CopyMemory(Buffer, glScriptBuffer + glScriptBufferLength, Size);
         glScriptBufferSize += inc;
         glScriptBufferLength += Size;
         glScriptBuffer[glScriptBufferLength] = 0;
      }
      else SendMessage(0, MSGID_QUIT, MSF_WAIT, NULL, 0);
   }
   else {
      CopyMemory(Buffer, glScriptBuffer + glScriptBufferLength, Size);
      glScriptBufferLength += Size;
      glScriptBuffer[glScriptBufferLength] = 0;
   }

   if (glScriptBuffer[glScriptBufferLength-1] IS 0x1a) { // Ctrl-Z
      glScriptBuffer[glScriptBufferLength-1] = 0;
      SendMessage(0, glScriptReceivedMsg, MSF_WAIT, NULL, 0);
      LogMsg("EOF received.");
      return;
   }
}

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

static ERROR msg_script_received(APTR Custom, LONG MsgID, LONG MsgType, APTR Message, LONG MsgSize)
{
   return ERR_Terminate;
}

//****************************************************************************
// Main entry point

int main(int argc, CSTRING *argv)
{
   const char *msg = init_parasol(argc, argv);
   if (msg) {
      int i;
      for (i=1; i < argc; i++) { // If in --verify mode, return with no error code and print nothing.
         if (!strcmp(argv[i], "--verify")) return 0;
      }
      print(msg);
      return -1;
   }

   if (!process_args()) {
      if (glTargetFile) {
         LONG type;
         if ((AnalysePath(glTargetFile, &type) != ERR_Okay) OR (type != LOC_FILE)) {
            print("File '%s' does not exist.", glTargetFile);
         }
         else exec_source(glTargetFile, glProcedure);
      }
      else {
         // Read script from std input

         glScriptReceivedMsg = AllocateID(IDTYPE_MESSAGE);

         FUNCTION callback;
         SET_FUNCTION_STDC(callback, (APTR)&msg_script_received);
         AddMsgHandler(NULL, glScriptReceivedMsg, &callback, NULL);

         SET_FUNCTION_STDC(callback, (APTR)&read_stdin);
         SetFunction(CurrentTask(), FID_InputCallback, &callback);

         ProcessMessages(0, -1);

         if (glScriptBuffer) {
            objScript *script;
            if (!NewObject(ID_FLUID, 0, &script)) {
               SetString(script, FID_Statement, glScriptBuffer);
               if (glProcedure) SetString(script, FID_Procedure, glProcedure);
               if (glArgs) set_script_args(script, glArgs);
               run_script(script);
               acFree(script);
            }
            else print("Internal Failure: Failed to create a new Script object for file processing.");
         }
      }
   }

   if (glScriptBuffer) { FreeMemory(glScriptBuffer); glScriptBuffer = NULL; }
   if (glProcedure)    { FreeMemory(glProcedure);    glProcedure = NULL; }
   if (glTargetFile)   { FreeMemory(glTargetFile);   glTargetFile = NULL; }

   close_parasol();

   return 0;
}
<commit_msg>Fixed Fluid bug in detecting '=' in commandline parameters<commit_after>/*****************************************************************************

The source code of the Parasol project is made publicly available under the
terms described in the LICENSE.TXT file that is distributed with this package.
Please refer to it for further information on licensing.

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

#include <parasol/main.h>
#include <startup.h>
#include <parasol/modules/core.h>
#include <string.h>

#include "common.h"

CSTRING ProgName      = "Fluid";
CSTRING ProgAuthor    = "Paul Manias";
CSTRING ProgDate      = "November 2018";
CSTRING ProgCopyright = "Copyright Paul Manias © 2000-2018";
LONG   ProgDebug = 0;
FLOAT  ProgCoreVersion = VER_CORE;

extern struct CoreBase *CoreBase;

static CSTRING *glArgs = NULL;
static BYTE glTime = FALSE;
static STRING glProcedure = NULL;
static STRING glTargetFile = NULL;

static const char glHelp[] = {
"Usage: fluid [options...] script.fluid [arg1=v1 arg2=v2 ...]\n\
\n\
Special options are:\n\
\n\
 --procedure [n] The name of a procedure in the script to execute.\n\
 --time          Print the amount of time that it took to execute the program.\n\
 --log-info      Activates run-time log messages at INFO level.\n\
 --log-error     Activates run-time log messages at ERROR level.\n\
 \n\
 If no script file is specified, the script will be parsed from std input after an EOF is received.\n\
 \n\
 All parameters following the script file are passed through as arguments to the program.\n\
 Arrays can be passed in the format key={ value1 value2 }\n"
};

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

static void set_script_args(objScript *Script, CSTRING *Args)
{
   char argbuffer[100];
   STRING argname = argbuffer;

   ULONG i;
   for (i=0; Args[i]; i++) {

      ULONG j = 0, k = 0;
      while (Args[i][k] IS '-') k++;
      while ((Args[i][k]) AND (Args[i][k] != '=') AND (j < sizeof(argbuffer)-10)) {
         argname[j++] = Args[i][k++];
      }
      argname[j] = 0;
      LONG al = j;

      CSTRING value = NULL;
      if (Args[i][k] IS '=') {
         value = Args[i] + k + 1;
      }
      else if (!Args[i+1]) {
         SetVar(Script, argname, "1");
         continue;
      }
      else if ((Args[i+1][0] IS '-') AND (Args[i+1][1] IS '-')) {
         SetVar(Script, argname, "1");
         continue;
      }
      else value = Args[++i];

      if ((value[0] IS '{') AND (value[1] <= 0x20)) {
         // Array definition, e.g. files={ file1.txt file2.txt }
         // This will be converted to files(0)=file.txt files(1)=file2.txt

         i++;
         LONG arg_index = 0;
         while ((Args[i]) AND (Args[i][0] != '}')) {
            StrFormat(argname+al, sizeof(argbuffer)-al, "(%d)", arg_index);
            SetVar(Script, argname, Args[i]);
            arg_index++;
            i++;
         }
         if (!Args[i]) break;
         // Note that the last arg in the array will be the "}" that closes it

         char array_size[16];
         StrCopy(":size", argname+al, sizeof(argbuffer)-al);
         IntToStr(arg_index, array_size, sizeof(array_size));
         SetVar(Script, argname, array_size);
      }
      else SetVar(Script, argname, value);
   }
}

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

static void run_script(objScript *Script)
{
   DOUBLE start_time = (DOUBLE)PreciseTime() / 1000000.0;
   ERROR error;
   if (!(error = acInit(Script))) {
      if (!(error = acActivate(Script))) {
         if (glTime) { // Print the execution time of the script
            DOUBLE end_time = (DOUBLE)PreciseTime() / 1000000.0;
            print("Script executed in %f seconds.\n\n", end_time - start_time);
         }
      }
      else print("Script failed during processing.  Use the --log-error option to examine the failure.");
   }
   else print("Failed to load / initialise the script: %s", GetErrorMsg(error));
}

//****************************************************************************
// Executes the target.

static void exec_source(CSTRING TargetFile, CSTRING Procedure)
{
   CLASSID class_id, subclass;
   ERROR error;
   if ((error = IdentifyFile(TargetFile, "Open", 0, &class_id, &subclass, NULL))) {
      subclass = ID_FLUID;
      class_id = ID_SCRIPT;
   }

   if (subclass != ID_FLUID) return;

   objScript *script;
   if (!NewObject(ID_FLUID, 0, &script)) {
      SetFields(script, FID_Path|TSTR,      TargetFile,
                        FID_Procedure|TSTR, Procedure,
                        TAGEND);

      if (glArgs) set_script_args(script, glArgs);

      run_script(script);
   }
   else print("Internal Failure: Failed to create a new Script object for file processing.");
}

//****************************************************************************
// Process arguments

static ERROR process_args(void)
{
   CSTRING *args;
   LONG i;

   if ((!GetPointer(CurrentTask(), FID_Parameters, &args)) AND (args)) {
      for (i=0; args[i]; i++) {
         if (!StrMatch(args[i], "--help")) {
            // Print help for the user
            print(glHelp);
            return ERR_Terminate;
         }
         else if (!StrMatch(args[i], "--verify")) {
            // Special internal function that checks that the installation is valid, returning 1 if checks pass.

            static CSTRING modules[] = { // These modules must be present for an installation to be valid.
               "display", "document", "fluid", "font", "http", "jpeg", "json", "network", "parc",
               "picture", "surface", "svg", "vector", "widget", "window", "xml"
            };

            struct DirInfo *dir;
            LONG total = 0;
            if (!OpenDir("modules:", RDF_QUALIFY, &dir)) {
               while (!ScanDir(dir)) {
                  struct FileInfo *folder = dir->Info;
                  if (folder->Flags & RDF_FILE) {
                     LONG m;
                     for (m=0; m < ARRAYSIZE(modules); m++) {
                        if (!StrCompare(modules[m], folder->Name, 0, 0)) total++;
                     }
                  }
               }
               CloseDir(dir);
            }

            if (total >= ARRAYSIZE(modules)) print("1");
            return ERR_Terminate;
         }
         else if (!StrMatch(args[i], "--time")) {
            glTime = TRUE;
         }
         else if (!StrMatch(args[i], "--procedure")) {
            if (glProcedure) { FreeMemory(glProcedure); glProcedure = NULL; }

            if (args[i+1]) {
               glProcedure = StrClone(args[i+1]);
               i++;
            }
         }
         else {
            if ((args[i][0] IS '-') AND (args[i][1] IS '-')) {
               glArgs = args + i;
            }
            else {
               // Assume this arg is the target file.

               if (ResolvePath(args[i], RSF_APPROXIMATE, &glTargetFile)) {
                  print("Unable to find file '%s'", args[i]);
                  return ERR_Terminate;
               }

               if (args[i+1]) glArgs = args + i + 1;
            }

            break;
         }
      }
   }

   return ERR_Okay;
}

//****************************************************************************
// Support for stdin

static STRING glScriptBuffer = NULL;
static LONG glScriptBufferSize = 0;
static LONG glScriptBufferLength = 0;
static LONG glScriptReceivedMsg = 0;

static void read_stdin(objTask *Task, APTR Buffer, LONG Size, ERROR Status)
{
   if (Status IS ERR_Finished) {
      SendMessage(0, glScriptReceivedMsg, MSF_WAIT, NULL, 0);
      LogMsg("Input pipe closed.");
      return;
   }

   if (!glScriptBuffer) {
      glScriptBufferSize = Size + 1;
      if (!AllocMemory(glScriptBufferSize, MEM_STRING, &glScriptBuffer, NULL)) {
         CopyMemory(Buffer, glScriptBuffer, glScriptBufferSize);
         glScriptBufferLength = Size;
      }
      else SendMessage(0, MSGID_QUIT, MSF_WAIT, NULL, 0);
   }
   else if (glScriptBufferLength + Size >= glScriptBufferSize-1) {
      LONG inc = (Size < 4096) ? 4096 : Size;
      if (!ReallocMemory(glScriptBuffer, glScriptBufferSize + inc, &glScriptBuffer, NULL)) {
         CopyMemory(Buffer, glScriptBuffer + glScriptBufferLength, Size);
         glScriptBufferSize += inc;
         glScriptBufferLength += Size;
         glScriptBuffer[glScriptBufferLength] = 0;
      }
      else SendMessage(0, MSGID_QUIT, MSF_WAIT, NULL, 0);
   }
   else {
      CopyMemory(Buffer, glScriptBuffer + glScriptBufferLength, Size);
      glScriptBufferLength += Size;
      glScriptBuffer[glScriptBufferLength] = 0;
   }

   if (glScriptBuffer[glScriptBufferLength-1] IS 0x1a) { // Ctrl-Z
      glScriptBuffer[glScriptBufferLength-1] = 0;
      SendMessage(0, glScriptReceivedMsg, MSF_WAIT, NULL, 0);
      LogMsg("EOF received.");
      return;
   }
}

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

static ERROR msg_script_received(APTR Custom, LONG MsgID, LONG MsgType, APTR Message, LONG MsgSize)
{
   return ERR_Terminate;
}

//****************************************************************************
// Main entry point

int main(int argc, CSTRING *argv)
{
   const char *msg = init_parasol(argc, argv);
   if (msg) {
      int i;
      for (i=1; i < argc; i++) { // If in --verify mode, return with no error code and print nothing.
         if (!strcmp(argv[i], "--verify")) return 0;
      }
      print(msg);
      return -1;
   }

   if (!process_args()) {
      if (glTargetFile) {
         LONG type;
         if ((AnalysePath(glTargetFile, &type) != ERR_Okay) OR (type != LOC_FILE)) {
            print("File '%s' does not exist.", glTargetFile);
         }
         else exec_source(glTargetFile, glProcedure);
      }
      else {
         // Read script from std input

         glScriptReceivedMsg = AllocateID(IDTYPE_MESSAGE);

         FUNCTION callback;
         SET_FUNCTION_STDC(callback, (APTR)&msg_script_received);
         AddMsgHandler(NULL, glScriptReceivedMsg, &callback, NULL);

         SET_FUNCTION_STDC(callback, (APTR)&read_stdin);
         SetFunction(CurrentTask(), FID_InputCallback, &callback);

         ProcessMessages(0, -1);

         if (glScriptBuffer) {
            objScript *script;
            if (!NewObject(ID_FLUID, 0, &script)) {
               SetString(script, FID_Statement, glScriptBuffer);
               if (glProcedure) SetString(script, FID_Procedure, glProcedure);
               if (glArgs) set_script_args(script, glArgs);
               run_script(script);
               acFree(script);
            }
            else print("Internal Failure: Failed to create a new Script object for file processing.");
         }
      }
   }

   if (glScriptBuffer) { FreeMemory(glScriptBuffer); glScriptBuffer = NULL; }
   if (glProcedure)    { FreeMemory(glProcedure);    glProcedure = NULL; }
   if (glTargetFile)   { FreeMemory(glTargetFile);   glTargetFile = NULL; }

   close_parasol();

   return 0;
}
<|endoftext|>