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

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  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 "AddPythonTransformReaction.h"

#include "ActiveObjects.h"
#include "DataSource.h"
#include "OperatorPython.h"
#include "pqCoreUtilities.h"
#include "EditPythonOperatorDialog.h"

#include <vtkImageData.h>
#include <vtkSMSourceProxy.h>
#include <vtkTrivialProducer.h>

#include <QDialog>
#include <QLabel>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDialogButtonBox>

namespace tomviz
{
//-----------------------------------------------------------------------------
AddPythonTransformReaction::AddPythonTransformReaction(QAction* parentObject,
                                               const QString &l,
                                               const QString &s)
  : Superclass(parentObject), scriptLabel(l), scriptSource(s),
    interactive(false)
{
  connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
          SLOT(updateEnableState()));
  updateEnableState();
}

//-----------------------------------------------------------------------------
AddPythonTransformReaction::~AddPythonTransformReaction()
{
}

//-----------------------------------------------------------------------------
void AddPythonTransformReaction::updateEnableState()
{
  parentAction()->setEnabled(
        ActiveObjects::instance().activeDataSource() != NULL);
}

//-----------------------------------------------------------------------------
OperatorPython* AddPythonTransformReaction::addExpression(DataSource* source)
{
  source = source ? source : ActiveObjects::instance().activeDataSource();
  if (!source)
    {
    return NULL;
    }

  OperatorPython *opPython = new OperatorPython();
  QSharedPointer<Operator> op(opPython);
  opPython->setLabel(scriptLabel);
  opPython->setScript(scriptSource);

  // Shift uniformly, crop, both have custom gui
  if (scriptLabel == "Shift Uniformly")
    {
    vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(
      source->producer()->GetClientSideObject());
    vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));
    int *extent = data->GetExtent();

    QDialog dialog(pqCoreUtilities::mainWidget());
    QHBoxLayout *layout = new QHBoxLayout;
    QLabel *label = new QLabel("Shift to apply:");
    layout->addWidget(label);
    QSpinBox *spinx = new QSpinBox;
    spinx->setRange(-(extent[1]-extent[0]), extent[1]-extent[0]);
    spinx->setValue(0);
    QSpinBox *spiny = new QSpinBox;
    spiny->setRange(-(extent[3]-extent[2]), extent[3]-extent[2]);
    spiny->setValue(0);
    QSpinBox *spinz = new QSpinBox;
    spinz->setRange(-(extent[5]-extent[4]), extent[5]-extent[4]);
    spinz->setValue(0);
    layout->addWidget(spinx);
    layout->addWidget(spiny);
    layout->addWidget(spinz);
    QVBoxLayout *v = new QVBoxLayout;
    QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok
                                                     | QDialogButtonBox::Cancel);
    connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
    connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
    v->addLayout(layout);
    v->addWidget(buttons);
    dialog.setLayout(v);

    if (dialog.exec() == QDialog::Accepted)
      {
      QString shiftScript = scriptSource;
      shiftScript.replace("###SHIFT###",
                          QString("SHIFT = [%1, %2, %3]").arg(spinx->value())
                          .arg(spiny->value()).arg(spinz->value()));
      opPython->setScript(shiftScript);
      source->addOperator(op);
      }
    }
  else if (scriptLabel == "Crop")
    {
    vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(
      source->producer()->GetClientSideObject());
    vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));
    int *extent = data->GetExtent();

    QDialog dialog(pqCoreUtilities::mainWidget());
    QHBoxLayout *layout1 = new QHBoxLayout;
    QLabel *label = new QLabel("Crop data start:");
    layout1->addWidget(label);
    QSpinBox *spinx = new QSpinBox;
    spinx->setRange(extent[0], extent[1]);
    spinx->setValue(extent[0]);
    QSpinBox *spiny = new QSpinBox;
    spiny->setRange(extent[2], extent[3]);
    spiny->setValue(extent[2]);
    QSpinBox *spinz = new QSpinBox;
    spinz->setRange(extent[4], extent[5]);
    spinz->setValue(extent[4]);
    layout1->addWidget(label);
    layout1->addWidget(spinx);
    layout1->addWidget(spiny);
    layout1->addWidget(spinz);
    QHBoxLayout *layout2 = new QHBoxLayout;
    label = new QLabel("Crop data end:");
    layout2->addWidget(label);
    QSpinBox *spinxx = new QSpinBox;
    spinxx->setRange(extent[0], extent[1]);
    spinxx->setValue(extent[1]);
    QSpinBox *spinyy = new QSpinBox;
    spinyy->setRange(extent[2], extent[3]);
    spinyy->setValue(extent[3]);
    QSpinBox *spinzz = new QSpinBox;
    spinzz->setRange(extent[4], extent[5]);
    spinzz->setValue(extent[5]);
    layout2->addWidget(label);
    layout2->addWidget(spinxx);
    layout2->addWidget(spinyy);
    layout2->addWidget(spinzz);
    QVBoxLayout *v = new QVBoxLayout;
    QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok
                                                     | QDialogButtonBox::Cancel);
    connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
    connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
    v->addLayout(layout1);
    v->addLayout(layout2);
    v->addWidget(buttons);
    dialog.setLayout(v);

    if (dialog.exec() == QDialog::Accepted)
      {
      QString cropScript = scriptSource;
      cropScript.replace("###START_CROP###",
                          QString("START_CROP = [%1, %2, %3]").arg(spinx->value())
                          .arg(spiny->value()).arg(spinz->value()));
      cropScript.replace("###END_CROP###",
                          QString("END_CROP = [%1, %2, %3]").arg(spinxx->value())
                          .arg(spinyy->value()).arg(spinzz->value()));
      opPython->setScript(cropScript);
      source->addOperator(op);
      }
    }
  else if (scriptLabel == "Rotate")
  {
      QDialog dialog(pqCoreUtilities::mainWidget());
      QHBoxLayout *layout1 = new QHBoxLayout;
      QLabel *label = new QLabel("Rotate Angle:");
      layout1->addWidget(label);
      QDoubleSpinBox *angle = new QDoubleSpinBox;
      angle->setRange(0, 360);
      angle->setValue(90);
      layout1->addWidget(label);
      layout1->addWidget(angle);
      QHBoxLayout *layout2 = new QHBoxLayout;
      label = new QLabel("Rotate Axis:");
      layout2->addWidget(label);
      QSpinBox *axis = new QSpinBox;
      axis->setRange(0, 2);
      axis->setValue(2);
      layout2->addWidget(label);
      layout2->addWidget(axis);
      QVBoxLayout *v = new QVBoxLayout;
      QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok
                                                       | QDialogButtonBox::Cancel);
      connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
      connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
      v->addLayout(layout1);
      v->addLayout(layout2);
      v->addWidget(buttons);
      dialog.setLayout(v);

      if (dialog.exec() == QDialog::Accepted)
      {
          QString cropScript = scriptSource;
          cropScript.replace("###ROT_AXIS###",
                             QString("ROT_AXIS = %1").arg(axis->value()) );
          cropScript.replace("###ROT_ANGLE###",
                             QString("ROT_ANGLE = %1").arg(angle->value()) );
          opPython->setScript(cropScript);
          source->addOperator(op);
      }
  }
  else if (scriptLabel == "Sobel Filter") //UI for Sobel Filter
  {
      QDialog dialog(pqCoreUtilities::mainWidget());
      QHBoxLayout *layout = new QHBoxLayout;
      QLabel *label = new QLabel("Axis:");
      layout->addWidget(label);
      QSpinBox *axis = new QSpinBox;
      axis->setRange(0, 2);
      axis->setValue(0);
      layout->addWidget(label);
      layout->addWidget(axis);
      QVBoxLayout *v = new QVBoxLayout;
      QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok
                                                       | QDialogButtonBox::Cancel);
      connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
      connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
      v->addLayout(layout);
      v->addWidget(buttons);
      dialog.setLayout(v);

      if (dialog.exec() == QDialog::Accepted)
      {
          QString cropScript = scriptSource;
          cropScript.replace("###Filter_AXIS###",
                             QString("Filter_AXIS = %1").arg(axis->value()) );
          opPython->setScript(cropScript);
          source->addOperator(op);
      }
  }
  else if (interactive)
    {
    // Create a non-modal dialog, delete it once it has been closed.
    EditPythonOperatorDialog *dialog =
        new EditPythonOperatorDialog(op, pqCoreUtilities::mainWidget());
    dialog->setAttribute(Qt::WA_DeleteOnClose, true);
    connect(dialog, SIGNAL(accepted()), SLOT(addOperator()));
    dialog->show();
    }
  else
    {
    source->addOperator(op);
    }
  return NULL;
}

void AddPythonTransformReaction::addOperator()
{
  EditPythonOperatorDialog *dialog =
      qobject_cast<EditPythonOperatorDialog*>(sender());
  if (!dialog)
    return;
  DataSource *source = ActiveObjects::instance().activeDataSource();
  if (!source)
    {
    return;
    }
  source->addOperator(dialog->op());
}

}
<commit_msg>Changed axis selection to a QComboBox<commit_after>/******************************************************************************

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  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 "AddPythonTransformReaction.h"

#include "ActiveObjects.h"
#include "DataSource.h"
#include "OperatorPython.h"
#include "pqCoreUtilities.h"
#include "EditPythonOperatorDialog.h"

#include <vtkImageData.h>
#include <vtkSMSourceProxy.h>
#include <vtkTrivialProducer.h>

#include <QComboBox>
#include <QDialog>
#include <QLabel>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDialogButtonBox>

namespace tomviz
{
//-----------------------------------------------------------------------------
AddPythonTransformReaction::AddPythonTransformReaction(QAction* parentObject,
                                               const QString &l,
                                               const QString &s)
  : Superclass(parentObject), scriptLabel(l), scriptSource(s),
    interactive(false)
{
  connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
          SLOT(updateEnableState()));
  updateEnableState();
}

//-----------------------------------------------------------------------------
AddPythonTransformReaction::~AddPythonTransformReaction()
{
}

//-----------------------------------------------------------------------------
void AddPythonTransformReaction::updateEnableState()
{
  parentAction()->setEnabled(
        ActiveObjects::instance().activeDataSource() != NULL);
}

//-----------------------------------------------------------------------------
OperatorPython* AddPythonTransformReaction::addExpression(DataSource* source)
{
  source = source ? source : ActiveObjects::instance().activeDataSource();
  if (!source)
    {
    return NULL;
    }

  OperatorPython *opPython = new OperatorPython();
  QSharedPointer<Operator> op(opPython);
  opPython->setLabel(scriptLabel);
  opPython->setScript(scriptSource);

  // Shift uniformly, crop, both have custom gui
  if (scriptLabel == "Shift Uniformly")
    {
    vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(
      source->producer()->GetClientSideObject());
    vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));
    int *extent = data->GetExtent();

    QDialog dialog(pqCoreUtilities::mainWidget());
    QHBoxLayout *layout = new QHBoxLayout;
    QLabel *label = new QLabel("Shift to apply:");
    layout->addWidget(label);
    QSpinBox *spinx = new QSpinBox;
    spinx->setRange(-(extent[1]-extent[0]), extent[1]-extent[0]);
    spinx->setValue(0);
    QSpinBox *spiny = new QSpinBox;
    spiny->setRange(-(extent[3]-extent[2]), extent[3]-extent[2]);
    spiny->setValue(0);
    QSpinBox *spinz = new QSpinBox;
    spinz->setRange(-(extent[5]-extent[4]), extent[5]-extent[4]);
    spinz->setValue(0);
    layout->addWidget(spinx);
    layout->addWidget(spiny);
    layout->addWidget(spinz);
    QVBoxLayout *v = new QVBoxLayout;
    QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok
                                                     | QDialogButtonBox::Cancel);
    connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
    connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
    v->addLayout(layout);
    v->addWidget(buttons);
    dialog.setLayout(v);

    if (dialog.exec() == QDialog::Accepted)
      {
      QString shiftScript = scriptSource;
      shiftScript.replace("###SHIFT###",
                          QString("SHIFT = [%1, %2, %3]").arg(spinx->value())
                          .arg(spiny->value()).arg(spinz->value()));
      opPython->setScript(shiftScript);
      source->addOperator(op);
      }
    }
  else if (scriptLabel == "Crop")
    {
    vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(
      source->producer()->GetClientSideObject());
    vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));
    int *extent = data->GetExtent();

    QDialog dialog(pqCoreUtilities::mainWidget());
    QHBoxLayout *layout1 = new QHBoxLayout;
    QLabel *label = new QLabel("Crop data start:");
    layout1->addWidget(label);
    QSpinBox *spinx = new QSpinBox;
    spinx->setRange(extent[0], extent[1]);
    spinx->setValue(extent[0]);
    QSpinBox *spiny = new QSpinBox;
    spiny->setRange(extent[2], extent[3]);
    spiny->setValue(extent[2]);
    QSpinBox *spinz = new QSpinBox;
    spinz->setRange(extent[4], extent[5]);
    spinz->setValue(extent[4]);
    layout1->addWidget(label);
    layout1->addWidget(spinx);
    layout1->addWidget(spiny);
    layout1->addWidget(spinz);
    QHBoxLayout *layout2 = new QHBoxLayout;
    label = new QLabel("Crop data end:");
    layout2->addWidget(label);
    QSpinBox *spinxx = new QSpinBox;
    spinxx->setRange(extent[0], extent[1]);
    spinxx->setValue(extent[1]);
    QSpinBox *spinyy = new QSpinBox;
    spinyy->setRange(extent[2], extent[3]);
    spinyy->setValue(extent[3]);
    QSpinBox *spinzz = new QSpinBox;
    spinzz->setRange(extent[4], extent[5]);
    spinzz->setValue(extent[5]);
    layout2->addWidget(label);
    layout2->addWidget(spinxx);
    layout2->addWidget(spinyy);
    layout2->addWidget(spinzz);
    QVBoxLayout *v = new QVBoxLayout;
    QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok
                                                     | QDialogButtonBox::Cancel);
    connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
    connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
    v->addLayout(layout1);
    v->addLayout(layout2);
    v->addWidget(buttons);
    dialog.setLayout(v);

    if (dialog.exec() == QDialog::Accepted)
      {
      QString cropScript = scriptSource;
      cropScript.replace("###START_CROP###",
                          QString("START_CROP = [%1, %2, %3]").arg(spinx->value())
                          .arg(spiny->value()).arg(spinz->value()));
      cropScript.replace("###END_CROP###",
                          QString("END_CROP = [%1, %2, %3]").arg(spinxx->value())
                          .arg(spinyy->value()).arg(spinzz->value()));
      opPython->setScript(cropScript);
      source->addOperator(op);
      }
    }
  else if (scriptLabel == "Rotate")
  {
      QDialog dialog(pqCoreUtilities::mainWidget());
      QHBoxLayout *layout1 = new QHBoxLayout;
      QLabel *label = new QLabel("Rotate Angle:");
      layout1->addWidget(label);
      QDoubleSpinBox *angle = new QDoubleSpinBox;
      angle->setRange(0, 360);
      angle->setValue(90);
      layout1->addWidget(label);
      layout1->addWidget(angle);
      QHBoxLayout *layout2 = new QHBoxLayout;
      label = new QLabel("Rotate Axis:");
      layout2->addWidget(label);
      QComboBox *axis = new QComboBox(&dialog);
      axis->addItem("X");
      axis->addItem("Y");
      axis->addItem("Z");
      axis->setCurrentIndex(2);
      layout2->addWidget(label);
      layout2->addWidget(axis);
      QVBoxLayout *v = new QVBoxLayout;
      QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok
                                                       | QDialogButtonBox::Cancel);
      connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
      connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
      v->addLayout(layout1);
      v->addLayout(layout2);
      v->addWidget(buttons);
      dialog.setLayout(v);

      if (dialog.exec() == QDialog::Accepted)
      {
          QString cropScript = scriptSource;
          cropScript.replace("###ROT_AXIS###",
                             QString("ROT_AXIS = %1").arg(axis->currentIndex()) );
          cropScript.replace("###ROT_ANGLE###",
                             QString("ROT_ANGLE = %1").arg(angle->value()) );
          opPython->setScript(cropScript);
          source->addOperator(op);
      }
  }
  else if (scriptLabel == "Sobel Filter") //UI for Sobel Filter
  {
      QDialog dialog(pqCoreUtilities::mainWidget());
      QHBoxLayout *layout = new QHBoxLayout;
      QLabel *label = new QLabel("Axis:");
      layout->addWidget(label);
      QComboBox *axis = new QComboBox(&dialog);
      axis->addItem("X");
      axis->addItem("Y");
      axis->addItem("Z");
      axis->setCurrentIndex(2);
      layout->addWidget(label);
      layout->addWidget(axis);
      QVBoxLayout *v = new QVBoxLayout;
      QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok
                                                       | QDialogButtonBox::Cancel);
      connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
      connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
      v->addLayout(layout);
      v->addWidget(buttons);
      dialog.setLayout(v);

      if (dialog.exec() == QDialog::Accepted)
      {
          QString cropScript = scriptSource;
          cropScript.replace("###Filter_AXIS###",
                             QString("Filter_AXIS = %1").arg(axis->currentIndex()) );
          opPython->setScript(cropScript);
          source->addOperator(op);
      }
  }
  else if (interactive)
    {
    // Create a non-modal dialog, delete it once it has been closed.
    EditPythonOperatorDialog *dialog =
        new EditPythonOperatorDialog(op, pqCoreUtilities::mainWidget());
    dialog->setAttribute(Qt::WA_DeleteOnClose, true);
    connect(dialog, SIGNAL(accepted()), SLOT(addOperator()));
    dialog->show();
    }
  else
    {
    source->addOperator(op);
    }
  return NULL;
}

void AddPythonTransformReaction::addOperator()
{
  EditPythonOperatorDialog *dialog =
      qobject_cast<EditPythonOperatorDialog*>(sender());
  if (!dialog)
    return;
  DataSource *source = ActiveObjects::instance().activeDataSource();
  if (!source)
    {
    return;
    }
  source->addOperator(dialog->op());
}

}
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *                2019  Nina Engelhardt <nak@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct ScratchpadPass : public Pass {
	ScratchpadPass() : Pass("scratchpad", "get/set values in the scratchpad") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    scratchpad [options]\n");
		log("\n");
		log("This pass allows to read and modify values from the scratchpad of the current\n");
		log("design. Options:\n");
		log("\n");
		log("    -get <identifier>\n");
		log("        print the value saved in the scratchpad under the given identifier.\n");
		log("\n");
		log("    -set <identifier> <value>\n");
		log("        save the given value in the scratchpad under the given identifier.\n");
		log("\n");
		log("    -unset <identifier>\n");
		log("        remove the entry for the given identifier from the scratchpad.\n");
		log("\n");
		log("    -copy <identifier_from> <identifier_to>\n");
		log("        copy the value of the first identifier to the second identifier.\n");
		log("\n");
		log("    -assert <identifier> <value>\n");
		log("        assert that the entry for the given identifier is set to the given value.\n");
		log("\n");
		log("    -assert-set <identifier>\n");
		log("        assert that the entry for the given identifier exists.\n");
		log("\n");
		log("    -assert-unset <identifier>\n");
		log("        assert that the entry for the given identifier does not exist.\n");
		log("\n");
		log("The identifier may not contain whitespace. By convention, it is usually prefixed\n");
		log("by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\n");
		log("contains whitespace, it must be enclosed in double quotes.\n");
		log("\n");
	}

	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-get" && argidx+1 < args.size()) {
				string identifier = args[++argidx];
				if (design->scratchpad.count(identifier)){
					log("%s\n", design->scratchpad_get_string(identifier).c_str());
				} else {
					log("\"%s\" not set\n", identifier.c_str());
				}
				continue;
			}
			if (args[argidx] == "-set" && argidx+2 < args.size()) {
				string identifier = args[++argidx];
				string value = args[++argidx];
				if (value.front() == '\"' && value.back() == '\"') value = value.substr(1, value.size() - 2);
				design->scratchpad_set_string(identifier, value);
				continue;
			}
			if (args[argidx] == "-unset" && argidx+1 < args.size()) {
				string identifier = args[++argidx];
				design->scratchpad_unset(identifier);
				continue;
			}
			if (args[argidx] == "-copy" && argidx+2 < args.size()) {
				string identifier_from = args[++argidx];
				string identifier_to = args[++argidx];
				if (design->scratchpad.count(identifier_from) == 0) log_error("\"%s\" not set\n", identifier_from.c_str());
				string value = design->scratchpad_get_string(identifier_from);
				design->scratchpad_set_string(identifier_to, value);
				continue;
			}
			if (args[argidx] == "-assert" && argidx+2 < args.size()) {
				string identifier = args[++argidx];
				string expected = args[++argidx];
				if (expected.front() == '\"' && expected.back() == '\"') expected = expected.substr(1, expected.size() - 2);
				if (design->scratchpad.count(identifier) == 0)
					log_error("Assertion failed: scratchpad entry '%s' is not defined\n", identifier.c_str());
				string value = design->scratchpad_get_string(identifier);
				if (value != expected) {
					log_error("Assertion failed: scratchpad entry '%s' is set to '%s' instead of the asserted '%s'\n",
					           identifier.c_str(), value.c_str(), expected.c_str());
				}
				continue;
			}
			if (args[argidx] == "-assert-set" && argidx+1 < args.size()) {
				string identifier = args[++argidx];
				if (design->scratchpad.count(identifier) == 0)
					log_error("Assertion failed: scratchpad entry '%s' is not defined\n", identifier.c_str());
				continue;
			}
			if (args[argidx] == "-assert-unset" && argidx+1 < args.size()) {
				string identifier = args[++argidx];
				if (design->scratchpad.count(identifier) > 0)
					log_error("Assertion failed: scratchpad entry '%s' is defined\n", identifier.c_str());
				continue;
			}
			log("Unrecognized argument: %s\n", args[argidx].c_str());
			break;
		}
	}
} ScratchpadPass;
PRIVATE_NAMESPACE_END
<commit_msg>use extra_args<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *                2019  Nina Engelhardt <nak@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct ScratchpadPass : public Pass {
	ScratchpadPass() : Pass("scratchpad", "get/set values in the scratchpad") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    scratchpad [options]\n");
		log("\n");
		log("This pass allows to read and modify values from the scratchpad of the current\n");
		log("design. Options:\n");
		log("\n");
		log("    -get <identifier>\n");
		log("        print the value saved in the scratchpad under the given identifier.\n");
		log("\n");
		log("    -set <identifier> <value>\n");
		log("        save the given value in the scratchpad under the given identifier.\n");
		log("\n");
		log("    -unset <identifier>\n");
		log("        remove the entry for the given identifier from the scratchpad.\n");
		log("\n");
		log("    -copy <identifier_from> <identifier_to>\n");
		log("        copy the value of the first identifier to the second identifier.\n");
		log("\n");
		log("    -assert <identifier> <value>\n");
		log("        assert that the entry for the given identifier is set to the given value.\n");
		log("\n");
		log("    -assert-set <identifier>\n");
		log("        assert that the entry for the given identifier exists.\n");
		log("\n");
		log("    -assert-unset <identifier>\n");
		log("        assert that the entry for the given identifier does not exist.\n");
		log("\n");
		log("The identifier may not contain whitespace. By convention, it is usually prefixed\n");
		log("by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\n");
		log("contains whitespace, it must be enclosed in double quotes.\n");
		log("\n");
	}

	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-get" && argidx+1 < args.size()) {
				string identifier = args[++argidx];
				if (design->scratchpad.count(identifier)){
					log("%s\n", design->scratchpad_get_string(identifier).c_str());
				} else {
					log("\"%s\" not set\n", identifier.c_str());
				}
				continue;
			}
			if (args[argidx] == "-set" && argidx+2 < args.size()) {
				string identifier = args[++argidx];
				string value = args[++argidx];
				if (value.front() == '\"' && value.back() == '\"') value = value.substr(1, value.size() - 2);
				design->scratchpad_set_string(identifier, value);
				continue;
			}
			if (args[argidx] == "-unset" && argidx+1 < args.size()) {
				string identifier = args[++argidx];
				design->scratchpad_unset(identifier);
				continue;
			}
			if (args[argidx] == "-copy" && argidx+2 < args.size()) {
				string identifier_from = args[++argidx];
				string identifier_to = args[++argidx];
				if (design->scratchpad.count(identifier_from) == 0) log_error("\"%s\" not set\n", identifier_from.c_str());
				string value = design->scratchpad_get_string(identifier_from);
				design->scratchpad_set_string(identifier_to, value);
				continue;
			}
			if (args[argidx] == "-assert" && argidx+2 < args.size()) {
				string identifier = args[++argidx];
				string expected = args[++argidx];
				if (expected.front() == '\"' && expected.back() == '\"') expected = expected.substr(1, expected.size() - 2);
				if (design->scratchpad.count(identifier) == 0)
					log_error("Assertion failed: scratchpad entry '%s' is not defined\n", identifier.c_str());
				string value = design->scratchpad_get_string(identifier);
				if (value != expected) {
					log_error("Assertion failed: scratchpad entry '%s' is set to '%s' instead of the asserted '%s'\n",
					           identifier.c_str(), value.c_str(), expected.c_str());
				}
				continue;
			}
			if (args[argidx] == "-assert-set" && argidx+1 < args.size()) {
				string identifier = args[++argidx];
				if (design->scratchpad.count(identifier) == 0)
					log_error("Assertion failed: scratchpad entry '%s' is not defined\n", identifier.c_str());
				continue;
			}
			if (args[argidx] == "-assert-unset" && argidx+1 < args.size()) {
				string identifier = args[++argidx];
				if (design->scratchpad.count(identifier) > 0)
					log_error("Assertion failed: scratchpad entry '%s' is defined\n", identifier.c_str());
				continue;
			}
			break;
		}
		extra_args(args, argidx, design, false);
	}
} ScratchpadPass;
PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct Clk2fflogicPass : public Pass {
	Clk2fflogicPass() : Pass("clk2fflogic", "convert clocked FFs to generic $ff cells") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    clk2fflogic [options] [selection]\n");
		log("\n");
		log("This command replaces clocked flip-flops with generic $ff cells that use the\n");
		log("implicit global clock. This is useful for formal verification of designs with\n");
		log("multiple clocks.\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		// bool flag_noinit = false;

		log_header(design, "Executing CLK2FFLOGIC pass (convert clocked FFs to generic $ff cells).\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			// if (args[argidx] == "-noinit") {
			// 	flag_noinit = true;
			// 	continue;
			// }
			break;
		}
		extra_args(args, argidx, design);

		for (auto module : design->selected_modules())
		{
			SigMap sigmap(module);
			dict<SigBit, State> initbits;
			pool<SigBit> del_initbits;

			for (auto wire : module->wires())
				if (wire->attributes.count("\\init") > 0)
				{
					Const initval = wire->attributes.at("\\init");
					SigSpec initsig = sigmap(wire);

					for (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++)
						if (initval[i] == State::S0 || initval[i] == State::S1)
							initbits[initsig[i]] = initval[i];
				}

			for (auto cell : vector<Cell*>(module->selected_cells()))
			{
				if (cell->type.in("$dff", "$adff"))
				{
					bool clkpol = cell->parameters["\\CLK_POLARITY"].as_bool();

					SigSpec clk = cell->getPort("\\CLK");
					Wire *past_clk = module->addWire(NEW_ID);
					past_clk->attributes["\\init"] = clkpol ? State::S1 : State::S0;
					module->addFf(NEW_ID, clk, past_clk);

					SigSpec sig_d = cell->getPort("\\D");
					SigSpec sig_q = cell->getPort("\\Q");

					log("Replacing %s.%s (%s): CLK=%s, D=%s, Q=%s\n",
							log_id(module), log_id(cell), log_id(cell->type),
							log_signal(clk), log_signal(sig_d), log_signal(sig_q));

					SigSpec clock_edge_pattern;

					if (clkpol) {
						clock_edge_pattern.append_bit(State::S0);
						clock_edge_pattern.append_bit(State::S1);
					} else {
						clock_edge_pattern.append_bit(State::S1);
						clock_edge_pattern.append_bit(State::S0);
					}

					SigSpec clock_edge = module->Eqx(NEW_ID, {clk, SigSpec(past_clk)}, clock_edge_pattern);

					Wire *past_d = module->addWire(NEW_ID, GetSize(sig_d));
					Wire *past_q = module->addWire(NEW_ID, GetSize(sig_q));
					module->addFf(NEW_ID, sig_d, past_d);
					module->addFf(NEW_ID, sig_q, past_q);

					if (cell->type == "$adff")
					{
						SigSpec arst = cell->getPort("\\ARST");
						SigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge);
						Const rstval = cell->parameters["\\ARST_VALUE"];

						if (cell->parameters["\\ARST_POLARITY"].as_bool())
							module->addMux(NEW_ID, qval, rstval, arst, sig_q);
						else
							module->addMux(NEW_ID, rstval, qval, arst, sig_q);
					}
					else
					{
						module->addMux(NEW_ID, past_q, past_d, clock_edge, sig_q);
					}

					Const initval;
					bool assign_initval = false;
					for (int i = 0; i < GetSize(sig_d); i++) {
						SigBit qbit = sigmap(sig_q[i]);
						if (initbits.count(qbit)) {
							initval.bits.push_back(initbits.at(qbit));
							del_initbits.insert(qbit);
						} else
							initval.bits.push_back(State::Sx);
						if (initval.bits.back() != State::Sx)
							assign_initval = true;
					}

					if (assign_initval) {
						past_d->attributes["\\init"] = initval;
						past_q->attributes["\\init"] = initval;
					}

					module->remove(cell);
					continue;
				}
			}

			for (auto wire : module->wires())
				if (wire->attributes.count("\\init") > 0)
				{
					bool delete_initattr = true;
					Const initval = wire->attributes.at("\\init");
					SigSpec initsig = sigmap(wire);

					for (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++)
						if (del_initbits.count(initsig[i]) > 0)
							initval[i] = State::Sx;
						else if (initval[i] != State::Sx)
							delete_initattr = false;

					if (delete_initattr)
						wire->attributes.erase("\\init");
					else
						wire->attributes.at("\\init") = initval;
				}
		}

	}
} Clk2fflogicPass;

PRIVATE_NAMESPACE_END
<commit_msg>Added clk2fflogic support for $dffsr and $dlatch<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct Clk2fflogicPass : public Pass {
	Clk2fflogicPass() : Pass("clk2fflogic", "convert clocked FFs to generic $ff cells") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    clk2fflogic [options] [selection]\n");
		log("\n");
		log("This command replaces clocked flip-flops with generic $ff cells that use the\n");
		log("implicit global clock. This is useful for formal verification of designs with\n");
		log("multiple clocks.\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		// bool flag_noinit = false;

		log_header(design, "Executing CLK2FFLOGIC pass (convert clocked FFs to generic $ff cells).\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			// if (args[argidx] == "-noinit") {
			// 	flag_noinit = true;
			// 	continue;
			// }
			break;
		}
		extra_args(args, argidx, design);

		for (auto module : design->selected_modules())
		{
			SigMap sigmap(module);
			dict<SigBit, State> initbits;
			pool<SigBit> del_initbits;

			for (auto wire : module->wires())
				if (wire->attributes.count("\\init") > 0)
				{
					Const initval = wire->attributes.at("\\init");
					SigSpec initsig = sigmap(wire);

					for (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++)
						if (initval[i] == State::S0 || initval[i] == State::S1)
							initbits[initsig[i]] = initval[i];
				}

			for (auto cell : vector<Cell*>(module->selected_cells()))
			{
				if (cell->type.in("$dlatch"))
				{
					bool enpol = cell->parameters["\\EN_POLARITY"].as_bool();

					SigSpec sig_en = cell->getPort("\\EN");
					SigSpec sig_d = cell->getPort("\\D");
					SigSpec sig_q = cell->getPort("\\Q");

					log("Replacing %s.%s (%s): EN=%s, D=%s, Q=%s\n",
							log_id(module), log_id(cell), log_id(cell->type),
							log_signal(sig_en), log_signal(sig_d), log_signal(sig_q));

					Wire *past_q = module->addWire(NEW_ID, GetSize(sig_q));
					module->addFf(NEW_ID, sig_q, past_q);

					if (enpol)
						module->addMux(NEW_ID, past_q, sig_d, sig_en, sig_q);
					else
						module->addMux(NEW_ID, sig_d, past_q, sig_en, sig_q);

					Const initval;
					bool assign_initval = false;
					for (int i = 0; i < GetSize(sig_d); i++) {
						SigBit qbit = sigmap(sig_q[i]);
						if (initbits.count(qbit)) {
							initval.bits.push_back(initbits.at(qbit));
							del_initbits.insert(qbit);
						} else
							initval.bits.push_back(State::Sx);
						if (initval.bits.back() != State::Sx)
							assign_initval = true;
					}

					if (assign_initval)
						past_q->attributes["\\init"] = initval;

					module->remove(cell);
					continue;
				}

				if (cell->type.in("$dff", "$adff", "$dffsr"))
				{
					bool clkpol = cell->parameters["\\CLK_POLARITY"].as_bool();

					SigSpec clk = cell->getPort("\\CLK");
					Wire *past_clk = module->addWire(NEW_ID);
					past_clk->attributes["\\init"] = clkpol ? State::S1 : State::S0;
					module->addFf(NEW_ID, clk, past_clk);

					SigSpec sig_d = cell->getPort("\\D");
					SigSpec sig_q = cell->getPort("\\Q");

					log("Replacing %s.%s (%s): CLK=%s, D=%s, Q=%s\n",
							log_id(module), log_id(cell), log_id(cell->type),
							log_signal(clk), log_signal(sig_d), log_signal(sig_q));

					SigSpec clock_edge_pattern;

					if (clkpol) {
						clock_edge_pattern.append_bit(State::S0);
						clock_edge_pattern.append_bit(State::S1);
					} else {
						clock_edge_pattern.append_bit(State::S1);
						clock_edge_pattern.append_bit(State::S0);
					}

					SigSpec clock_edge = module->Eqx(NEW_ID, {clk, SigSpec(past_clk)}, clock_edge_pattern);

					Wire *past_d = module->addWire(NEW_ID, GetSize(sig_d));
					Wire *past_q = module->addWire(NEW_ID, GetSize(sig_q));
					module->addFf(NEW_ID, sig_d, past_d);
					module->addFf(NEW_ID, sig_q, past_q);

					if (cell->type == "$adff")
					{
						SigSpec arst = cell->getPort("\\ARST");
						SigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge);
						Const rstval = cell->parameters["\\ARST_VALUE"];

						if (cell->parameters["\\ARST_POLARITY"].as_bool())
							module->addMux(NEW_ID, qval, rstval, arst, sig_q);
						else
							module->addMux(NEW_ID, rstval, qval, arst, sig_q);
					}
					else
					if (cell->type == "$dffsr")
					{
						SigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge);
						SigSpec setval = cell->getPort("\\SET");
						SigSpec clrval = cell->getPort("\\CLR");

						if (!cell->parameters["\\SET_POLARITY"].as_bool())
							setval = module->Not(NEW_ID, setval);

						if (cell->parameters["\\CLR_POLARITY"].as_bool())
							clrval = module->Not(NEW_ID, clrval);

						qval = module->Or(NEW_ID, qval, setval);
						module->addAnd(NEW_ID, qval, clrval, sig_q);
					}
					else
					{
						module->addMux(NEW_ID, past_q, past_d, clock_edge, sig_q);
					}

					Const initval;
					bool assign_initval = false;
					for (int i = 0; i < GetSize(sig_d); i++) {
						SigBit qbit = sigmap(sig_q[i]);
						if (initbits.count(qbit)) {
							initval.bits.push_back(initbits.at(qbit));
							del_initbits.insert(qbit);
						} else
							initval.bits.push_back(State::Sx);
						if (initval.bits.back() != State::Sx)
							assign_initval = true;
					}

					if (assign_initval) {
						past_d->attributes["\\init"] = initval;
						past_q->attributes["\\init"] = initval;
					}

					module->remove(cell);
					continue;
				}
			}

			for (auto wire : module->wires())
				if (wire->attributes.count("\\init") > 0)
				{
					bool delete_initattr = true;
					Const initval = wire->attributes.at("\\init");
					SigSpec initsig = sigmap(wire);

					for (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++)
						if (del_initbits.count(initsig[i]) > 0)
							initval[i] = State::Sx;
						else if (initval[i] != State::Sx)
							delete_initattr = false;

					if (delete_initattr)
						wire->attributes.erase("\\init");
					else
						wire->attributes.at("\\init") = initval;
				}
		}

	}
} Clk2fflogicPass;

PRIVATE_NAMESPACE_END
<|endoftext|>


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

#ifndef _TOOLKIT_HELPER_MACROS_HXX_
#define _TOOLKIT_HELPER_MACROS_HXX_

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

#define IMPL_XUNOTUNNEL( ClassName ) \
sal_Int64 ClassName::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException) \
{ \
    if( ( rIdentifier.getLength() == 16 ) && ( 0 == rtl_compareMemory( ClassName::GetUnoTunnelId().getConstArray(), rIdentifier.getConstArray(), 16 ) ) ) \
    { \
        return (sal_Int64)this; \
    } \
    return 0; \
} \
const ::com::sun::star::uno::Sequence< sal_Int8 >& ClassName::GetUnoTunnelId() throw() \
{ \
    static ::com::sun::star::uno::Sequence< sal_Int8 > * pSeq = NULL; \
    if( !pSeq ) \
    { \
        ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \
        if( !pSeq ) \
        { \
            static ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( 16 ); \
            rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True ); \
            pSeq = &aSeq; \
        } \
    } \
    return *pSeq; \
} \
ClassName* ClassName::GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw() \
{ \
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xUT( rxIFace, ::com::sun::star::uno::UNO_QUERY ); \
    return xUT.is() ? (ClassName*)xUT->getSomething( ClassName::GetUnoTunnelId() ) : NULL; \
}

#define IMPL_XUNOTUNNEL2( ClassName, BaseClass ) \
sal_Int64 ClassName::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException) \
{ \
    if( ( rIdentifier.getLength() == 16 ) && ( 0 == rtl_compareMemory( ClassName::GetUnoTunnelId().getConstArray(), rIdentifier.getConstArray(), 16 ) ) ) \
    { \
        return (sal_Int64)this; \
    } \
    return BaseClass::getSomething( rIdentifier ); \
} \
const ::com::sun::star::uno::Sequence< sal_Int8 >& ClassName::GetUnoTunnelId() throw() \
{ \
    static ::com::sun::star::uno::Sequence< sal_Int8 > * pSeq = NULL; \
    if( !pSeq ) \
    { \
        ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \
        if( !pSeq ) \
        { \
            static ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( 16 ); \
            rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True ); \
            pSeq = &aSeq; \
        } \
    } \
    return *pSeq; \
} \
ClassName* ClassName::GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw() \
{ \
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xUT( rxIFace, ::com::sun::star::uno::UNO_QUERY ); \
    return xUT.is() ? (ClassName*)xUT->getSomething( ClassName::GetUnoTunnelId() ) : NULL; \
}

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

#define IMPL_IMPLEMENTATION_ID( ClassName ) \
::com::sun::star::uno::Sequence< sal_Int8 > ClassName::getImplementationId() throw(::com::sun::star::uno::RuntimeException) \
{ \
    static ::cppu::OImplementationId* pId = NULL; \
    if( !pId ) \
    { \
        ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \
        if( ! pId ) \
        { \
            static ::cppu::OImplementationId id( sal_False ); \
            pId = &id; \
        } \
    } \
    return (*pId).getImplementationId(); \
}

#define IMPL_XTYPEPROVIDER_START( ClassName )   \
IMPL_IMPLEMENTATION_ID( ClassName ) \
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > ClassName::getTypes() throw(::com::sun::star::uno::RuntimeException) \
{ \
    static ::cppu::OTypeCollection* pCollection = NULL; \
    if( !pCollection ) \
    { \
        ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \
        if( !pCollection ) \
        { \
            static ::cppu::OTypeCollection collection( \
            getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider>* ) NULL ),

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

#define IMPL_XTYPEPROVIDER_END \
            ); \
            pCollection = &collection; \
        } \
    } \
    return (*pCollection).getTypes(); \
}

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

#define DECL_LISTENERMULTIPLEXER_START( ClassName, InterfaceName ) \
class ClassName : public ListenerMultiplexerBase, public InterfaceName \
{ \
public: \
    ClassName( ::cppu::OWeakObject& rSource ); \
    ::com::sun::star::uno::Any  SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); \
    void                        SAL_CALL acquire() throw()  { ListenerMultiplexerBase::acquire(); } \
    void                        SAL_CALL release() throw()  { ListenerMultiplexerBase::release(); } \
    void                        SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

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

#define DECL_LISTENERMULTIPLEXER_END \
};

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

#define IMPL_LISTENERMULTIPLEXER_BASEMETHODS( ClassName, InterfaceName ) \
ClassName::ClassName( ::cppu::OWeakObject& rSource ) \
    : ListenerMultiplexerBase( rSource ) \
{ \
} \
::com::sun::star::uno::Any ClassName::queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) \
{ \
    ::com::sun::star::uno::Any aRet = ::cppu::queryInterface( rType, \
                                        SAL_STATIC_CAST( ::com::sun::star::lang::XEventListener*, this ), \
                                        SAL_STATIC_CAST( InterfaceName*, this ) ); \
    return (aRet.hasValue() ? aRet : ListenerMultiplexerBase::queryInterface( rType )); \
} \
void ClassName::disposing( const ::com::sun::star::lang::EventObject& ) throw(::com::sun::star::uno::RuntimeException) \
{ \
}

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

#define IMPL_LISTENERMULTIPLEXER_LISTENERMETHOD( ClassName, InterfaceName, MethodName, EventType ) \
void ClassName::MethodName( const EventType& e ) throw(::com::sun::star::uno::RuntimeException) \
{ \
    EventType aMulti( e ); \
    aMulti.Source = &GetContext(); \
    ::cppu::OInterfaceIteratorHelper aIt( *this ); \
    while( aIt.hasMoreElements() ) \
        ((InterfaceName*)aIt.next())->MethodName( aMulti ); \
}

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

#define DECLIMPL_SUPPORTS_SERVICE( ) \
    sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw(::com::sun::star::uno::RuntimeException) \
    { \
        ::com::sun::star::uno::Sequence< ::rtl::OUString > aServiceNames( getSupportedServiceNames() ); \
        const ::rtl::OUString* pSupported = aServiceNames.getConstArray(); \
        const ::rtl::OUString* pSupportedEnd = pSupported + aServiceNames.getLength(); \
        for ( ; pSupported != pSupportedEnd; ++pSupported ) \
            if ( *pSupported == rServiceName ) \
                return sal_True; \
        return sal_False; \
    }

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

#define DECLIMPL_SERVICEINFO_DERIVED( ImplName, BaseClass, ServiceName ) \
    ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii( "stardiv.Toolkit." #ImplName ); } \
    ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)   \
                            { \
                                ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = BaseClass::getSupportedServiceNames( ); \
                                aNames.realloc( aNames.getLength() + 1 ); \
                                aNames[ aNames.getLength() - 1 ] = ::rtl::OUString::createFromAscii( ServiceName ); \
                                return aNames; \
                            } \

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

#define DECLIMPL_SERVICEINFO( ImplName, ServiceName ) \
    ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii( "stardiv.Toolkit." #ImplName ); } \
    ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)   \
                            { \
                                ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames( 1 ); \
                                aNames[ 0 ] = ::rtl::OUString::createFromAscii( ServiceName ); \
                                return aNames; \
                            } \
    DECLIMPL_SUPPORTS_SERVICE( )

#endif // _TOOLKIT_HELPER_MACROS_HXX_

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

#ifndef _TOOLKIT_HELPER_MACROS_HXX_
#define _TOOLKIT_HELPER_MACROS_HXX_

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

#define IMPL_XUNOTUNNEL( ClassName ) \
sal_Int64 ClassName::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException) \
{ \
    if( ( rIdentifier.getLength() == 16 ) && ( 0 == rtl_compareMemory( ClassName::GetUnoTunnelId().getConstArray(), rIdentifier.getConstArray(), 16 ) ) ) \
    { \
        return (sal_Int64)this; \
    } \
    return 0; \
} \
const ::com::sun::star::uno::Sequence< sal_Int8 >& ClassName::GetUnoTunnelId() throw() \
{ \
    static ::com::sun::star::uno::Sequence< sal_Int8 > * pSeq = NULL; \
    if( !pSeq ) \
    { \
        ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \
        if( !pSeq ) \
        { \
            static ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( 16 ); \
            rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True ); \
            pSeq = &aSeq; \
        } \
    } \
    return *pSeq; \
} \
ClassName* ClassName::GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw() \
{ \
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xUT( rxIFace, ::com::sun::star::uno::UNO_QUERY ); \
    return xUT.is() ? (ClassName*)xUT->getSomething( ClassName::GetUnoTunnelId() ) : NULL; \
}

#define IMPL_XUNOTUNNEL2( ClassName, BaseClass ) \
sal_Int64 ClassName::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException) \
{ \
    if( ( rIdentifier.getLength() == 16 ) && ( 0 == rtl_compareMemory( ClassName::GetUnoTunnelId().getConstArray(), rIdentifier.getConstArray(), 16 ) ) ) \
    { \
        return (sal_Int64)this; \
    } \
    return BaseClass::getSomething( rIdentifier ); \
} \
const ::com::sun::star::uno::Sequence< sal_Int8 >& ClassName::GetUnoTunnelId() throw() \
{ \
    static ::com::sun::star::uno::Sequence< sal_Int8 > * pSeq = NULL; \
    if( !pSeq ) \
    { \
        ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \
        if( !pSeq ) \
        { \
            static ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( 16 ); \
            rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True ); \
            pSeq = &aSeq; \
        } \
    } \
    return *pSeq; \
} \
ClassName* ClassName::GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw() \
{ \
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xUT( rxIFace, ::com::sun::star::uno::UNO_QUERY ); \
    return xUT.is() ? (ClassName*)xUT->getSomething( ClassName::GetUnoTunnelId() ) : NULL; \
}

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

#define IMPL_IMPLEMENTATION_ID( ClassName ) \
::com::sun::star::uno::Sequence< sal_Int8 > ClassName::getImplementationId() throw(::com::sun::star::uno::RuntimeException) \
{ \
    static ::cppu::OImplementationId* pId = NULL; \
    if( !pId ) \
    { \
        ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \
        if( ! pId ) \
        { \
            static ::cppu::OImplementationId id( sal_False ); \
            pId = &id; \
        } \
    } \
    return (*pId).getImplementationId(); \
}

#define IMPL_XTYPEPROVIDER_START( ClassName )   \
IMPL_IMPLEMENTATION_ID( ClassName ) \
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > ClassName::getTypes() throw(::com::sun::star::uno::RuntimeException) \
{ \
    static ::cppu::OTypeCollection* pCollection = NULL; \
    if( !pCollection ) \
    { \
        ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \
        if( !pCollection ) \
        { \
            static ::cppu::OTypeCollection collection( \
            getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider>* ) NULL ),

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

#define IMPL_XTYPEPROVIDER_END \
            ); \
            pCollection = &collection; \
        } \
    } \
    return (*pCollection).getTypes(); \
}

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

#define DECL_LISTENERMULTIPLEXER_START( ClassName, InterfaceName ) \
class ClassName : public ListenerMultiplexerBase, public InterfaceName \
{ \
public: \
    ClassName( ::cppu::OWeakObject& rSource ); \
    ::com::sun::star::uno::Any  SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); \
    void                        SAL_CALL acquire() throw()  { ListenerMultiplexerBase::acquire(); } \
    void                        SAL_CALL release() throw()  { ListenerMultiplexerBase::release(); } \
    void                        SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

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

#define DECL_LISTENERMULTIPLEXER_END \
};

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

#define IMPL_LISTENERMULTIPLEXER_BASEMETHODS( ClassName, InterfaceName ) \
ClassName::ClassName( ::cppu::OWeakObject& rSource ) \
    : ListenerMultiplexerBase( rSource ) \
{ \
} \
::com::sun::star::uno::Any ClassName::queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) \
{ \
    ::com::sun::star::uno::Any aRet = ::cppu::queryInterface( rType, \
                                        SAL_STATIC_CAST( ::com::sun::star::lang::XEventListener*, this ), \
                                        SAL_STATIC_CAST( InterfaceName*, this ) ); \
    return (aRet.hasValue() ? aRet : ListenerMultiplexerBase::queryInterface( rType )); \
} \
void ClassName::disposing( const ::com::sun::star::lang::EventObject& ) throw(::com::sun::star::uno::RuntimeException) \
{ \
}

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

#define IMPL_LISTENERMULTIPLEXER_LISTENERMETHOD( ClassName, InterfaceName, MethodName, EventType ) \
void ClassName::MethodName( const EventType& e ) throw(::com::sun::star::uno::RuntimeException) \
{ \
    EventType aMulti( e ); \
    aMulti.Source = &GetContext(); \
    ::cppu::OInterfaceIteratorHelper aIt( *this ); \
    while( aIt.hasMoreElements() ) \
    { \
        ::com::sun::star::uno::Reference< InterfaceName > xListener( \
            static_cast< InterfaceName* >( aIt.next() ) ); \
        try \
        { \
            xListener->MethodName( aMulti ); \
        } \
        catch( ::com::sun::star::lang::DisposedException e ) \
        { \
            OSL_ENSURE( e.Context.is(), "caught DisposedException with empty Context field" ); \
            if ( e.Context == xListener || !e.Context.is() ) \
                aIt.remove(); \
        } \
    } \
}

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

#define DECLIMPL_SUPPORTS_SERVICE( ) \
    sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw(::com::sun::star::uno::RuntimeException) \
    { \
        ::com::sun::star::uno::Sequence< ::rtl::OUString > aServiceNames( getSupportedServiceNames() ); \
        const ::rtl::OUString* pSupported = aServiceNames.getConstArray(); \
        const ::rtl::OUString* pSupportedEnd = pSupported + aServiceNames.getLength(); \
        for ( ; pSupported != pSupportedEnd; ++pSupported ) \
            if ( *pSupported == rServiceName ) \
                return sal_True; \
        return sal_False; \
    }

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

#define DECLIMPL_SERVICEINFO_DERIVED( ImplName, BaseClass, ServiceName ) \
    ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii( "stardiv.Toolkit." #ImplName ); } \
    ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)   \
                            { \
                                ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = BaseClass::getSupportedServiceNames( ); \
                                aNames.realloc( aNames.getLength() + 1 ); \
                                aNames[ aNames.getLength() - 1 ] = ::rtl::OUString::createFromAscii( ServiceName ); \
                                return aNames; \
                            } \

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

#define DECLIMPL_SERVICEINFO( ImplName, ServiceName ) \
    ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii( "stardiv.Toolkit." #ImplName ); } \
    ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)   \
                            { \
                                ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames( 1 ); \
                                aNames[ 0 ] = ::rtl::OUString::createFromAscii( ServiceName ); \
                                return aNames; \
                            } \
    DECLIMPL_SUPPORTS_SERVICE( )

#endif // _TOOLKIT_HELPER_MACROS_HXX_

<|endoftext|>


<commit_before>/*************************************************/
/* class_drc_item.cpp - DRC_ITEM class functions */
/*************************************************/
#include "fctsys.h"
#include "common.h"

#include "pcbnew.h"

wxString DRC_ITEM::GetErrorText() const
{
    switch( m_ErrorCode )
    {
//    case DRCE_:    not assigned yet

    case DRCE_UNCONNECTED_PADS:
        return wxString( _("Unconnected pads") );
    case DRCE_TRACK_NEAR_THROUGH_HOLE:
        return wxString( _("Track near thru-hole") );
    case DRCE_TRACK_NEAR_PAD:
        return wxString( _("Track near pad") );
    case DRCE_TRACK_NEAR_VIA:
        return wxString( _("Track near via") );
    case DRCE_VIA_NEAR_VIA:
        return wxString( _("Via near via") );
    case DRCE_VIA_NEAR_TRACK:
        return wxString( _("Via near track") );
    case DRCE_TRACK_ENDS1:
    case DRCE_TRACK_ENDS2:
    case DRCE_TRACK_ENDS3:
    case DRCE_TRACK_ENDS4:
    case DRCE_ENDS_PROBLEM1:
    case DRCE_ENDS_PROBLEM2:
    case DRCE_ENDS_PROBLEM3:
    case DRCE_ENDS_PROBLEM4:
    case DRCE_ENDS_PROBLEM5:
        return wxString( _("Two track ends") );
    case DRCE_TRACK_UNKNOWN1:
        return wxString( _("This looks bad") );  ///< @todo check source code and change this comment
    case DRCE_TRACKS_CROSSING:
        return wxString( _("Tracks crossing") );
    case DRCE_PAD_NEAR_PAD1:
        return wxString( _("Pad near pad") );
    case DRCE_VIA_HOLE_BIGGER:
        return wxString( _("Via hole > diameter"));

    default:
        return wxString( wxT("PROGRAM BUG, PLEASE LEAVE THE ROOM.") );
    }
}

wxString DRC_ITEM::ShowCoord( const wxPoint& aPos )
{
    wxString temp;
    wxString ret;

    ret << wxT("@(") << valeur_param( aPos.x, temp );
    ret << wxT(",")  << valeur_param( aPos.y, temp );
    ret << wxT(")");

    return ret;
}

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

/*************************************************/
/* class_drc_item.cpp - DRC_ITEM class functions */
/*************************************************/
#include "fctsys.h"
#include "common.h"

#include "pcbnew.h"

wxString DRC_ITEM::GetErrorText() const
{
    switch( m_ErrorCode )
    {
    case DRCE_UNCONNECTED_PADS:
        return wxString( _("Unconnected pads") );
    case DRCE_TRACK_NEAR_THROUGH_HOLE:
        return wxString( _("Track near thru-hole") );
    case DRCE_TRACK_NEAR_PAD:
        return wxString( _("Track near pad") );
    case DRCE_TRACK_NEAR_VIA:
        return wxString( _("Track near via") );
    case DRCE_VIA_NEAR_VIA:
        return wxString( _("Via near via") );
    case DRCE_VIA_NEAR_TRACK:
        return wxString( _("Via near track") );
    case DRCE_TRACK_ENDS1:
    case DRCE_TRACK_ENDS2:
    case DRCE_TRACK_ENDS3:
    case DRCE_TRACK_ENDS4:
    case DRCE_ENDS_PROBLEM1:
    case DRCE_ENDS_PROBLEM2:
    case DRCE_ENDS_PROBLEM3:
    case DRCE_ENDS_PROBLEM4:
    case DRCE_ENDS_PROBLEM5:
        return wxString( _("Two track ends") );
    case DRCE_TRACK_UNKNOWN1:
        return wxString( _("This looks bad") );  ///< @todo check source code and change this comment
    case DRCE_TRACKS_CROSSING:
        return wxString( _("Tracks crossing") );
    case DRCE_PAD_NEAR_PAD1:
        return wxString( _("Pad near pad") );
    case DRCE_VIA_HOLE_BIGGER:
        return wxString( _("Via hole > diameter"));

    default:
        return wxString( wxT("PROGRAM BUG, PLEASE LEAVE THE ROOM.") );
    }
}

wxString DRC_ITEM::ShowCoord( const wxPoint& aPos )
{
    wxString temp;
    wxString ret;

    ret << wxT("@(") << valeur_param( aPos.x, temp );
    ret << wxT(",")  << valeur_param( aPos.y, temp );
    ret << wxT(")");

    return ret;
}

<|endoftext|>


<commit_before>#include "MifareClassic.h"
#include "Ndef.h"
#include <Adafruit_NFCShield_I2C.h>

#define BLOCK_SIZE 16

NdefMessage readMifareClassic(Adafruit_NFCShield_I2C& nfc, uint8_t * uid, int uidLength)
{
    uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 };
    int currentBlock = 4;
    int messageLength = 0;
    byte data[16];

    // read first block to get message length
    int success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
    if (success)
    {
      success = nfc.mifareclassic_ReadDataBlock(currentBlock, data);
      if (success)
      {
        messageLength = getNdefLength(data);
      }
      else
      {
        Serial.print("Error. Failed read block ");Serial.println(currentBlock);
      }
    }
    else
    {
      Serial.print("Error. Block Authentication failed for ");Serial.println(currentBlock);
    }

    // this should be nested in the message length loop
    int index = 0;
    int bufferSize = getBufferSize(messageLength);
    uint8_t buffer[bufferSize];

    Serial.print("Message Length ");Serial.println(messageLength);
    Serial.print("Buffer Size ");Serial.println(bufferSize);

    while (index < bufferSize)
    {
      // authenticate on every sector
      if (nfc.mifareclassic_IsFirstBlock(currentBlock))
      {
        success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
        if (!success)
        {
          Serial.print("Error. Block Authentication failed for ");Serial.println(currentBlock);
        }
      }

      // read the data
      success = nfc.mifareclassic_ReadDataBlock(currentBlock, &buffer[index]);
      if (success)
      {
        Serial.print("Read block ");Serial.println(currentBlock);
        // Serial.print("Block ");Serial.print(currentBlock);Serial.print(" ");
        // nfc.PrintHexChar(&buffer[index], BLOCK_SIZE);
      }
      else
      {
        Serial.print("Read failed ");Serial.println(currentBlock);
      }

      index += BLOCK_SIZE;
      currentBlock++;

      // skip the trailer block
      if (nfc.mifareclassic_IsTrailerBlock(currentBlock))
      {
        Serial.print("Skipping block ");Serial.println(currentBlock);
        currentBlock++;
      }

    }

    // print out for debugging (this would be easier block by block)
    Serial.println("\nRaw NDEF data");
    uint8_t* buffer_ptr = &buffer[0];
    int j = 0;
    for (j = 0; j < (bufferSize / BLOCK_SIZE); j++)
    {
        nfc.PrintHexChar(buffer_ptr, BLOCK_SIZE);
        buffer_ptr += BLOCK_SIZE;
    }
    Serial.println();

    nfc.PrintHex(&buffer[4], messageLength);

    NdefMessage ndefMessage = NdefMessage(&buffer[4], messageLength);
    return ndefMessage;
}

int getBufferSize(int messageLength)
{

  // TLV header is 4 bytes. TLV terminator is 1 byte.
  int bufferSize = messageLength + 5;

  // bufferSize needs to be a multiple of BLOCK_SIZE
  if (bufferSize % BLOCK_SIZE != 0)
  {
      bufferSize = ((messageLength / BLOCK_SIZE) + 1) * BLOCK_SIZE;
  }

  return bufferSize;
}

// get the ndef data length from the mifare TLV
// assuming the type and the length are in the first 4 bytes
// { 0x0, 0x0, 0x3, LENGTH }
// { 0x3, 0xFF, LENGTH, LENGTH }
int getNdefLength(byte *data)
{
    int ndefLength;
    if (data[0] == 0x03 && data[1] == 0xFF) {
        // would rather find spec, but using
        // http://www.developer.nokia.com/Community/Discussion/showthread.php?131601-Problem-decoding-NDEF-message-on-Mifare-Card&p=407235&viewfull=1#post407235
        ndefLength = ((0xFF & data[2]) << 8) | (0xFF & data[3]);
    } else if (data[2] == 0x03) { // 1 byte
        ndefLength = data[3];
    } else {
        Serial.println("ERROR: Do not know how to decode length.");
        ndefLength = -1;
    }

    return ndefLength;
}

// TODO return success / failure
void writeMifareClassic(Adafruit_NFCShield_I2C& nfc, NdefMessage& m, uint8_t * uid, int uidLength)
{

    uint8_t encoded[m.getEncodedSize()];
    m.encode(encoded);

    uint8_t buffer[getBufferSize(sizeof(encoded))];
    memset(buffer, 0, sizeof(buffer));
    buffer[0] = 0x0;
    buffer[1] = 0x0;
    buffer[2] = 0x3;
    buffer[3] = sizeof(encoded);
    memcpy(&buffer[4], encoded, sizeof(encoded));
    buffer[4+sizeof(encoded)] = 0xFE; // terminator

    // Write to tag
    int index = 0;
    int currentBlock = 4;
    uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; // this is Sector 1 - 15 key

    while (index < sizeof(buffer))
    {

      if (nfc.mifareclassic_IsFirstBlock(currentBlock))
      {
        int success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
        if (!success)
        {
          Serial.print("Error. Block Authentication failed for ");Serial.println(currentBlock);
          while (1); // halt
        }
      }

      int write_success = nfc.mifareclassic_WriteDataBlock (currentBlock, &buffer[index]);
      if (write_success)
      {
        Serial.print(F("Wrote block "));Serial.print(currentBlock);Serial.print(" - ");
        nfc.PrintHexChar(&buffer[index], BLOCK_SIZE);
      }
      else
      {
        Serial.print(F("Write failed "));Serial.println(currentBlock);
        while (1); // halt
      }
      index += BLOCK_SIZE;
      currentBlock++;

      if (nfc.mifareclassic_IsTrailerBlock(currentBlock))
      {
        // can't write to trailer block
        Serial.print(F("Skipping block "));Serial.println(currentBlock);
        currentBlock++;
      }

    }
  }<commit_msg>Fix buffer size calculation<commit_after>#include "MifareClassic.h"
#include "Ndef.h"
#include <Adafruit_NFCShield_I2C.h>

#define BLOCK_SIZE 16

NdefMessage readMifareClassic(Adafruit_NFCShield_I2C& nfc, uint8_t * uid, int uidLength)
{
    uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 };
    int currentBlock = 4;
    int messageLength = 0;
    byte data[16];

    // read first block to get message length
    int success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
    if (success)
    {
      success = nfc.mifareclassic_ReadDataBlock(currentBlock, data);
      if (success)
      {
        messageLength = getNdefLength(data);
      }
      else
      {
        Serial.print("Error. Failed read block ");Serial.println(currentBlock);
      }
    }
    else
    {
      Serial.print("Error. Block Authentication failed for ");Serial.println(currentBlock);
    }

    // this should be nested in the message length loop
    int index = 0;
    int bufferSize = getBufferSize(messageLength);
    uint8_t buffer[bufferSize];

    Serial.print("Message Length ");Serial.println(messageLength);
    Serial.print("Buffer Size ");Serial.println(bufferSize);

    while (index < bufferSize)
    {
      // authenticate on every sector
      if (nfc.mifareclassic_IsFirstBlock(currentBlock))
      {
        success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
        if (!success)
        {
          Serial.print("Error. Block Authentication failed for ");Serial.println(currentBlock);
        }
      }

      // read the data
      success = nfc.mifareclassic_ReadDataBlock(currentBlock, &buffer[index]);
      if (success)
      {
        Serial.print("Read block ");Serial.println(currentBlock);
        // Serial.print("Block ");Serial.print(currentBlock);Serial.print(" ");
        // nfc.PrintHexChar(&buffer[index], BLOCK_SIZE);
      }
      else
      {
        Serial.print("Read failed ");Serial.println(currentBlock);
      }

      index += BLOCK_SIZE;
      currentBlock++;

      // skip the trailer block
      if (nfc.mifareclassic_IsTrailerBlock(currentBlock))
      {
        Serial.print("Skipping block ");Serial.println(currentBlock);
        currentBlock++;
      }

    }

    // print out for debugging (this would be easier block by block)
    Serial.println("\nRaw NDEF data");
    uint8_t* buffer_ptr = &buffer[0];
    int j = 0;
    for (j = 0; j < (bufferSize / BLOCK_SIZE); j++)
    {
        nfc.PrintHexChar(buffer_ptr, BLOCK_SIZE);
        buffer_ptr += BLOCK_SIZE;
    }
    Serial.println();

    nfc.PrintHex(&buffer[4], messageLength);

    NdefMessage ndefMessage = NdefMessage(&buffer[4], messageLength);
    return ndefMessage;
}

int getBufferSize(int messageLength)
{

  // TLV header is 4 bytes. TLV terminator is 1 byte.
  int bufferSize = messageLength + 5;

  // bufferSize needs to be a multiple of BLOCK_SIZE
  if (bufferSize % BLOCK_SIZE != 0)
  {
    bufferSize = ((bufferSize / BLOCK_SIZE) + 1) * BLOCK_SIZE;
  }

  return bufferSize;
}

// get the ndef data length from the mifare TLV
// assuming the type and the length are in the first 4 bytes
// { 0x0, 0x0, 0x3, LENGTH }
// { 0x3, 0xFF, LENGTH, LENGTH }
int getNdefLength(byte *data)
{
    int ndefLength;
    if (data[0] == 0x03 && data[1] == 0xFF) {
        // would rather find spec, but using
        // http://www.developer.nokia.com/Community/Discussion/showthread.php?131601-Problem-decoding-NDEF-message-on-Mifare-Card&p=407235&viewfull=1#post407235
        ndefLength = ((0xFF & data[2]) << 8) | (0xFF & data[3]);
    } else if (data[2] == 0x03) { // 1 byte
        ndefLength = data[3];
    } else {
        Serial.println("ERROR: Do not know how to decode length.");
        ndefLength = -1;
    }

    return ndefLength;
}

// TODO return success / failure
void writeMifareClassic(Adafruit_NFCShield_I2C& nfc, NdefMessage& m, uint8_t * uid, int uidLength)
{

    uint8_t encoded[m.getEncodedSize()];
    m.encode(encoded);

    uint8_t buffer[getBufferSize(sizeof(encoded))];
    memset(buffer, 0, sizeof(buffer));

    Serial.print("sizeof(encoded) ");Serial.println(sizeof(encoded));
    Serial.print("sizeof(buffer) ");Serial.println(sizeof(buffer));

    buffer[0] = 0x0;
    buffer[1] = 0x0;
    buffer[2] = 0x3;
    buffer[3] = sizeof(encoded);
    memcpy(&buffer[4], encoded, sizeof(encoded));
    buffer[4+sizeof(encoded)] = 0xFE; // terminator

    // Write to tag
    int index = 0;
    int currentBlock = 4;
    uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; // this is Sector 1 - 15 key

    while (index < sizeof(buffer))
    {

      if (nfc.mifareclassic_IsFirstBlock(currentBlock))
      {
        int success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
        if (!success)
        {
          Serial.print("Error. Block Authentication failed for ");Serial.println(currentBlock);
          while (1); // halt
        }
      }

      int write_success = nfc.mifareclassic_WriteDataBlock (currentBlock, &buffer[index]);
      if (write_success)
      {
        Serial.print(F("Wrote block "));Serial.print(currentBlock);Serial.print(" - ");
        nfc.PrintHexChar(&buffer[index], BLOCK_SIZE);
      }
      else
      {
        Serial.print(F("Write failed "));Serial.println(currentBlock);
        while (1); // halt
      }
      index += BLOCK_SIZE;
      currentBlock++;

      if (nfc.mifareclassic_IsTrailerBlock(currentBlock))
      {
        // can't write to trailer block
        Serial.print(F("Skipping block "));Serial.println(currentBlock);
        currentBlock++;
      }

    }
  }<|endoftext|>


<commit_before>#include <stdio.h>
#include <fstream>
#include "Input.h"
#include "ValType.h"
#include <stdexcept>
#include <sstream>
//MR CHANGE
#include <cstdlib>
//MR CHANGE END

// return a given key value (if it's in the map)
ValType phSolver::Input::GetValue(const string &str) const
{
  if (input_map->find(str) != input_map->end()) {
    if ( (*input_map)[str] == "NODEFAULT" ) {
      stringstream ost;
      ost << "required input variable not set: " << str << ends;
      throw invalid_argument( ost.str() );
    }
  } else {
    stringstream ost;
    ost << "required input variable not set: " << str << ends;
    throw invalid_argument( ost.str() );
  }

  return ValType( (*input_map)[str] );
}

const char* phSolver::Input::GetUserFileName() {
  return userConfFileName.c_str();
}

const char* phSolver::Input::GetDefaultFileName() {
  return defaultConfFileName.c_str();
}

phSolver::Input::Input(const string &fname, const string &default_fname)
  : userConfFileName(fname), defaultConfFileName(default_fname)
{
  // open the input file
  ifstream infile( fname.c_str(), ios::in);

  if(!infile || infile.eof()){
    cerr<<" Input file does not exist or is empty or perhaps you forgot mpirun? "<<endl;
    exit(-2);
  }

  // allocate memory
  input_text   = new vector<string>;
  input_map    = new map<string,string>;

  // get the lines of text from the input file
  get_input_lines(input_text, infile);
  build_map(input_map, input_text);

  // build and merge with default map ( if desired )
  if (!default_fname.empty()) {
    ifstream infile2( default_fname.c_str(), ios::in);

    map<string,string> *default_map  = new map<string,string>;
    vector<string> *default_text = new vector<string>;

    get_input_lines(default_text, infile2);
    build_map(default_map, default_text);

    // merge the two maps
    map<string,string>::const_iterator iter = default_map->begin();
    for ( ; iter != default_map->end(); ++iter ) {
      string defkey = iter->first;
      string defval = iter->second;
      if ( input_map->find(defkey) == input_map->end() ) {
	(*input_map)[defkey] = defval;
      }
    }
    infile2.close();

    delete default_map;
    delete default_text;

  } else  {
    cerr << "Input warning: no input.config file found." << endl;
    cerr << "Get one from source directory." << endl;
    exit(-2);
  }

  infile.close();

}

phSolver::Input::~Input()
{
  delete input_text;
  delete input_map;
}

// return the input map
map<string,string> phSolver::Input::InputMap() const
{
  return *input_map;
}

// echo the entire map
void phSolver::Input::EchoInputMap(const ostream &ofile)
{
  map<string,string>::const_iterator iter = input_map->begin();
  for ( ; iter != input_map->end(); ++iter ) {
    cout << "Keyphrase: " << iter->first << endl
	 << "Keyvalue:  " << iter->second << endl << endl;
  }
}

// read the input text from the given stream
void phSolver::Input::get_input_lines(vector<string> *text, ifstream &infile)
{
  string textline;
  while ( getline( infile, textline, '\n' ) ) {
    // ignore everything on a comment line
    if ( textline[0] != '#' ) {
      text->push_back( textline );
    }
  }
}

//
void phSolver::Input::build_map(map<string,string> *inmap,
		      vector<string>     *intext)
{
  // iterate through input_text of text and separate at :'s
  for (int i = 0 ; i < intext->size(); i++) {
    string textlineALL = (*intext)[i];
    string textline;
    int pos  = 0;

    // modification introduced so that comments starting midway in a file
    // can be handled.

    if ( (pos = textlineALL.find_first_of( '#',pos)) != string::npos) {
      textline = textlineALL.substr(0,pos);
    }else {
      textline = textlineALL;
    }
    pos = 0;
    if ( (pos = textline.find_first_of( ':',pos)) != string::npos) {

      // get the keyphrase
      string keywd = textline.substr(0,pos);
      trim_string(&keywd);

      // get the key-value
      string keyval = textline.substr( pos+1, textline.length() - pos);
      trim_string(&keyval);

      // put the pair into the map
      (*inmap)[keywd] = keyval;

    }
  }
}

// remove leading and trailing spaces (or tabs)
void phSolver::Input::trim_string(string *str)
{
  // check for empty string
  int length = str->length();
  if ( length == 0 )
    return;

  // erase leading spaces (or tabs)
  int pos0 = 0;
  while ( (*str)[pos0] == ' ' || (*str)[pos0] == '\t') {
    pos0++;
  }
  if ( pos0 > 0 ) {
    str->erase(0,pos0);
  }

  length = str->length();
  pos0 = length-1;
  // erase trailing spaces (or tabs)
  while ( (*str)[pos0] == ' ' || (*str)[pos0] == '\t') {
    pos0--;
  }
  if ( pos0 < length-1 ) {
    str->erase(pos0+1, length-pos0);
  }

}
<commit_msg>initialize variables, and compare like types<commit_after>#include <stdio.h>
#include <fstream>
#include "Input.h"
#include "ValType.h"
#include <stdexcept>
#include <sstream>
//MR CHANGE
#include <cstdlib>
//MR CHANGE END

// return a given key value (if it's in the map)
ValType phSolver::Input::GetValue(const string &str) const
{
  if (input_map->find(str) != input_map->end()) {
    if ( (*input_map)[str] == "NODEFAULT" ) {
      stringstream ost;
      ost << "required input variable not set: " << str << ends;
      throw invalid_argument( ost.str() );
    }
  } else {
    stringstream ost;
    ost << "required input variable not set: " << str << ends;
    throw invalid_argument( ost.str() );
  }

  return ValType( (*input_map)[str] );
}

const char* phSolver::Input::GetUserFileName() {
  return userConfFileName.c_str();
}

const char* phSolver::Input::GetDefaultFileName() {
  return defaultConfFileName.c_str();
}

phSolver::Input::Input(const string &fname, const string &default_fname)
  : userConfFileName(fname), defaultConfFileName(default_fname)
{
  // open the input file
  ifstream infile( fname.c_str(), ios::in);

  if(!infile || infile.eof()){
    cerr<<" Input file does not exist or is empty or perhaps you forgot mpirun? "<<endl;
    exit(-2);
  }

  // allocate memory
  input_text   = new vector<string>;
  input_map    = new map<string,string>;

  // get the lines of text from the input file
  get_input_lines(input_text, infile);
  build_map(input_map, input_text);

  // build and merge with default map ( if desired )
  if (!default_fname.empty()) {
    ifstream infile2( default_fname.c_str(), ios::in);

    map<string,string> *default_map  = new map<string,string>;
    vector<string> *default_text = new vector<string>;

    get_input_lines(default_text, infile2);
    build_map(default_map, default_text);

    // merge the two maps
    map<string,string>::const_iterator iter = default_map->begin();
    for ( ; iter != default_map->end(); ++iter ) {
      string defkey = iter->first;
      string defval = iter->second;
      if ( input_map->find(defkey) == input_map->end() ) {
	(*input_map)[defkey] = defval;
      }
    }
    infile2.close();

    delete default_map;
    delete default_text;

  } else  {
    cerr << "Input warning: no input.config file found." << endl;
    cerr << "Get one from source directory." << endl;
    exit(-2);
  }

  infile.close();

}

phSolver::Input::~Input()
{
  delete input_text;
  delete input_map;
}

// return the input map
map<string,string> phSolver::Input::InputMap() const
{
  return *input_map;
}

// echo the entire map
void phSolver::Input::EchoInputMap(const ostream &ofile)
{
  map<string,string>::const_iterator iter = input_map->begin();
  for ( ; iter != input_map->end(); ++iter ) {
    cout << "Keyphrase: " << iter->first << endl
	 << "Keyvalue:  " << iter->second << endl << endl;
  }
}

// read the input text from the given stream
void phSolver::Input::get_input_lines(vector<string> *text, ifstream &infile)
{
  string textline;
  while ( getline( infile, textline, '\n' ) ) {
    // ignore everything on a comment line
    if ( textline[0] != '#' ) {
      text->push_back( textline );
    }
  }
}

//
void phSolver::Input::build_map(map<string,string> *inmap,
		      vector<string>     *intext)
{
  // iterate through input_text of text and separate at :'s
  for (unsigned i = 0 ; i < intext->size(); i++) {
    string textlineALL = (*intext)[i];
    string textline;

    // modification introduced so that comments starting midway in a file
    // can be handled.
    size_t pos = textlineALL.find_first_of( '#',0);
    if ( pos != string::npos) {
      textline = textlineALL.substr(0,pos);
    }else {
      textline = textlineALL;
    }
    pos = textline.find_first_of( ':', 0);
    if ( pos != string::npos) {

      // get the keyphrase
      string keywd = textline.substr(0,pos);
      trim_string(&keywd);

      // get the key-value
      string keyval = textline.substr( pos+1, textline.length() - pos);
      trim_string(&keyval);

      // put the pair into the map
      (*inmap)[keywd] = keyval;

    }
  }
}

// remove leading and trailing spaces (or tabs)
void phSolver::Input::trim_string(string *str)
{
  // check for empty string
  int length = str->length();
  if ( length == 0 )
    return;

  // erase leading spaces (or tabs)
  int pos0 = 0;
  while ( (*str)[pos0] == ' ' || (*str)[pos0] == '\t') {
    pos0++;
  }
  if ( pos0 > 0 ) {
    str->erase(0,pos0);
  }

  length = str->length();
  pos0 = length-1;
  // erase trailing spaces (or tabs)
  while ( (*str)[pos0] == ' ' || (*str)[pos0] == '\t') {
    pos0--;
  }
  if ( pos0 < length-1 ) {
    str->erase(pos0+1, length-pos0);
  }

}
<|endoftext|>


<commit_before>
#ifndef AT_COMMAND_LINE_HPP
#define AT_COMMAND_LINE_HPP

#include "atNotifier.h++"
#include "atString.h++"
#include "atList.h++"
#include "atMap.h++"

class atCommandLine : public atNotifier
{
   protected:

      atMap    valid_options;

      atMap    options_map;
      atList   args_list;

      void     parseValidOptions(atString optionsSpec);
      bool     takesValue(atString option);
      bool     parseOption(char * arg, char * nextArg);

   public:

      atCommandLine();
      atCommandLine(atString optionsSpec);
      atCommandLine(int argc, char ** argv, atString optionsSpec);
      virtual ~atCommandLine();

      void       setValidOptions(atString optionsSpec);
      void       addValidOption(char option, bool takesValue);

      void       parseCommandLine(int argc, char ** argv);

      bool       hasOption(atString opt);
      atString   getOptionValue(atString opt);

      atList *   getOptionList();
      atList *   getArgumentList();
};

#endif

<commit_msg>Forgot ATLAS_SYM<commit_after>
#ifndef AT_COMMAND_LINE_HPP
#define AT_COMMAND_LINE_HPP

#include "atNotifier.h++"
#include "atString.h++"
#include "atList.h++"
#include "atMap.h++"

class ATLAS_SYM atCommandLine : public atNotifier
{
   protected:

      atMap    valid_options;

      atMap    options_map;
      atList   args_list;

      void     parseValidOptions(atString optionsSpec);
      bool     takesValue(atString option);
      bool     parseOption(char * arg, char * nextArg);

   public:

      atCommandLine();
      atCommandLine(atString optionsSpec);
      atCommandLine(int argc, char ** argv, atString optionsSpec);
      virtual ~atCommandLine();

      void       setValidOptions(atString optionsSpec);
      void       addValidOption(char option, bool takesValue);

      void       parseCommandLine(int argc, char ** argv);

      bool       hasOption(atString opt);
      atString   getOptionValue(atString opt);

      atList *   getOptionList();
      atList *   getArgumentList();
};

#endif

<|endoftext|>