<commit_before>/*********************************************************************
 *
 * Copyright (C) 2008,  Simon Kagstrom
 *
 * Filename:      basicblock.cc
 * Author:        Simon Kagstrom <simon.kagstrom@gmail.com>
 * Description:   Basic block implementation
 *
 * $Id:$
 *
 ********************************************************************/
#include <controller.hh>
#include <basicblock.hh>
#include <emit.hh>
#include <config.hh>

BasicBlock::BasicBlock(Instruction **insns,
		       bb_type_t type,
		       int first, int last) : CodeBlock()
{
  this->instructions = &(insns[first]);
  this->n_insns = last - first;
  this->type = type;

  this->address = this->instructions[0]->getAddress();
  this->size = this->n_insns * 4;
}

bool BasicBlock::pass1()
{
  bool out = true;

  for (int i = 0; i < this->n_insns; i++)
    {
      Instruction *insn = this->instructions[i];

      /* Compile the instruction */
      if (!insn->pass1())
	out = false;

      if ( (this->type == PROLOGUE && insn->getOpcode() == OP_SW) ||
	   (this->type == EPILOGUE && insn->getOpcode() == OP_LW) )
	{
	  int p_s[N_REGS];
	  int p_d[N_REGS];

	  memset(p_s, 0, sizeof(p_s));
	  memset(p_d, 0, sizeof(p_d));
	  insn->fillSources(p_s);
	  insn->fillDestinations(p_d);

	  /* Loop through all caller saved registers and for writes, simply skip them */
	  for (int j = 0;
	       mips_caller_saved[j] != R_ZERO;
	       j++)
	    {
	      MIPS_register_t reg = mips_caller_saved[j];

	      if ( (this->type == PROLOGUE && p_s[reg] != 0) ||
                   (this->type == EPILOGUE && p_d[reg] != 0) )
		{
		  this->instructions[i] = new Nop(insn->getAddress());
                  if (insn->isBranchTarget())
                    this->instructions[i]->setBranchTarget();
		  delete insn;
		  break;
		}
	    }
	}
    }

  return out;
}

static void pushRegister(MIPS_register_t reg)
{
  if (reg != R_RA)
    emit->bc_pushregister(reg);
  else
    emit->bc_pushconst(0);
}

void BasicBlock::traceRegisterValues(Instruction *insn)
{
  MIPS_register_t rs,rt,rd;

  rs = insn->getRs();
  rt = insn->getRt();
  rd = insn->getRd();

  /* Push all registers, then invoke the tracer */
  pushRegister(rs);
  pushRegister(rt);
  pushRegister(rd);

  emit->bc_invokestatic("CRunTime/emitRegisterTrace(III)V");
  if (insn->getDelayed())
    this->traceRegisterValues(insn->getDelayed());
}

void BasicBlock::commentInstruction(Instruction *insn)
{
  char buf[255];
  char out[255];

  /* Output a comment */
  int l = snprintf(buf, 255, "0x%x: ", insn->getAddress());
  l += instruction_to_string(insn, buf+l, 255);
  if (insn->hasDelaySlot())
    {
      buf[l] = ' ';
      instruction_to_string(insn->getDelayed(), buf+l+1, 255-l-1);
    }

  snprintf(out, 255, "0x%08x: %s", insn->getAddress(), buf);
  emit->bc_comment(out);

  if ( insn->getAddress() >= config->traceRange[0] && insn->getAddress() < config->traceRange[1])
    {
      emit->bc_ldc(buf);
      emit->bc_invokestatic("CRunTime/emitTrace(Ljava/lang/String;)V");
      this->traceRegisterValues(insn);
    }
}

bool BasicBlock::pass2()
{
  bool out = true;

  emit->bc_comment("--- basic block ---");
  for (int i = 0; i < this->n_insns; i++)
    {
      Instruction *insn = this->instructions[i];

      /* FIXME: Emit .line info if debug is on */
      if (insn->isBranchTarget() || controller->hasJumptabLabel(insn->getAddress()))
	emit->bc_label( "L_%x", insn->getAddress() );

      if (!insn->isNop())
	this->commentInstruction(insn);

      /* Compile the instruction */
      if (!insn->pass2())
	out = false;
    }

  return out;
}

int BasicBlock::fillDestinations(int *p)
{
  int out = 0;

  for (int i = 0; i < this->n_insns; i++)
    {
      Instruction *insn = this->instructions[i];
      Instruction *delayed = insn->getDelayed();
      Instruction *prefix = insn->getPrefix();

      out += insn->fillDestinations(p);
      if (delayed)
        out += delayed->fillDestinations(p);
      if (prefix)
        out += prefix->fillDestinations(p);
    }

  return out;
}

int BasicBlock::fillSources(int *p)
{
  int out = 0;

  for (int i = 0; i < this->n_insns; i++)
    {
      Instruction *insn = this->instructions[i];
      Instruction *delayed = insn->getDelayed();
      Instruction *prefix = insn->getPrefix();

      out += insn->fillSources(p);
      if (delayed)
        out += delayed->fillSources(p);
      if (prefix)
        out += prefix->fillSources(p);
    }

  return out;
}
<commit_msg>Set current instruction (for error reporting)<commit_after>/*********************************************************************
 *
 * Copyright (C) 2008,  Simon Kagstrom
 *
 * Filename:      basicblock.cc
 * Author:        Simon Kagstrom <simon.kagstrom@gmail.com>
 * Description:   Basic block implementation
 *
 * $Id:$
 *
 ********************************************************************/
#include <controller.hh>
#include <basicblock.hh>
#include <emit.hh>
#include <config.hh>

BasicBlock::BasicBlock(Instruction **insns,
		       bb_type_t type,
		       int first, int last) : CodeBlock()
{
  this->instructions = &(insns[first]);
  this->n_insns = last - first;
  this->type = type;

  this->address = this->instructions[0]->getAddress();
  this->size = this->n_insns * 4;
}

bool BasicBlock::pass1()
{
  bool out = true;

  for (int i = 0; i < this->n_insns; i++)
    {
      Instruction *insn = this->instructions[i];

      controller->setCurrentInstruction(insn);

      /* Compile the instruction */
      if (!insn->pass1())
	out = false;

      if ( (this->type == PROLOGUE && insn->getOpcode() == OP_SW) ||
	   (this->type == EPILOGUE && insn->getOpcode() == OP_LW) )
	{
	  int p_s[N_REGS];
	  int p_d[N_REGS];

	  memset(p_s, 0, sizeof(p_s));
	  memset(p_d, 0, sizeof(p_d));
	  insn->fillSources(p_s);
	  insn->fillDestinations(p_d);

	  /* Loop through all caller saved registers and for writes, simply skip them */
	  for (int j = 0;
	       mips_caller_saved[j] != R_ZERO;
	       j++)
	    {
	      MIPS_register_t reg = mips_caller_saved[j];

	      if ( (this->type == PROLOGUE && p_s[reg] != 0) ||
                   (this->type == EPILOGUE && p_d[reg] != 0) )
		{
		  this->instructions[i] = new Nop(insn->getAddress());
                  if (insn->isBranchTarget())
                    this->instructions[i]->setBranchTarget();
		  delete insn;
		  break;
		}
	    }
	}
    }

  return out;
}

static void pushRegister(MIPS_register_t reg)
{
  if (reg != R_RA)
    emit->bc_pushregister(reg);
  else
    emit->bc_pushconst(0);
}

void BasicBlock::traceRegisterValues(Instruction *insn)
{
  MIPS_register_t rs,rt,rd;

  rs = insn->getRs();
  rt = insn->getRt();
  rd = insn->getRd();

  /* Push all registers, then invoke the tracer */
  pushRegister(rs);
  pushRegister(rt);
  pushRegister(rd);

  emit->bc_invokestatic("CRunTime/emitRegisterTrace(III)V");
  if (insn->getDelayed())
    this->traceRegisterValues(insn->getDelayed());
}

void BasicBlock::commentInstruction(Instruction *insn)
{
  char buf[255];
  char out[255];

  /* Output a comment */
  int l = snprintf(buf, 255, "0x%x: ", insn->getAddress());
  l += instruction_to_string(insn, buf+l, 255);
  if (insn->hasDelaySlot())
    {
      buf[l] = ' ';
      instruction_to_string(insn->getDelayed(), buf+l+1, 255-l-1);
    }

  snprintf(out, 255, "0x%08x: %s", insn->getAddress(), buf);
  emit->bc_comment(out);

  if ( insn->getAddress() >= config->traceRange[0] && insn->getAddress() < config->traceRange[1])
    {
      emit->bc_ldc(buf);
      emit->bc_invokestatic("CRunTime/emitTrace(Ljava/lang/String;)V");
      this->traceRegisterValues(insn);
    }
}

bool BasicBlock::pass2()
{
  bool out = true;

  emit->bc_comment("--- basic block ---");
  for (int i = 0; i < this->n_insns; i++)
    {
      Instruction *insn = this->instructions[i];

      controller->setCurrentInstruction(insn);

      /* FIXME: Emit .line info if debug is on */
      if (insn->isBranchTarget() || controller->hasJumptabLabel(insn->getAddress()))
	emit->bc_label( "L_%x", insn->getAddress() );

      if (!insn->isNop())
	this->commentInstruction(insn);

      /* Compile the instruction */
      if (!insn->pass2())
	out = false;
    }

  return out;
}

int BasicBlock::fillDestinations(int *p)
{
  int out = 0;

  for (int i = 0; i < this->n_insns; i++)
    {
      Instruction *insn = this->instructions[i];
      Instruction *delayed = insn->getDelayed();
      Instruction *prefix = insn->getPrefix();

      out += insn->fillDestinations(p);
      if (delayed)
        out += delayed->fillDestinations(p);
      if (prefix)
        out += prefix->fillDestinations(p);
    }

  return out;
}

int BasicBlock::fillSources(int *p)
{
  int out = 0;

  for (int i = 0; i < this->n_insns; i++)
    {
      Instruction *insn = this->instructions[i];
      Instruction *delayed = insn->getDelayed();
      Instruction *prefix = insn->getPrefix();

      out += insn->fillSources(p);
      if (delayed)
        out += delayed->fillSources(p);
      if (prefix)
        out += prefix->fillSources(p);
    }

  return out;
}
<|endoftext|>


<commit_before>/******************************************************************************\
* TestLuaVariable.cpp                                                          *
* Unit tests for things declared in 'LuaVariable.hpp'.                         *
* Leandro Motta Barros                                                         *
\******************************************************************************/

#include <boost/test/unit_test.hpp>
#include "LuaState.hpp"

// - TestLuaVariableSubscriptOperator ------------------------------------------
void TestLuaVariableSubscriptOperator()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("a = 1; b = 'two'; c = true; d = { 'foo', 'bar', 'baz' }");

   // Check if the values can be read
   BOOST_CHECK (ls["a"] == 1);
   BOOST_CHECK (ls["b"] == "two");
   BOOST_CHECK (ls["c"] == true);
   BOOST_CHECK (ls["d"][1] == "foo");
   BOOST_CHECK (ls["d"][2] == "bar");
   BOOST_CHECK (ls["d"][3] == "baz");

   // Change some values and verify if they were really changed
   ls["a"] = false;
   ls["b"] = 3 * 7;
   ls["d"][2] = "two";
   ls["d"][3] = ls["b"].value();

   BOOST_CHECK (ls["a"] == false);
   BOOST_CHECK (ls["b"] == 21);
   BOOST_CHECK (ls["d"][2] == "two");
   BOOST_CHECK (ls["d"][3] == 21);

   // Add some new values, and read them
   LuaValueMap nestedLVM;
   nestedLVM[1] = "I";
   nestedLVM["six"] = "VI";
   nestedLVM[false] = 0;

   LuaValueMap lvm;
   lvm[1] = "eins";
   lvm[2] = "deux";
   lvm[3] = "trs";
   lvm[4] = "cuatro";
   lvm[5] = "five";
   lvm[6] = nestedLVM;

   ls["d"][4] = 12.34;
   ls["d"][true] = lvm;
   ls["z"] = 56.78;

   BOOST_CHECK (ls["d"][4] == 12.34);
   BOOST_CHECK (ls["d"][true][1] == "eins");
   BOOST_CHECK (ls["d"][true][2] == "deux");
   BOOST_CHECK (ls["d"][true][3] == "trs");
   BOOST_CHECK (ls["d"][true][4] == "cuatro");
   BOOST_CHECK (ls["d"][true][5] == "five");
   BOOST_CHECK (ls["d"][true][6][1] == "I");
   BOOST_CHECK (ls["d"][true][6]["six"] == "VI");
   BOOST_CHECK (ls["d"][true][6][false] == 0);
   BOOST_CHECK (ls["z"] == 56.78);
}

// - TestLuaVariableAssignmentOperatorValue ------------------------------------
void TestLuaVariableAssignmentOperatorValue()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("a = 1; b = 'two'; c = true; d = { 'foo', 'bar', [5] = 'baz' }");

   // "Multiple" assignment
   ls["a"] = ls["c"] = ls["d"][5] = 123.456;
   BOOST_CHECK (ls["a"] == 123.456);
   BOOST_CHECK (ls["c"] == 123.456);
   BOOST_CHECK (ls["d"][5] == 123.456);

   // The other fields shall be untouched
   BOOST_CHECK (ls["b"] == "two");
   BOOST_CHECK (ls["d"][1] == "foo");
   BOOST_CHECK (ls["d"][2] == "bar");
}

// - TestLuaVariableAssignmentOperatorVariable ---------------------------------
void TestLuaVariableAssignmentOperatorVariable()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("a = 1; b = 'two'; c = { 1.1, 2.2, 3.3 }");

   // Create two 'LuaVariable's and, just in case, check if they have the proper
   // values
   LuaVariable lv1 = ls["a"];
   LuaVariable lv2 = ls["b"];
   BOOST_CHECK (lv1 == 1);
   BOOST_CHECK (lv2 == "two");

   // Test for self assignment
   lv1 = lv1;
   lv2 = lv2;
   BOOST_CHECK (lv1 == 1);
   BOOST_CHECK (lv2 == "two");

   // Assign one to another. Check if they now refer to the same variable
   lv2 = lv1;
   BOOST_CHECK (lv1 == 1);
   BOOST_CHECK (lv2 == 1);

   lv2 = false;
   BOOST_CHECK (lv1 == false);
   BOOST_CHECK (lv2 == false);

   // "Multiple" assignment
   LuaVariable lv3 = ls["c"];
   lv1 = lv2 = lv3;
   BOOST_CHECK (lv1[1] == 1.1);
   BOOST_CHECK (lv1[2] == 2.2);
   BOOST_CHECK (lv1[3] == 3.3);
   BOOST_CHECK (lv2[1] == 1.1);
   BOOST_CHECK (lv2[2] == 2.2);
   BOOST_CHECK (lv2[3] == 3.3);
   BOOST_CHECK (lv3[1] == 1.1);
   BOOST_CHECK (lv3[2] == 2.2);
   BOOST_CHECK (lv3[3] == 3.3);
}

// - TestLuaVariableCopyConstructor --------------------------------------------
void TestLuaVariableCopyConstructor()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("a = 1");

   // Create two 'LuaVariable's referring to the same variable in the same
   // 'LuaState'. Then chack if changing one also changes the another one.
   LuaVariable lv = ls["a"];
   BOOST_CHECK (lv == 1); // just to be sure, this is already tested elsewhere

   LuaVariable lvc (lv);
   BOOST_CHECK (lvc == 1);

   lvc = "a string";
   BOOST_CHECK (lvc == "a string");
   BOOST_CHECK (lv == "a string");

   lv = true;
   BOOST_CHECK (lv == true);
   BOOST_CHECK (lvc == true);
}

// - TestLuaVariableEqualityOperator -------------------------------------------
void TestLuaVariableEqualityOperator()
{
   using namespace Diluculum;

   LuaState ls1;
   ls1.doString ("a = 1; b = 'two'");

   LuaState ls2;
   ls2.doString ("a = 1; b = 'two'");

   LuaVariable lv1 = ls1["a"];
   LuaVariable lv2 = ls1["b"];
   LuaVariable lv3 = ls2["a"];
   LuaVariable lv4 = ls2["b"];

   LuaVariable lv5 = ls1["a"];
   LuaVariable lv6 = ls1["b"];
   LuaVariable lv7 = ls2["a"];
   LuaVariable lv8 = ls2["b"];

   // Each variable is expected to be equal to itself
   BOOST_CHECK (lv1 == lv1);
   BOOST_CHECK (lv2 == lv2);
   BOOST_CHECK (lv3 == lv3);
   BOOST_CHECK (lv4 == lv4);
   BOOST_CHECK (lv5 == lv5);
   BOOST_CHECK (lv6 == lv6);
   BOOST_CHECK (lv7 == lv7);
   BOOST_CHECK (lv8 == lv8);

   // Each variable is expected to be no different than itself
   BOOST_CHECK (!(lv1 != lv1));
   BOOST_CHECK (!(lv2 != lv2));
   BOOST_CHECK (!(lv3 != lv3));
   BOOST_CHECK (!(lv4 != lv4));
   BOOST_CHECK (!(lv5 != lv5));
   BOOST_CHECK (!(lv6 != lv6));
   BOOST_CHECK (!(lv7 != lv7));
   BOOST_CHECK (!(lv8 != lv8));

   // 'LuaVariable's created as referring to the same variables should be equal
   BOOST_CHECK (lv1 == lv5);
   BOOST_CHECK (lv2 == lv6);
   BOOST_CHECK (lv3 == lv7);
   BOOST_CHECK (lv4 == lv8);

   BOOST_CHECK (!(lv1 != lv5));
   BOOST_CHECK (!(lv2 != lv6));
   BOOST_CHECK (!(lv3 != lv7));
   BOOST_CHECK (!(lv4 != lv8));

   // The same as the previous, but inverting the operands
   BOOST_CHECK (lv5 == lv1);
   BOOST_CHECK (lv6 == lv2);
   BOOST_CHECK (lv7 == lv3);
   BOOST_CHECK (lv8 == lv4);

   BOOST_CHECK (!(lv5 != lv1));
   BOOST_CHECK (!(lv6 != lv2));
   BOOST_CHECK (!(lv7 != lv3));
   BOOST_CHECK (!(lv8 != lv4));

   // If the variables differ "just" by the 'LuaState', they are still different
   BOOST_CHECK (lv1 != lv3);
   BOOST_CHECK (lv2 != lv4);

   BOOST_CHECK (!(lv1 == lv3));
   BOOST_CHECK (!(lv2 == lv4));

   // Try some other assorted comparisons
   BOOST_CHECK (lv1 != lv2);
   BOOST_CHECK (lv1 != lv3);
   BOOST_CHECK (lv1 != lv4);

   BOOST_CHECK (!(lv1 == lv2));
   BOOST_CHECK (!(lv1 == lv3));
   BOOST_CHECK (!(lv1 == lv4));

   // Finally, ensure that variables are equal after one is assigned to another
   lv1 = lv2;
   lv3 = lv4 = lv5 = lv6;

   BOOST_CHECK (lv1 == lv1);
   BOOST_CHECK (lv1 == lv2);
   BOOST_CHECK (lv2 == lv2);

   BOOST_CHECK (lv3 == lv3);
   BOOST_CHECK (lv3 == lv4);
   BOOST_CHECK (lv3 == lv5);
   BOOST_CHECK (lv3 == lv6);

   BOOST_CHECK (lv4 == lv3);
   BOOST_CHECK (lv4 == lv4);
   BOOST_CHECK (lv4 == lv5);
   BOOST_CHECK (lv4 == lv6);

   BOOST_CHECK (lv5 == lv3);
   BOOST_CHECK (lv5 == lv4);
   BOOST_CHECK (lv5 == lv5);
   BOOST_CHECK (lv5 == lv6);

   BOOST_CHECK (lv6 == lv3);
   BOOST_CHECK (lv6 == lv4);
   BOOST_CHECK (lv6 == lv5);
   BOOST_CHECK (lv6 == lv6);
}

// - TestLuaVariableExceptions -------------------------------------------------
void TestLuaVariableExceptions()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("t = { a = 1, b = 'b', c = true }");

   // Accessing a valid global variable shall not throw.
   LuaVariable lv1 = ls["t"];
   BOOST_CHECK_NO_THROW (lv1.value());

   // Accessing an invalid global variable shall not throw ('Nil' is returned)
   LuaVariable lv2 = ls["x"];
   BOOST_CHECK_NO_THROW (lv2.value());
   BOOST_CHECK (lv2.value() == Nil);

   // Accessing a valid table key shall not throw
   LuaVariable lv3 = ls["t"]["a"];
   BOOST_CHECK_NO_THROW (lv3.value());

   // Accessing an invalid table key shall not throw ('Nil' is returned)
   LuaVariable lv4 = ls["t"]["x"];
   BOOST_CHECK_NO_THROW (lv4.value());
   BOOST_CHECK (lv4.value() == Nil);

   // Accessing an (obviously) invalid key of an invalid table shall throw
   BOOST_CHECK_THROW (ls["x"]["x"].value(), TypeMismatchError);

   // Subscripting a non-table shall throw, too
   BOOST_CHECK_THROW (ls["a"]["x"].value(), TypeMismatchError);
}

// - TestLuaVariableFunctionCall -----------------------------------------------
void TestLuaVariableFunctionCall()
{
   using namespace Diluculum;

   LuaState ls;

//    // <--- Just wondering... not real tests yet...
//    LuaValue f = ls.doString ("return function (x) return x * x end");

//    BOOST_CHECK (1 == 2);
}

using boost::unit_test_framework::test_suite;

// - init_unit_test_suite ------------------------------------------------------
test_suite* init_unit_test_suite (int, char*[])
{
   test_suite* test = BOOST_TEST_SUITE ("'LuaVariable' tests");
   test->add (BOOST_TEST_CASE (&TestLuaVariableSubscriptOperator));
   test->add (BOOST_TEST_CASE (&TestLuaVariableAssignmentOperatorValue));
   test->add (BOOST_TEST_CASE (&TestLuaVariableAssignmentOperatorVariable));
   test->add (BOOST_TEST_CASE (&TestLuaVariableCopyConstructor));
   test->add (BOOST_TEST_CASE (&TestLuaVariableEqualityOperator));
   test->add (BOOST_TEST_CASE (&TestLuaVariableExceptions));
   test->add (BOOST_TEST_CASE (&TestLuaVariableFunctionCall));

   return test;
}
<commit_msg>Added some new tests to 'LuaVariable''s assignment operator.<commit_after>/******************************************************************************\
* TestLuaVariable.cpp                                                          *
* Unit tests for things declared in 'LuaVariable.hpp'.                         *
* Leandro Motta Barros                                                         *
\******************************************************************************/

#include <boost/test/unit_test.hpp>
#include "LuaState.hpp"

// - TestLuaVariableSubscriptOperator ------------------------------------------
void TestLuaVariableSubscriptOperator()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("a = 1; b = 'two'; c = true; d = { 'foo', 'bar', 'baz' }");

   // Check if the values can be read
   BOOST_CHECK (ls["a"] == 1);
   BOOST_CHECK (ls["b"] == "two");
   BOOST_CHECK (ls["c"] == true);
   BOOST_CHECK (ls["d"][1] == "foo");
   BOOST_CHECK (ls["d"][2] == "bar");
   BOOST_CHECK (ls["d"][3] == "baz");

   // Change some values and verify if they were really changed
   ls["a"] = false;
   ls["b"] = 3 * 7;
   ls["d"][2] = "two";
   ls["d"][3] = ls["b"].value();

   BOOST_CHECK (ls["a"] == false);
   BOOST_CHECK (ls["b"] == 21);
   BOOST_CHECK (ls["d"][2] == "two");
   BOOST_CHECK (ls["d"][3] == 21);

   // Add some new values, and read them
   LuaValueMap nestedLVM;
   nestedLVM[1] = "I";
   nestedLVM["six"] = "VI";
   nestedLVM[false] = 0;

   LuaValueMap lvm;
   lvm[1] = "eins";
   lvm[2] = "deux";
   lvm[3] = "trs";
   lvm[4] = "cuatro";
   lvm[5] = "five";
   lvm[6] = nestedLVM;

   ls["d"][4] = 12.34;
   ls["d"][true] = lvm;
   ls["z"] = 56.78;

   BOOST_CHECK (ls["d"][4] == 12.34);
   BOOST_CHECK (ls["d"][true][1] == "eins");
   BOOST_CHECK (ls["d"][true][2] == "deux");
   BOOST_CHECK (ls["d"][true][3] == "trs");
   BOOST_CHECK (ls["d"][true][4] == "cuatro");
   BOOST_CHECK (ls["d"][true][5] == "five");
   BOOST_CHECK (ls["d"][true][6][1] == "I");
   BOOST_CHECK (ls["d"][true][6]["six"] == "VI");
   BOOST_CHECK (ls["d"][true][6][false] == 0);
   BOOST_CHECK (ls["z"] == 56.78);
}

// - TestLuaVariableAssignmentOperatorValue ------------------------------------
void TestLuaVariableAssignmentOperatorValue()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("a = 1; b = 'two'; c = true; d = { 'foo', 'bar', [5] = 'baz' }");

   // "Multiple" assignment
   ls["newField"] = ls["a"] = ls["c"] = ls["d"][5] = 123.456;
   BOOST_CHECK (ls["newField"] == 123.456);
   BOOST_CHECK (ls["a"] == 123.456);
   BOOST_CHECK (ls["c"] == 123.456);
   BOOST_CHECK (ls["d"][5] == 123.456);

   // The other fields shall be untouched
   BOOST_CHECK (ls["b"] == "two");
   BOOST_CHECK (ls["d"][1] == "foo");
   BOOST_CHECK (ls["d"][2] == "bar");

   // Try with other types, too
   ls["a"] = "Boo!";
   BOOST_CHECK (ls["a"] == "Boo!");

   ls["a"] = false;
   BOOST_CHECK (ls["a"] == false);

   ls["a"] = Nil;
   BOOST_CHECK (ls["a"] == Nil);
}

// - TestLuaVariableAssignmentOperatorVariable ---------------------------------
void TestLuaVariableAssignmentOperatorVariable()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("a = 1; b = 'two'; c = { 1.1, 2.2, 3.3 }");

   // Create two 'LuaVariable's and, just in case, check if they have the proper
   // values
   LuaVariable lv1 = ls["a"];
   LuaVariable lv2 = ls["b"];
   BOOST_CHECK (lv1 == 1);
   BOOST_CHECK (lv2 == "two");

   // Test for self assignment
   lv1 = lv1;
   lv2 = lv2;
   BOOST_CHECK (lv1 == 1);
   BOOST_CHECK (lv2 == "two");

   // Assign one to another. Check if they now refer to the same variable
   lv2 = lv1;
   BOOST_CHECK (lv1 == 1);
   BOOST_CHECK (lv2 == 1);

   lv2 = false;
   BOOST_CHECK (lv1 == false);
   BOOST_CHECK (lv2 == false);

   // "Multiple" assignment
   LuaVariable lv3 = ls["c"];
   lv1 = lv2 = lv3;
   BOOST_CHECK (lv1[1] == 1.1);
   BOOST_CHECK (lv1[2] == 2.2);
   BOOST_CHECK (lv1[3] == 3.3);
   BOOST_CHECK (lv2[1] == 1.1);
   BOOST_CHECK (lv2[2] == 2.2);
   BOOST_CHECK (lv2[3] == 3.3);
   BOOST_CHECK (lv3[1] == 1.1);
   BOOST_CHECK (lv3[2] == 2.2);
   BOOST_CHECK (lv3[3] == 3.3);
}

// - TestLuaVariableCopyConstructor --------------------------------------------
void TestLuaVariableCopyConstructor()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("a = 1");

   // Create two 'LuaVariable's referring to the same variable in the same
   // 'LuaState'. Then chack if changing one also changes the another one.
   LuaVariable lv = ls["a"];
   BOOST_CHECK (lv == 1); // just to be sure, this is already tested elsewhere

   LuaVariable lvc (lv);
   BOOST_CHECK (lvc == 1);

   lvc = "a string";
   BOOST_CHECK (lvc == "a string");
   BOOST_CHECK (lv == "a string");

   lv = true;
   BOOST_CHECK (lv == true);
   BOOST_CHECK (lvc == true);
}

// - TestLuaVariableEqualityOperator -------------------------------------------
void TestLuaVariableEqualityOperator()
{
   using namespace Diluculum;

   LuaState ls1;
   ls1.doString ("a = 1; b = 'two'");

   LuaState ls2;
   ls2.doString ("a = 1; b = 'two'");

   LuaVariable lv1 = ls1["a"];
   LuaVariable lv2 = ls1["b"];
   LuaVariable lv3 = ls2["a"];
   LuaVariable lv4 = ls2["b"];

   LuaVariable lv5 = ls1["a"];
   LuaVariable lv6 = ls1["b"];
   LuaVariable lv7 = ls2["a"];
   LuaVariable lv8 = ls2["b"];

   // Each variable is expected to be equal to itself
   BOOST_CHECK (lv1 == lv1);
   BOOST_CHECK (lv2 == lv2);
   BOOST_CHECK (lv3 == lv3);
   BOOST_CHECK (lv4 == lv4);
   BOOST_CHECK (lv5 == lv5);
   BOOST_CHECK (lv6 == lv6);
   BOOST_CHECK (lv7 == lv7);
   BOOST_CHECK (lv8 == lv8);

   // Each variable is expected to be no different than itself
   BOOST_CHECK (!(lv1 != lv1));
   BOOST_CHECK (!(lv2 != lv2));
   BOOST_CHECK (!(lv3 != lv3));
   BOOST_CHECK (!(lv4 != lv4));
   BOOST_CHECK (!(lv5 != lv5));
   BOOST_CHECK (!(lv6 != lv6));
   BOOST_CHECK (!(lv7 != lv7));
   BOOST_CHECK (!(lv8 != lv8));

   // 'LuaVariable's created as referring to the same variables should be equal
   BOOST_CHECK (lv1 == lv5);
   BOOST_CHECK (lv2 == lv6);
   BOOST_CHECK (lv3 == lv7);
   BOOST_CHECK (lv4 == lv8);

   BOOST_CHECK (!(lv1 != lv5));
   BOOST_CHECK (!(lv2 != lv6));
   BOOST_CHECK (!(lv3 != lv7));
   BOOST_CHECK (!(lv4 != lv8));

   // The same as the previous, but inverting the operands
   BOOST_CHECK (lv5 == lv1);
   BOOST_CHECK (lv6 == lv2);
   BOOST_CHECK (lv7 == lv3);
   BOOST_CHECK (lv8 == lv4);

   BOOST_CHECK (!(lv5 != lv1));
   BOOST_CHECK (!(lv6 != lv2));
   BOOST_CHECK (!(lv7 != lv3));
   BOOST_CHECK (!(lv8 != lv4));

   // If the variables differ "just" by the 'LuaState', they are still different
   BOOST_CHECK (lv1 != lv3);
   BOOST_CHECK (lv2 != lv4);

   BOOST_CHECK (!(lv1 == lv3));
   BOOST_CHECK (!(lv2 == lv4));

   // Try some other assorted comparisons
   BOOST_CHECK (lv1 != lv2);
   BOOST_CHECK (lv1 != lv3);
   BOOST_CHECK (lv1 != lv4);

   BOOST_CHECK (!(lv1 == lv2));
   BOOST_CHECK (!(lv1 == lv3));
   BOOST_CHECK (!(lv1 == lv4));

   // Finally, ensure that variables are equal after one is assigned to another
   lv1 = lv2;
   lv3 = lv4 = lv5 = lv6;

   BOOST_CHECK (lv1 == lv1);
   BOOST_CHECK (lv1 == lv2);
   BOOST_CHECK (lv2 == lv2);

   BOOST_CHECK (lv3 == lv3);
   BOOST_CHECK (lv3 == lv4);
   BOOST_CHECK (lv3 == lv5);
   BOOST_CHECK (lv3 == lv6);

   BOOST_CHECK (lv4 == lv3);
   BOOST_CHECK (lv4 == lv4);
   BOOST_CHECK (lv4 == lv5);
   BOOST_CHECK (lv4 == lv6);

   BOOST_CHECK (lv5 == lv3);
   BOOST_CHECK (lv5 == lv4);
   BOOST_CHECK (lv5 == lv5);
   BOOST_CHECK (lv5 == lv6);

   BOOST_CHECK (lv6 == lv3);
   BOOST_CHECK (lv6 == lv4);
   BOOST_CHECK (lv6 == lv5);
   BOOST_CHECK (lv6 == lv6);
}

// - TestLuaVariableExceptions -------------------------------------------------
void TestLuaVariableExceptions()
{
   using namespace Diluculum;

   LuaState ls;
   ls.doString ("t = { a = 1, b = 'b', c = true }");

   // Accessing a valid global variable shall not throw.
   LuaVariable lv1 = ls["t"];
   BOOST_CHECK_NO_THROW (lv1.value());

   // Accessing an invalid global variable shall not throw ('Nil' is returned)
   LuaVariable lv2 = ls["x"];
   BOOST_CHECK_NO_THROW (lv2.value());
   BOOST_CHECK (lv2.value() == Nil);

   // Accessing a valid table key shall not throw
   LuaVariable lv3 = ls["t"]["a"];
   BOOST_CHECK_NO_THROW (lv3.value());

   // Accessing an invalid table key shall not throw ('Nil' is returned)
   LuaVariable lv4 = ls["t"]["x"];
   BOOST_CHECK_NO_THROW (lv4.value());
   BOOST_CHECK (lv4.value() == Nil);

   // Accessing an (obviously) invalid key of an invalid table shall throw
   BOOST_CHECK_THROW (ls["x"]["x"].value(), TypeMismatchError);

   // Subscripting a non-table shall throw, too
   BOOST_CHECK_THROW (ls["a"]["x"].value(), TypeMismatchError);
}

// - TestLuaVariableFunctionCall -----------------------------------------------
void TestLuaVariableFunctionCall()
{
   using namespace Diluculum;

   LuaState ls;

//    // <--- Just wondering... not real tests yet...
//    LuaValue f = ls.doString ("return function (x) return x * x end");

//    BOOST_CHECK (1 == 2);
}

using boost::unit_test_framework::test_suite;

// - init_unit_test_suite ------------------------------------------------------
test_suite* init_unit_test_suite (int, char*[])
{
   test_suite* test = BOOST_TEST_SUITE ("'LuaVariable' tests");
   test->add (BOOST_TEST_CASE (&TestLuaVariableSubscriptOperator));
   test->add (BOOST_TEST_CASE (&TestLuaVariableAssignmentOperatorValue));
   test->add (BOOST_TEST_CASE (&TestLuaVariableAssignmentOperatorVariable));
   test->add (BOOST_TEST_CASE (&TestLuaVariableCopyConstructor));
   test->add (BOOST_TEST_CASE (&TestLuaVariableEqualityOperator));
   test->add (BOOST_TEST_CASE (&TestLuaVariableExceptions));
   test->add (BOOST_TEST_CASE (&TestLuaVariableFunctionCall));

   return test;
}
<|endoftext|>


<commit_before>/* This file is part of the KDE libraries
   Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
   Copyright (C) 2001 Charles Samuels <charles@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

// $Id$

#include "katecmds.h"
#include "katedocument.h"
#include "kateview.h"

#include <qregexp.h>
#include <qstring.h>
#include <qdatetime.h>

#include <kdebug.h>

namespace KateCommands
{

bool InsertTime::execCmd(QString cmd, KateView *view)
{
	if (cmd.left(5) == "time")
	{
		view->insertText(QTime::currentTime().toString());
		return true;
	}

	return false;
}

static void replace(QString &s, const QString &needle, const QString &with)
{
	int pos=0;
	while (1)
	{
		pos=s.find(needle, pos);
		if (pos==-1) break;
		s.replace(pos, needle.length(), with);
		pos+=with.length();
	}

}

static int backslashString(const QString &haystack, const QString &needle, int index)
{
	int len=haystack.length();
	int searchlen=needle.length();
	bool evenCount=true;
	while (index<len)
	{
		if (haystack[index]=='\\')
		{
			evenCount=!evenCount;
		}
		else
		{  // isn't a slash
			if (!evenCount)
			{
				if (haystack.mid(index, searchlen)==needle)
					return index-1;
			}
			evenCount=true;
		}
		index++;

	}

	return -1;
}

// exchange "\t" for the actual tab character, for example
static void exchangeAbbrevs(QString &str)
{
	// the format is (findreplace)*[nullzero]
	const char *magic="a\x07t\t";

	while (*magic)
	{
		int index=0;
		char replace=magic[1];
		while ((index=backslashString(str, QChar(*magic), index))!=-1)
		{
			str.replace(index, 2, QChar(replace));
			index++;
		}
		magic++;
		magic++;
	}
}

QString SedReplace::sedMagic(QString textLine, const QString &find, const QString &repOld, bool noCase, bool repeat)
{

	QRegExp matcher(find, noCase);

	int start=0;
	while (start!=-1)
	{
		start=matcher.search(textLine, start);

		if (start==-1) break;

		int length=matcher.matchedLength();

		QString rep=repOld;

		// now set the backreferences in the replacement
		QStringList backrefs=matcher.capturedTexts();
		int refnum=1;

		QStringList::Iterator i = backrefs.begin();
		++i;

		for (; i!=backrefs.end(); ++i)
		{
			// I need to match "\\" or "", but not "\"
			QString number=QString::number(refnum);

			int index=0;
			while (index!=-1)
			{
				index=backslashString(rep, number, index);
				if (index>=0)
				{
					rep.replace(index, 2, *i);
					index+=(*i).length();
				}
			}

			refnum++;
		}

		replace(rep, "\\\\", "\\");
		replace(rep, "\\/", "/");

		textLine.replace(start, length, rep);
		if (!repeat) break;
		start+=rep.length();
	}

	return textLine;
}

static void setLineText(KateView *view, int line, const QString &text)
{
	if (view->doc()->insertLine(line, text))
	  view->doc()->removeLine(line+1);
}

bool SedReplace::execCmd(QString cmd, KateView *view)
{
	kdDebug(13010)<<"SedReplace::execCmd()"<<endl;

	if (QRegExp("[$%]?s/.+/.*/[ig]*").search(cmd, 0)==-1)
		return false;

	bool fullFile=cmd[0]=='%';
	bool noCase=cmd[cmd.length()-1]=='i' || cmd[cmd.length()-2]=='i';
	bool repeat=cmd[cmd.length()-1]=='g' || cmd[cmd.length()-2]=='g';
	bool onlySelect=cmd[0]=='$';

	QRegExp splitter("^[$%]?s/((?:[^\\\\/]|\\\\[\\\\/\\$\\-\\{\\}\\[\\]\\^\\?0-9tadDsSwW])*)/((?:[^\\\\/]|\\\\[\\\\/\\$\\-\\{\\}\\[\\]\\^\\?0-9tadDsSwW])*)/[ig]*$");
	if (splitter.search(cmd)<0) return false;

	QString find=splitter.cap(1);
	kdDebug(13010)<< "SedReplace: find=" << find.latin1() <<endl;

	QString replace=splitter.cap(2);
	exchangeAbbrevs(replace);
	kdDebug(13010)<< "SedReplace: replace=" << replace.latin1() <<endl;

	if (fullFile)
	{
		int numLines=view->doc()->numLines();
		for (int line=0; line < numLines; line++)
		{
			QString text=view->doc()->textLine(line);
			text=sedMagic(text, find, replace, noCase, repeat);
			setLineText(view, line, text);
		}
	}
	else if (onlySelect)
	{
		// Not implemented
	}
	else
	{ // just this line
		QString textLine=view->currentTextLine();
		int line=view->cursorLine();
		textLine=sedMagic(textLine, find, replace, noCase, repeat);
		setLineText(view, line, textLine);
	}
	return true;
}

bool Character::execCmd(QString cmd, KateView *view)
{
	// hex, octal, base 9+1
	QRegExp num("^char: *(0?x[0-9A-Fa-f]{1,4}|0[0-7]{1,6}|[0-9]{1,3})$");
	if (num.search(cmd)==-1) return false;

	cmd=num.cap(1);

	// identify the base

	unsigned short int number=0;
	int base=10;
	if (cmd[0]=='x' || cmd.left(2)=="0x")
	{
		cmd.replace(QRegExp("^0?x"), "");
		base=16;
	}
	else if (cmd[0]=='0')
		base=8;
	bool ok;
	number=cmd.toUShort(&ok, base);
	if (!ok || number==0) return false;
	if (number<=255)
	{
		char buf[2];
		buf[0]=(char)number;
		buf[1]=0;
		view->insertText(QString(buf));
	}
	else
	{ // do the unicode thing
		QChar c(number);
		view->insertText(QString(&c, 1));
	}

	return true;
}

bool Fifo::execCmd(QString , KateView *)
{
  return true;
}

}

// vim: noet

<commit_msg>I can't believe this works :)<commit_after>/* This file is part of the KDE libraries
   Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
   Copyright (C) 2001 Charles Samuels <charles@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

// $Id$

#include "katecmds.h"
#include "katedocument.h"
#include "kateview.h"

#include <qregexp.h>
#include <qstring.h>
#include <qdatetime.h>

#include <kdebug.h>

namespace KateCommands
{

bool InsertTime::execCmd(QString cmd, KateView *view)
{
	if (cmd.left(5) == "time")
	{
		view->insertText(QTime::currentTime().toString());
		return true;
	}

	return false;
}

static void replace(QString &s, const QString &needle, const QString &with)
{
	int pos=0;
	while (1)
	{
		pos=s.find(needle, pos);
		if (pos==-1) break;
		s.replace(pos, needle.length(), with);
		pos+=with.length();
	}

}

static int backslashString(const QString &haystack, const QString &needle, int index)
{
	int len=haystack.length();
	int searchlen=needle.length();
	bool evenCount=true;
	while (index<len)
	{
		if (haystack[index]=='\\')
		{
			evenCount=!evenCount;
		}
		else
		{  // isn't a slash
			if (!evenCount)
			{
				if (haystack.mid(index, searchlen)==needle)
					return index-1;
			}
			evenCount=true;
		}
		index++;

	}

	return -1;
}

// exchange "\t" for the actual tab character, for example
static void exchangeAbbrevs(QString &str)
{
	// the format is (findreplace)*[nullzero]
	const char *magic="a\x07t\t";

	while (*magic)
	{
		int index=0;
		char replace=magic[1];
		while ((index=backslashString(str, QChar(*magic), index))!=-1)
		{
			str.replace(index, 2, QChar(replace));
			index++;
		}
		magic++;
		magic++;
	}
}

QString SedReplace::sedMagic(QString textLine, const QString &find, const QString &repOld, bool noCase, bool repeat)
{

	QRegExp matcher(find, noCase);

	int start=0;
	while (start!=-1)
	{
		start=matcher.search(textLine, start);

		if (start==-1) break;

		int length=matcher.matchedLength();

		QString rep=repOld;

		// now set the backreferences in the replacement
		QStringList backrefs=matcher.capturedTexts();
		int refnum=1;

		QStringList::Iterator i = backrefs.begin();
		++i;

		for (; i!=backrefs.end(); ++i)
		{
			// I need to match "\\" or "", but not "\"
			QString number=QString::number(refnum);

			int index=0;
			while (index!=-1)
			{
				index=backslashString(rep, number, index);
				if (index>=0)
				{
					rep.replace(index, 2, *i);
					index+=(*i).length();
				}
			}

			refnum++;
		}

		replace(rep, "\\\\", "\\");
		replace(rep, "\\/", "/");

		textLine.replace(start, length, rep);
		if (!repeat) break;
		start+=rep.length();
	}

	return textLine;
}

static void setLineText(KateView *view, int line, const QString &text)
{
	if (view->doc()->insertLine(line, text))
	  view->doc()->removeLine(line+1);
}

bool SedReplace::execCmd(QString cmd, KateView *view)
{
	kdDebug(13010)<<"SedReplace::execCmd()"<<endl;

	if (QRegExp("[$%]?s/.+/.*/[ig]*").search(cmd, 0)==-1)
		return false;

	bool fullFile=cmd[0]=='%';
	bool noCase=cmd[cmd.length()-1]=='i' || cmd[cmd.length()-2]=='i';
	bool repeat=cmd[cmd.length()-1]=='g' || cmd[cmd.length()-2]=='g';
	bool onlySelect=cmd[0]=='$';

	QRegExp splitter("^s/((?:[^\\\\/]|\\\\.)*)/((?:[^\\\\/]|\\\\.)*)/[ig]*$");
	if (splitter.search(cmd)<0) return false;

	QString find=splitter.cap(1);
	kdDebug(13010)<< "SedReplace: find=" << find.latin1() <<endl;

	QString replace=splitter.cap(2);
	exchangeAbbrevs(replace);
	kdDebug(13010)<< "SedReplace: replace=" << replace.latin1() <<endl;

	if (fullFile)
	{
		int numLines=view->doc()->numLines();
		for (int line=0; line < numLines; line++)
		{
			QString text=view->doc()->textLine(line);
			text=sedMagic(text, find, replace, noCase, repeat);
			setLineText(view, line, text);
		}
	}
	else if (onlySelect)
	{
		// Not implemented
	}
	else
	{ // just this line
		QString textLine=view->currentTextLine();
		int line=view->cursorLine();
		textLine=sedMagic(textLine, find, replace, noCase, repeat);
		setLineText(view, line, textLine);
	}
	return true;
}

bool Character::execCmd(QString cmd, KateView *view)
{
	// hex, octal, base 9+1
	QRegExp num("^char: *(0?x[0-9A-Fa-f]{1,4}|0[0-7]{1,6}|[0-9]{1,3})$");
	if (num.search(cmd)==-1) return false;

	cmd=num.cap(1);

	// identify the base

	unsigned short int number=0;
	int base=10;
	if (cmd[0]=='x' || cmd.left(2)=="0x")
	{
		cmd.replace(QRegExp("^0?x"), "");
		base=16;
	}
	else if (cmd[0]=='0')
		base=8;
	bool ok;
	number=cmd.toUShort(&ok, base);
	if (!ok || number==0) return false;
	if (number<=255)
	{
		char buf[2];
		buf[0]=(char)number;
		buf[1]=0;
		view->insertText(QString(buf));
	}
	else
	{ // do the unicode thing
		QChar c(number);
		view->insertText(QString(&c, 1));
	}

	return true;
}

bool Fifo::execCmd(QString , KateView *)
{
  return true;
}

}

// vim: noet

<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkMinimumMaximumImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkMinimumMaximumImageFilter.h"
#include "itkSize.h"

typedef itk::Size<3>                                  SizeType;
typedef itk::Image<float, 3>                  ImageType;
typedef itk::MinimumMaximumImageFilter<ImageType>  MinMaxFilterType;

/* Define the image size and physical coordinates */
SizeType size = {{20, 20, 20}};
double origin [3] = { 0.0, 0.0, 0.0};
double spacing[3] = { 1, 1 , 1};

int
itkMinimumMaximumImageFilterTest(int , char *[] )
{
    int flag = 0;           /* Did this test program work? */

    std::cout << "Testing Minimum and Maximum Image Calulator:\n";

    // Allocate a simple test image
    ImageType::Pointer image = ImageType::New();
    ImageType::RegionType region;
    region.SetSize(size);
    image->SetLargestPossibleRegion(region);
    image->SetRequestedRegion(region);
    image->SetBufferedRegion(region);
    image->Allocate();

    // Set origin and spacing of physical coordinates
    image->SetOrigin(origin);
    image->SetSpacing(spacing);

    float minimum = -52;
    float maximum = -10;

    // Initialize the image contents with the minimum value
    itk::Index<3> index;
    for (int slice = 0; slice < 20; slice++) {
        index[2] = slice;
        for (int row = 0; row <20; row++) {
            index[1] = row;
            for (int col = 0; col < 20; col++) {
                index[0] = col;
                image->SetPixel(index, minimum);
            }
        }
    }

    // Set voxel (10,10,10) to maximum value
    index[0] = 10;
    index[1] = 10;
    index[2] = 10;
    image->SetPixel(index, maximum);

    // Create and initialize the filter
    MinMaxFilterType::Pointer filter = MinMaxFilterType::New();
    filter->SetInput(image);
    filter->Update();

    // Return minimum of intensity
    float minimumResult = filter->GetMinimum();
    std::cout << "The Minimum intensity value is : " << minimumResult << std::endl;

    if(minimumResult != minimum)
    {
       std::cout << "Minimum Value is wrong : " << minimumResult ;
       std::cout << " != " << minimum << std::endl;
       flag = 1;
    }

    // Return maximum of intensity
    float maximumResult = filter->GetMaximum();
    std::cout << "The Maximum intensity value is : " << maximumResult << std::endl;

    if(maximumResult != maximum)
    {
       std::cout << "Maximum Value is wrong : " << maximumResult ;
       std::cout << " != " << maximum << std::endl;
       flag = 2;
    }

    // Return results of test
    if (flag != 0) {
        std::cout << "*** Some tests failed" << std::endl;
        return flag; }
    else {
        std::cout << "All tests successfully passed" << std::endl;
        return 0; }

}

<commit_msg>ENH: added progress checking.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkMinimumMaximumImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkMinimumMaximumImageFilter.h"
#include "itkSize.h"
#include "itkFilterWatcher.h"

typedef itk::Size<3>                                  SizeType;
typedef itk::Image<float, 3>                  ImageType;
typedef itk::MinimumMaximumImageFilter<ImageType>  MinMaxFilterType;

/* Define the image size and physical coordinates */
SizeType size = {{20, 20, 20}};
double origin [3] = { 0.0, 0.0, 0.0};
double spacing[3] = { 1, 1 , 1};

int
itkMinimumMaximumImageFilterTest(int , char *[] )
{
    int flag = 0;           /* Did this test program work? */

    std::cout << "Testing Minimum and Maximum Image Calulator:\n";

    // Allocate a simple test image
    ImageType::Pointer image = ImageType::New();
    ImageType::RegionType region;
    region.SetSize(size);
    image->SetLargestPossibleRegion(region);
    image->SetRequestedRegion(region);
    image->SetBufferedRegion(region);
    image->Allocate();

    // Set origin and spacing of physical coordinates
    image->SetOrigin(origin);
    image->SetSpacing(spacing);

    float minimum = -52;
    float maximum = -10;

    // Initialize the image contents with the minimum value
    itk::Index<3> index;
    for (int slice = 0; slice < 20; slice++) {
        index[2] = slice;
        for (int row = 0; row <20; row++) {
            index[1] = row;
            for (int col = 0; col < 20; col++) {
                index[0] = col;
                image->SetPixel(index, minimum);
            }
        }
    }

    // Set voxel (10,10,10) to maximum value
    index[0] = 10;
    index[1] = 10;
    index[2] = 10;
    image->SetPixel(index, maximum);

    // Create and initialize the filter
    MinMaxFilterType::Pointer filter = MinMaxFilterType::New();
    FilterWatcher watcher(filter);

    filter->SetInput(image);
    filter->Update();

    // Return minimum of intensity
    float minimumResult = filter->GetMinimum();
    std::cout << "The Minimum intensity value is : " << minimumResult << std::endl;

    if(minimumResult != minimum)
    {
       std::cout << "Minimum Value is wrong : " << minimumResult ;
       std::cout << " != " << minimum << std::endl;
       flag = 1;
    }

    // Return maximum of intensity
    float maximumResult = filter->GetMaximum();
    std::cout << "The Maximum intensity value is : " << maximumResult << std::endl;

    if(maximumResult != maximum)
    {
       std::cout << "Maximum Value is wrong : " << maximumResult ;
       std::cout << " != " << maximum << std::endl;
       flag = 2;
    }

    // Return results of test
    if (flag != 0) {
        std::cout << "*** Some tests failed" << std::endl;
        return flag; }
    else {
        std::cout << "All tests successfully passed" << std::endl;
        return 0; }

}

<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/app/xwalk_main_delegate.h"

#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "xwalk/runtime/browser/xwalk_content_browser_client.h"
#include "xwalk/runtime/browser/ui/taskbar_util.h"
#include "xwalk/runtime/common/paths_mac.h"
#include "xwalk/runtime/common/xwalk_paths.h"
#include "xwalk/runtime/renderer/xwalk_content_renderer_client.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"

namespace xwalk {

XWalkMainDelegate::XWalkMainDelegate()
    : content_client_(new XWalkContentClient) {
}

XWalkMainDelegate::~XWalkMainDelegate() {
  browser_client_.reset();
  renderer_client_.reset();
  content_client_.reset();
}

bool XWalkMainDelegate::BasicStartupComplete(int* exit_code) {
  logging::InitLogging(logging::LoggingSettings());
  SetContentClient(content_client_.get());
#if defined(OS_WIN)
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  std::string process_type =
          command_line->GetSwitchValueASCII(switches::kProcessType);
  // Only set the id for browser process
  if (process_type.empty())
    SetTaskbarGroupIdForProcess();
#endif
  return false;
}

void XWalkMainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX)
  OverrideFrameworkBundlePath();
  OverrideChildProcessPath();
#endif  // OS_MACOSX

  RegisterPathProvider();
  InitializeResourceBundle();
}

int XWalkMainDelegate::RunProcess(const std::string& process_type,
    const content::MainFunctionParams& main_function_params) {
  // Tell content to use default process main entries by returning -1.
  return -1;
}

// static
void XWalkMainDelegate::InitializeResourceBundle() {
  base::FilePath pak_file;
#if defined(OS_MACOSX)
  pak_file = GetResourcesPakFilePath();
#else
  base::FilePath pak_dir;
  PathService::Get(base::DIR_MODULE, &pak_dir);
  DCHECK(!pak_dir.empty());

  pak_file = pak_dir.Append(FILE_PATH_LITERAL("xwalk.pak"));
#endif
  ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
}

content::ContentBrowserClient* XWalkMainDelegate::CreateContentBrowserClient() {
  browser_client_.reset(new XWalkContentBrowserClient);
  return browser_client_.get();
}

content::ContentRendererClient*
    XWalkMainDelegate::CreateContentRendererClient() {
  renderer_client_.reset(new XWalkContentRendererClient);
  return renderer_client_.get();
}

}  // namespace xwalk
<commit_msg>Fix windows functionality after rebase to 29<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/app/xwalk_main_delegate.h"

#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "xwalk/runtime/browser/xwalk_content_browser_client.h"
#include "xwalk/runtime/browser/ui/taskbar_util.h"
#include "xwalk/runtime/common/paths_mac.h"
#include "xwalk/runtime/common/xwalk_paths.h"
#include "xwalk/runtime/renderer/xwalk_content_renderer_client.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"

namespace xwalk {

XWalkMainDelegate::XWalkMainDelegate()
    : content_client_(new XWalkContentClient) {
}

XWalkMainDelegate::~XWalkMainDelegate() {
  browser_client_.reset();
  renderer_client_.reset();
  content_client_.reset();
}

bool XWalkMainDelegate::BasicStartupComplete(int* exit_code) {
  logging::LoggingSettings loggingSettings;
  loggingSettings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
  logging::InitLogging(loggingSettings);
  SetContentClient(content_client_.get());
#if defined(OS_WIN)
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  std::string process_type =
          command_line->GetSwitchValueASCII(switches::kProcessType);
  // Only set the id for browser process
  if (process_type.empty())
    SetTaskbarGroupIdForProcess();
#endif
  return false;
}

void XWalkMainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX)
  OverrideFrameworkBundlePath();
  OverrideChildProcessPath();
#endif  // OS_MACOSX

  RegisterPathProvider();
  InitializeResourceBundle();
}

int XWalkMainDelegate::RunProcess(const std::string& process_type,
    const content::MainFunctionParams& main_function_params) {
  // Tell content to use default process main entries by returning -1.
  return -1;
}

// static
void XWalkMainDelegate::InitializeResourceBundle() {
  base::FilePath pak_file;
#if defined(OS_MACOSX)
  pak_file = GetResourcesPakFilePath();
#else
  base::FilePath pak_dir;
  PathService::Get(base::DIR_MODULE, &pak_dir);
  DCHECK(!pak_dir.empty());

  pak_file = pak_dir.Append(FILE_PATH_LITERAL("xwalk.pak"));
#endif
  ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
}

content::ContentBrowserClient* XWalkMainDelegate::CreateContentBrowserClient() {
  browser_client_.reset(new XWalkContentBrowserClient);
  return browser_client_.get();
}

content::ContentRendererClient*
    XWalkMainDelegate::CreateContentRendererClient() {
  renderer_client_.reset(new XWalkContentRendererClient);
  return renderer_client_.get();
}

}  // namespace xwalk
<|endoftext|>


<commit_before>/*
  ACE.CPP

  Second-level plugin module for FAR Manager 1.70 and MultiArc plugin

  Copyright (c) 1996-2000 Eugene Roshal
  Copyrigth (c) 2000-2001 FAR group
*/
/* $Revision: 1.01 20.05.2001 $ */

#include <windows.h>
#include <string.h>
#include <dos.h>
#include <malloc.h>
#include <memory.h>
#include "plugin.hpp"
#include "fmt.hpp"

#if defined(__BORLANDC__)
  #pragma option -a1
#elif defined(__GNUC__) || (defined(__WATCOMC__) && (__WATCOMC__ < 1100)) || defined(__LCC__)
  #pragma pack(1)
  #if defined(__LCC__)
    #define _export __declspec(dllexport)
  #endif
#else
  #pragma pack(push,1)
  #if _MSC_VER
    #define _export
  #endif
#endif

//#define CALC_CRC

static struct OSIDType{
  BYTE Type;
  char Name[15];
} OSID[]={
  {0,"MS-DOS"},   {1,"OS/2"},     {2,"Win32"},
  {3,"Unix"},     {4,"MAC-OS"},   {5,"Win NT"},
  {6,"Primos"},   {7,"APPLE GS"}, {8,"ATARI"},
  {9,"VAX VMS"},  {10,"AMIGA"},   {11,"NEXT"},
};

struct ACEHEADER
{
  WORD  CRC16;        // CRC16 over block
  WORD  HeaderSize;   // size of the block(from HeaderType)
  BYTE  HeaderType;   // archive header type is 0
  WORD  HeaderFlags;
  BYTE  Signature[7]; // '**ACE**'
  BYTE  VerExtract;   // version needed to extract archive
  BYTE  VerCreate;    // version used to create the archive
  BYTE  Host;         // HOST-OS for ACE used to create the archive
  BYTE  VolumeNum;    // which volume of a multi-volume-archive is it?
  DWORD AcrTime;      // date and time in MS-DOS format
  BYTE  Reserved[8];  // 8 bytes reserved for the future
};

static HANDLE ArcHandle;
static DWORD NextPosition,FileSize,SFXSize;
static struct ACEHEADER MainHeader;
int HostOS=0, UnpVer=0;

#if defined(CALC_CRC)
#define CRCPOLY 0xEDB88320
#define CRC_MASK 0xFFFFFFFF

static unsigned crctable[256];
static BOOL CRCTableCreated=FALSE;

static void make_crctable(void)
{
  unsigned r,i,j;
  for (i=0;i<=255;i++)
  {
    for (r=i,j=8;j;j--)
      r=(r&1)?(r>>1)^CRCPOLY:(r>>1);
    crctable[i] = r;
  }
  CRCTableCreated=TRUE;
}

static DWORD getcrc(DWORD crc,BYTE *addr,int len)
{
  if(!CRCTableCreated) make_crctable();
  while (len--)
    crc=crctable[(BYTE)crc^(*addr++)]^(crc>>8);
  return(crc);
}
#endif

BOOL WINAPI _export IsArchive(const char *Name,const unsigned char *Data,int DataSize)
{
  for (int I=0;I<(int)(DataSize-sizeof(struct ACEHEADER));I++)
  {
    const unsigned char *D=Data+I;
    if (D[0]=='*' && D[1]=='*' && D[2]=='A' && D[3]=='C' && D[4]=='E' && D[5]=='*' && D[6]=='*' )
    {
      struct ACEHEADER *Header=(struct ACEHEADER *)(Data+I-7);
#if defined(CALC_CRC)
      DWORD crc=CRC_MASK;
      crc=getcrc(crc,&Header->HeaderType,Header->HeaderSize);
#endif
      if (Header->HeaderType == 0
#if defined(CALC_CRC)
          && LOWORD(crc) == LOWORD(Header->CRC16)
#endif
         )
      {
        SFXSize=NextPosition=I-7;
        return(TRUE);
      }
    }
  }
  return(FALSE);
}

BOOL WINAPI _export OpenArchive(const char *Name,int *Type)
{
  DWORD ReadSize;
  int I;

  ArcHandle=CreateFile(Name,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,
                       NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);
  if (ArcHandle==INVALID_HANDLE_VALUE)
    return(FALSE);

  *Type=0;

  FileSize=GetFileSize(ArcHandle,NULL);

  SetFilePointer(ArcHandle,NextPosition,NULL,FILE_BEGIN);
  if (!ReadFile(ArcHandle,&MainHeader,sizeof(MainHeader),&ReadSize,NULL) ||
      ReadSize!=sizeof(MainHeader))
  {
    CloseHandle(ArcHandle);
    return(FALSE);
  }

  NextPosition=SFXSize+MainHeader.HeaderSize+sizeof(WORD)*2;
  SetFilePointer(ArcHandle,NextPosition,NULL,FILE_BEGIN);

  for(I=0; I < sizeof(OSID)/sizeof(OSID[0]); ++I)
    if(OSID[I].Type == MainHeader.Host)
    {
      HostOS=I;
      break;
    }

  UnpVer=(MainHeader.VerExtract/10)*256+(MainHeader.VerExtract%10);

  return(TRUE);
}

int WINAPI _export GetArcItem(struct PluginPanelItem *Item,struct ArcItemInfo *Info)
{
  struct ACEHEADERBLOCK
  {
    WORD  CRC16;
    WORD  HeaderSize;
  } Block;
  HANDLE hHeap=GetProcessHeap();

  DWORD ReadSize;
  BYTE *TempBuf;

  while(1)
  {
    NextPosition=SetFilePointer(ArcHandle,NextPosition,NULL,FILE_BEGIN);
    if (NextPosition==0xFFFFFFFF)
      return(GETARC_READERROR);

    if (NextPosition>FileSize)
      return(GETARC_UNEXPEOF);

    if (!ReadFile(ArcHandle,&Block,sizeof(Block),&ReadSize,NULL))
      return(GETARC_READERROR);

    if (!ReadSize || !Block.HeaderSize) //???
      return(GETARC_EOF);

    TempBuf=(BYTE*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, Block.HeaderSize);
    if(!TempBuf)
      return(GETARC_READERROR);

    if (!ReadFile(ArcHandle,TempBuf,Block.HeaderSize,&ReadSize,NULL))
    {
      HeapFree(hHeap,0,TempBuf);
      return(GETARC_READERROR);
    }

    if (ReadSize==0 || Block.HeaderSize != ReadSize)
    {
      HeapFree(hHeap,0,TempBuf);
      return(GETARC_EOF);
    }

#if defined(CALC_CRC)
    DWORD crc=CRC_MASK;
    crc=getcrc(crc,TempBuf,Block.HeaderSize);
    if (LOWORD(crc) != LOWORD(Block.CRC16))
    {
      HeapFree(hHeap,0,TempBuf);
      return(GETARC_BROKEN);
    }
#endif

    NextPosition+=sizeof(Block)+Block.HeaderSize;

    if(*TempBuf == 1) // File block
    {
      struct ACEHEADERFILE
      {
        BYTE  HeaderType;
        WORD  HeaderFlags;
        DWORD PackSize;
        DWORD UnpSize;
        WORD  FTime;         // File Time an Date Stamp
        WORD  FDate;         // File Time an Date Stamp
        DWORD FileAttr;
        DWORD CRC32;
        WORD  TechInfo;
        WORD  DictSize;     //????
        WORD  Reserved;
        WORD  FileNameSize;
        char  FileName[1];
      } *FileHeader;
      FileHeader=(struct ACEHEADERFILE*)TempBuf;
      if(FileHeader->HeaderFlags&1)
      {
        Item->FindData.dwFileAttributes=FileHeader->FileAttr;
        if(FileHeader->FileNameSize)
          memcpy(Item->FindData.cFileName,FileHeader->FileName,FileHeader->FileNameSize);
        Item->FindData.cFileName[FileHeader->FileNameSize]=0;
        Item->FindData.nFileSizeLow=FileHeader->UnpSize;
        Item->FindData.nFileSizeHigh=0;
        Item->PackSize=FileHeader->PackSize;
        FILETIME lft;
        DosDateTimeToFileTime(FileHeader->FDate,FileHeader->FTime,&lft);
        LocalFileTimeToFileTime(&lft,&Item->FindData.ftLastWriteTime);

        Info->Solid=FileHeader->HeaderFlags&(1<<15)?1:0;
        Info->Encrypted=FileHeader->HeaderFlags&(1<<14)?1:0;
        Info->Comment=FileHeader->HeaderFlags&2?1:0;
        Info->UnpVer=UnpVer;
        //?????
        Info->DictSize=1<<FileHeader->DictSize;
        //?????
        strcpy(Info->HostOS,OSID[HostOS].Name);

        NextPosition+=FileHeader->PackSize;
        break;
      }
    }
    struct ACERECORDS
    {
      BYTE  HeaderType;    // header type of recovery records is 2
      WORD  HeaderFlags;   // Bit 0   1 (RecSize field present)
      DWORD RecSize;
    } *RecHeader;

    RecHeader=(struct ACERECORDS*)TempBuf;
    if(RecHeader->HeaderFlags&1)
      NextPosition+=RecHeader->RecSize;
    HeapFree(hHeap,0,TempBuf);
  }
  HeapFree(hHeap,0,TempBuf);
  return(GETARC_SUCCESS);
}

BOOL WINAPI _export CloseArchive(struct ArcInfo *Info)
{
  if(Info)
  {
    Info->SFXSize=SFXSize;
    Info->Volume=MainHeader.HeaderFlags&(1<<11)?1:0;
    Info->Comment=MainHeader.HeaderFlags&2?1:0;
    Info->Recovery=MainHeader.HeaderFlags&(1<<13)?1:0;
    Info->Lock=MainHeader.HeaderFlags&(1<<14)?1:0;
    Info->Flags|=MainHeader.HeaderFlags&(1<<12)?AF_AVPRESENT:0;
  }
  return(CloseHandle(ArcHandle));
}

DWORD WINAPI _export GetSFXPos(void)
{
  return SFXSize;
}

BOOL WINAPI _export GetFormatName(int Type,char *FormatName,char *DefaultExt)
{
  if (Type==0)
  {
    strcpy(FormatName,"ACE");
    strcpy(DefaultExt,"ACE");
    return(TRUE);
  }
  return(FALSE);
}

BOOL WINAPI _export GetDefaultCommands(int Type,int Command,char *Dest)
{
  if (Type==0)
  {
    static char *Commands[]={
      "ace32 x {-p%%P} -y -c- -std {%%S} %%A @%%LN",            // Extract
      "ace32 e -av- {-p%%P} -y -c- -std {%%S} %%A @%%LN",       // ExtractWithoutPath
      "ace32 t -y {-p%%P} -c- -std {%%S} %%A",                  // Test
      "ace32 d -y -std {-t%%W} {%%S} %%A @%%LN",                // Delete
      "ace32 cm -y -std {-t%%W} {%%S} %%A",                     // Comment
      "ace32 cf -y -std {-t%%W} {%%S} %%A {@%%LN}",             // CommentFiles
      "ace32 s -y -std {%%S} %%A",                              // SFX
      "ace32 k -y -std {%%S} %%A",                              // Lock
      "ace32 rr -y -std {%%S} %%A",                             // Protect
      "ace32 r -y -std {%%S} %%A",                              // Recover
      "ace32 a -c2 -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN",    // Add
      "ace32 m -c2 -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN",    // Move
      "ace32 a -c2 -r -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN", // AddRecurse
      "ace32 m -c2 -r -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN", // MoveRecurse
      "*.*"
    };
    if (Command<sizeof(Commands)/sizeof(Commands[0]))
    {
      strcpy(Dest,Commands[Command]);
      return(TRUE);
    }
  }
  return(FALSE);
}
<commit_msg>Multiarc patch 00028.ace.cpp Дата              : 31.05.2001 Сделал            : Valentin Skirdin Описание          : ACE Измененные файлы  : ace.cpp Новые файлы       : Удаленные файлы   : Состав            : 00028.ace.cpp.txt                     ace.cpp.28.diff Основан на патче  : 27 Дополнение        :<commit_after>/*
  ACE.CPP

  Second-level plugin module for FAR Manager 1.70 and MultiArc plugin

  Copyright (c) 1996-2000 Eugene Roshal
  Copyrigth (c) 2000-2001 FAR group
*/
/* $Revision: 1.02 31.05.2001 $ */

#include <windows.h>
#include <string.h>
#include <dos.h>
#include <malloc.h>
#include <memory.h>
#include "plugin.hpp"
#include "fmt.hpp"

#if defined(__BORLANDC__)
  #pragma option -a1
#elif defined(__GNUC__) || (defined(__WATCOMC__) && (__WATCOMC__ < 1100)) || defined(__LCC__)
  #pragma pack(1)
  #if defined(__LCC__)
    #define _export __declspec(dllexport)
  #endif
#else
  #pragma pack(push,1)
  #if _MSC_VER
    #define _export
  #endif
#endif

//#define CALC_CRC

static struct OSIDType{
  BYTE Type;
  char Name[15];
} OSID[]={
  {0,"MS-DOS"},   {1,"OS/2"},     {2,"Win32"},
  {3,"Unix"},     {4,"MAC-OS"},   {5,"Win NT"},
  {6,"Primos"},   {7,"APPLE GS"}, {8,"ATARI"},
  {9,"VAX VMS"},  {10,"AMIGA"},   {11,"NEXT"},
};

struct ACEHEADER
{
  WORD  CRC16;        // CRC16 over block
  WORD  HeaderSize;   // size of the block(from HeaderType)
  BYTE  HeaderType;   // archive header type is 0
  WORD  HeaderFlags;
  BYTE  Signature[7]; // '**ACE**'
  BYTE  VerExtract;   // version needed to extract archive
  BYTE  VerCreate;    // version used to create the archive
  BYTE  Host;         // HOST-OS for ACE used to create the archive
  BYTE  VolumeNum;    // which volume of a multi-volume-archive is it?
  DWORD AcrTime;      // date and time in MS-DOS format
  BYTE  Reserved[8];  // 8 bytes reserved for the future
};

static HANDLE ArcHandle;
static DWORD NextPosition,FileSize,SFXSize;
static struct ACEHEADER MainHeader;
int HostOS=0, UnpVer=0;

#if defined(CALC_CRC)
#define CRCPOLY 0xEDB88320
#define CRC_MASK 0xFFFFFFFF

static unsigned crctable[256];
static BOOL CRCTableCreated=FALSE;

static void make_crctable(void)
{
  unsigned r,i,j;
  for (i=0;i<=255;i++)
  {
    for (r=i,j=8;j;j--)
      r=(r&1)?(r>>1)^CRCPOLY:(r>>1);
    crctable[i] = r;
  }
  CRCTableCreated=TRUE;
}

static DWORD getcrc(DWORD crc,BYTE *addr,int len)
{
  if(!CRCTableCreated) make_crctable();
  while (len--)
    crc=crctable[(BYTE)crc^(*addr++)]^(crc>>8);
  return(crc);
}
#endif

BOOL WINAPI _export IsArchive(const char *Name,const unsigned char *Data,int DataSize)
{
  for (int I=0;I<(int)(DataSize-sizeof(struct ACEHEADER));I++)
  {
    const unsigned char *D=Data+I;
    if (D[0]=='*' && D[1]=='*' && D[2]=='A' && D[3]=='C' && D[4]=='E' && D[5]=='*' && D[6]=='*' )
    {
      struct ACEHEADER *Header=(struct ACEHEADER *)(Data+I-7);
#if defined(CALC_CRC)
      DWORD crc=CRC_MASK;
      crc=getcrc(crc,&Header->HeaderType,Header->HeaderSize);
#endif
      if (Header->HeaderType == 0
#if defined(CALC_CRC)
          && LOWORD(crc) == LOWORD(Header->CRC16)
#endif
         )
      {
        SFXSize=I-7;
        return(TRUE);
      }
    }
  }
  return(FALSE);
}

BOOL WINAPI _export OpenArchive(const char *Name,int *Type)
{
  DWORD ReadSize;
  int I;

  ArcHandle=CreateFile(Name,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,
                       NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);
  if (ArcHandle==INVALID_HANDLE_VALUE)
    return(FALSE);

  *Type=0;

  FileSize=GetFileSize(ArcHandle,NULL);
  NextPosition=SFXSize;

  SetFilePointer(ArcHandle,NextPosition,NULL,FILE_BEGIN);
  if (!ReadFile(ArcHandle,&MainHeader,sizeof(MainHeader),&ReadSize,NULL) ||
      ReadSize!=sizeof(MainHeader))
  {
    CloseHandle(ArcHandle);
    return(FALSE);
  }

  NextPosition=SFXSize+MainHeader.HeaderSize+sizeof(WORD)*2;
  SetFilePointer(ArcHandle,NextPosition,NULL,FILE_BEGIN);

  for(I=0; I < sizeof(OSID)/sizeof(OSID[0]); ++I)
    if(OSID[I].Type == MainHeader.Host)
    {
      HostOS=I;
      break;
    }

  UnpVer=(MainHeader.VerExtract/10)*256+(MainHeader.VerExtract%10);

  return(TRUE);
}

int WINAPI _export GetArcItem(struct PluginPanelItem *Item,struct ArcItemInfo *Info)
{
  struct ACEHEADERBLOCK
  {
    WORD  CRC16;
    WORD  HeaderSize;
  } Block;
  HANDLE hHeap=GetProcessHeap();

  DWORD ReadSize;
  BYTE *TempBuf;

  while(1)
  {
    NextPosition=SetFilePointer(ArcHandle,NextPosition,NULL,FILE_BEGIN);
    if (NextPosition==0xFFFFFFFF)
      return(GETARC_READERROR);

    if (NextPosition>FileSize)
      return(GETARC_UNEXPEOF);

    if (!ReadFile(ArcHandle,&Block,sizeof(Block),&ReadSize,NULL))
      return(GETARC_READERROR);

    if (!ReadSize || !Block.HeaderSize) //???
      return(GETARC_EOF);

    TempBuf=(BYTE*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, Block.HeaderSize);
    if(!TempBuf)
      return(GETARC_READERROR);

    if (!ReadFile(ArcHandle,TempBuf,Block.HeaderSize,&ReadSize,NULL))
    {
      HeapFree(hHeap,0,TempBuf);
      return(GETARC_READERROR);
    }

    if (ReadSize==0 || Block.HeaderSize != ReadSize)
    {
      HeapFree(hHeap,0,TempBuf);
      return(GETARC_EOF);
    }

#if defined(CALC_CRC)
    DWORD crc=CRC_MASK;
    crc=getcrc(crc,TempBuf,Block.HeaderSize);
    if (LOWORD(crc) != LOWORD(Block.CRC16))
    {
      HeapFree(hHeap,0,TempBuf);
      return(GETARC_BROKEN);
    }
#endif

    NextPosition+=sizeof(Block)+Block.HeaderSize;

    if(*TempBuf == 1) // File block
    {
      struct ACEHEADERFILE
      {
        BYTE  HeaderType;
        WORD  HeaderFlags;
        DWORD PackSize;
        DWORD UnpSize;
        WORD  FTime;         // File Time an Date Stamp
        WORD  FDate;         // File Time an Date Stamp
        DWORD FileAttr;
        DWORD CRC32;
        WORD  TechInfo;
        WORD  DictSize;     //????
        WORD  Reserved;
        WORD  FileNameSize;
        char  FileName[1];
      } *FileHeader;
      FileHeader=(struct ACEHEADERFILE*)TempBuf;
      if(FileHeader->HeaderFlags&1)
      {
        Item->FindData.dwFileAttributes=FileHeader->FileAttr;
        if(FileHeader->FileNameSize)
          memcpy(Item->FindData.cFileName,FileHeader->FileName,FileHeader->FileNameSize);
        Item->FindData.cFileName[FileHeader->FileNameSize]=0;
        Item->FindData.nFileSizeLow=FileHeader->UnpSize;
        Item->FindData.nFileSizeHigh=0;
        Item->PackSize=FileHeader->PackSize;
        FILETIME lft;
        DosDateTimeToFileTime(FileHeader->FDate,FileHeader->FTime,&lft);
        LocalFileTimeToFileTime(&lft,&Item->FindData.ftLastWriteTime);

        Info->Solid=FileHeader->HeaderFlags&(1<<15)?1:0;
        Info->Encrypted=FileHeader->HeaderFlags&(1<<14)?1:0;
        Info->Comment=FileHeader->HeaderFlags&2?1:0;
        Info->UnpVer=UnpVer;
        //?????
        Info->DictSize=1<<FileHeader->DictSize;
        //?????
        strcpy(Info->HostOS,OSID[HostOS].Name);

        NextPosition+=FileHeader->PackSize;
        break;
      }
    }
    struct ACERECORDS
    {
      BYTE  HeaderType;    // header type of recovery records is 2
      WORD  HeaderFlags;   // Bit 0   1 (RecSize field present)
      DWORD RecSize;
    } *RecHeader;

    RecHeader=(struct ACERECORDS*)TempBuf;
    if(RecHeader->HeaderFlags&1)
      NextPosition+=RecHeader->RecSize;
    HeapFree(hHeap,0,TempBuf);
  }
  HeapFree(hHeap,0,TempBuf);
  return(GETARC_SUCCESS);
}

BOOL WINAPI _export CloseArchive(struct ArcInfo *Info)
{
  if(Info)
  {
    Info->SFXSize=SFXSize;
    Info->Volume=MainHeader.HeaderFlags&(1<<11)?1:0;
    Info->Comment=MainHeader.HeaderFlags&2?1:0;
    Info->Recovery=MainHeader.HeaderFlags&(1<<13)?1:0;
    Info->Lock=MainHeader.HeaderFlags&(1<<14)?1:0;
    Info->Flags|=MainHeader.HeaderFlags&(1<<12)?AF_AVPRESENT:0;
  }
  return(CloseHandle(ArcHandle));
}

DWORD WINAPI _export GetSFXPos(void)
{
  return SFXSize;
}

BOOL WINAPI _export GetFormatName(int Type,char *FormatName,char *DefaultExt)
{
  if (Type==0)
  {
    strcpy(FormatName,"ACE");
    strcpy(DefaultExt,"ACE");
    return(TRUE);
  }
  return(FALSE);
}

BOOL WINAPI _export GetDefaultCommands(int Type,int Command,char *Dest)
{
  if (Type==0)
  {
    static char *Commands[]={
      "ace32 x {-p%%P} -y -c- -std {%%S} %%A @%%LN",            // Extract
      "ace32 e -av- {-p%%P} -y -c- -std {%%S} %%A @%%LN",       // ExtractWithoutPath
      "ace32 t -y {-p%%P} -c- -std {%%S} %%A",                  // Test
      "ace32 d -y -std {-t%%W} {%%S} %%A @%%LN",                // Delete
      "ace32 cm -y -std {-t%%W} {%%S} %%A",                     // Comment
      "ace32 cf -y -std {-t%%W} {%%S} %%A {@%%LN}",             // CommentFiles
      "ace32 s -y -std {%%S} %%A",                              // SFX
      "ace32 k -y -std {%%S} %%A",                              // Lock
      "ace32 rr -y -std {%%S} %%A",                             // Protect
      "ace32 r -y -std {%%S} %%A",                              // Recover
      "ace32 a -c2 -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN",    // Add
      "ace32 m -c2 -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN",    // Move
      "ace32 a -c2 -r -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN", // AddRecurse
      "ace32 m -c2 -r -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN", // MoveRecurse
      "*.*"
    };
    if (Command<sizeof(Commands)/sizeof(Commands[0]))
    {
      strcpy(Dest,Commands[Command]);
      return(TRUE);
    }
  }
  return(FALSE);
}
<|endoftext|>


<commit_before>#include "musictransformwidget.h"
#include "ui_musictransformwidget.h"
#include <QFileDialog>
#include <QProcess>
#include <QMovie>

#ifdef Q_OS_WIN
    #include <windows.h>
    #include <mmsystem.h>
    #pragma comment(lib,"winmm.lib")
#endif

MusicTransformWidget::MusicTransformWidget(QWidget *parent)
        : MusicMoveDialogAbstract(parent),m_movie(NULL),
        ui(new Ui::MusicTransformWidget)
{
    ui->setupUi(this);
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter p(&bmp);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::black);
    p.drawRoundedRect(bmp.rect(),4,4);
    setMask(bmp);
    //set window radius

    m_process = new QProcess(this);
    ui->topTitleCloseButton->setIcon(QIcon(QPixmap(":/share/searchclosed")));
    ui->topTitleCloseButton->setStyleSheet(MusicObject::QToolButtonStyle);
    ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor));
    ui->topTitleCloseButton->setToolTip(tr("Close"));
    connect(ui->topTitleCloseButton,SIGNAL(clicked()),SLOT(close()));

    ui->inputButton->setStyleSheet(MusicObject::MusicSettingMainButton);
    ui->outputButton->setStyleSheet(MusicObject::MusicSettingMainButton);
    ui->formatCombo->setStyleSheet(MusicObject::MusicEqComboboxEditStyle);
    ui->kbpsCombo->setStyleSheet(MusicObject::MusicEqComboboxEditStyle);
    ui->hzCombo->setStyleSheet(MusicObject::MusicEqComboboxEditStyle);
    ui->msCombo->setStyleSheet(MusicObject::MusicEqComboboxEditStyle);
    ui->transformButton->setStyleSheet(MusicObject::MusicSettingMainButton);
    ui->inputLineEdit->setStyleSheet(MusicObject::MusicLoginEditStyle);
    ui->outputLineEdit->setStyleSheet(MusicObject::MusicLoginEditStyle);

    ui->inputButton->setCursor(QCursor(Qt::PointingHandCursor));
    ui->outputButton->setCursor(QCursor(Qt::PointingHandCursor));
    ui->transformButton->setCursor(QCursor(Qt::PointingHandCursor));

    connect(ui->inputButton,SIGNAL(clicked()),SLOT(initInputPath()));
    connect(ui->outputButton,SIGNAL(clicked()),SLOT(initOutputPath()));
    connect(ui->transformButton,SIGNAL(clicked()),SLOT(startTransform()));
    connect(m_process,SIGNAL(finished(int)),SLOT(transformFinish(int)));

    ui->folderBox->setStyleSheet(MusicObject::MusicSettingCheckButton);
    connect(ui->folderBox,SIGNAL(clicked(bool)),SLOT(folderBoxChecked(bool)));
    initControlParameter();

}

MusicTransformWidget::~MusicTransformWidget()
{
    delete m_movie;
    delete m_process;
    delete ui;
}

void MusicTransformWidget::initControlParameter()
{
    ui->formatCombo->addItems(QStringList()<<"MP3"<<"WAV"<<"WMA"
                              <<"OGG"<<"FLAC"<<"AC3"<<"AAC");
    ui->kbpsCombo->addItems(QStringList()<<"32"<<"48"<<"56"<<"64"<<"80"
                    <<"96"<<"112"<<"128"<<"192"<<"224"<<"256"<<"320");
    ui->hzCombo->addItems(QStringList()<<"8000"<<"12050"<<"16000"
                    <<"22050"<<"24000"<<"32000"<<"44100"<<"48000");
    ui->msCombo->addItems(QStringList()<<"Mono"<<"Stereo");

    ui->kbpsCombo->setCurrentIndex(7);
    ui->hzCombo->setCurrentIndex(6);
}

void MusicTransformWidget::initInputPath()
{
    QString path;
    if(!ui->folderBox->isChecked())
    {
        path =  QFileDialog::getOpenFileName(
                this, "" , "./",
                "Files (*.mp3 *.wav *.wma *.ogg *.flac *.ac3 *.aac)");
        if(path.isEmpty())
            return;
        ui->listWidget->addItem(QFontMetrics(font()).elidedText(path, Qt::ElideLeft,215));
        m_path<<path;
    }
    else
    {
        QFileDialog dialog(this);
        dialog.setFileMode(QFileDialog::Directory );
        dialog.setViewMode(QFileDialog::Detail);
        if(dialog.exec())
        {
            path = dialog.directory().absolutePath();
            QList<QFileInfo> file(dialog.directory().entryInfoList());
            for(int i=0; i<file.count(); ++i)
            {
                if(file[i].isFile())
                   m_path<<file[i].absoluteFilePath();
            }

//            ui->listWidget->addItems(m_path);
            for(int i=0; i<m_path.count(); ++i)
                ui->listWidget->addItem(QFontMetrics(font()).elidedText(m_path[i],
                                                                        Qt::ElideLeft,215));
        }
    }

    if(!path.isEmpty())
        ui->inputLineEdit->setText(path);
}

void MusicTransformWidget::initOutputPath()
{
    QString path =  QFileDialog::getExistingDirectory(this, "" , "./");
    if(!path.isEmpty())
        ui->outputLineEdit->setText(path);
}

QString MusicTransformWidget::getTransformSongName() const
{
    if(m_path.isEmpty())
        return QString();
    QString str = m_path[0];
    str.replace("\\","/");
    str = str.split('/').back().split('.').front();
    return str;
}

void MusicTransformWidget::transformFinish(int)
{
#ifdef Q_OS_WIN
    mciSendString(TEXT("close sound.wav"),NULL,0,NULL);
    mciSendString(TEXT("open  sound.wav"),NULL,0,NULL);
    mciSendString(TEXT("play  sound.wav"),NULL,0,NULL);
#endif
    m_path.removeAt(0);
    ui->listWidget->clear();
    if(!m_path.isEmpty())
    {
        for(int i=0; i<m_path.count(); ++i)
            ui->listWidget->addItem(QFontMetrics(font()).elidedText(m_path[i],
                                                                    Qt::ElideLeft,215));
        if(!processTransform(MAKE_TRANSFORM))
            return;
    }
    else
    {
        setCheckedControl(true);
        ui->loadingLabel->hide();
        delete m_movie;
        m_movie = NULL;
    }
}

bool MusicTransformWidget::processTransform(const QString& para)
{
    if(m_path.isEmpty())
        return false;

    QString in = m_path[0].trimmed();
    QString out = ui->outputLineEdit->text().trimmed();

    if(in.isEmpty() || out.isEmpty() )
        return false;

    if(ui->formatCombo->currentText() == "OGG")
        ui->msCombo->setCurrentIndex(1);

    qDebug()<<ui->formatCombo->currentText()
            <<ui->kbpsCombo->currentText()
            <<ui->hzCombo->currentText()
            <<QString::number(ui->msCombo->currentIndex() + 1);

    m_process->start(para, QStringList()<<"-i"<<in<<"-y"
                     <<"-ab"<<ui->kbpsCombo->currentText()+ "k"
                     <<"-ar"<<ui->hzCombo->currentText()
                     <<"-ac"<<QString::number(ui->msCombo->currentIndex()+1)
                     <<QString("%1/%2-Transed.%3").arg(out).arg(getTransformSongName())
                       .arg(ui->formatCombo->currentText().toLower()) );
    return true;
}

void MusicTransformWidget::startTransform()
{
    if(!QFile(MAKE_TRANSFORM).exists())
        return;

    if(!processTransform(MAKE_TRANSFORM))
        return;
    ///////////////////////////////////////////////////////////
    ui->loadingLabel->show();
    ui->loadingLabel->setMovie(m_movie = new QMovie(":/image/loading",QByteArray(),this));
    m_movie->start();
    setCheckedControl(false);
}

void MusicTransformWidget::folderBoxChecked(bool)
{
    ui->inputLineEdit->clear();
    ui->listWidget->clear();
    m_path.clear();
}

void MusicTransformWidget::setCheckedControl(bool enable)
{
    ui->inputButton->setEnabled(enable);
    ui->inputLineEdit->setEnabled(enable);
    ui->outputButton->setEnabled(enable);
    ui->outputLineEdit->setEnabled(enable);
    ui->formatCombo->setEnabled(enable);
    ui->kbpsCombo->setEnabled(enable);
    ui->hzCombo->setEnabled(enable);
    ui->msCombo->setEnabled(enable);
    ui->folderBox->setEnabled(enable);
    ui->transformButton->setEnabled(enable);
}
<commit_msg>changed the macro for msvc version[987521]<commit_after>#include "musictransformwidget.h"
#include "ui_musictransformwidget.h"
#include <QFileDialog>
#include <QProcess>
#include <QMovie>

#if defined Q_OS_WIN32 && defined _MSC_VER
    #include <windows.h>
    #include <mmsystem.h>
    #pragma comment(lib,"winmm.lib")
#endif

MusicTransformWidget::MusicTransformWidget(QWidget *parent)
        : MusicMoveDialogAbstract(parent),m_movie(NULL),
        ui(new Ui::MusicTransformWidget)
{
    ui->setupUi(this);
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter p(&bmp);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::black);
    p.drawRoundedRect(bmp.rect(),4,4);
    setMask(bmp);
    //set window radius

    m_process = new QProcess(this);
    ui->topTitleCloseButton->setIcon(QIcon(QPixmap(":/share/searchclosed")));
    ui->topTitleCloseButton->setStyleSheet(MusicObject::QToolButtonStyle);
    ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor));
    ui->topTitleCloseButton->setToolTip(tr("Close"));
    connect(ui->topTitleCloseButton,SIGNAL(clicked()),SLOT(close()));

    ui->inputButton->setStyleSheet(MusicObject::MusicSettingMainButton);
    ui->outputButton->setStyleSheet(MusicObject::MusicSettingMainButton);
    ui->formatCombo->setStyleSheet(MusicObject::MusicEqComboboxEditStyle);
    ui->kbpsCombo->setStyleSheet(MusicObject::MusicEqComboboxEditStyle);
    ui->hzCombo->setStyleSheet(MusicObject::MusicEqComboboxEditStyle);
    ui->msCombo->setStyleSheet(MusicObject::MusicEqComboboxEditStyle);
    ui->transformButton->setStyleSheet(MusicObject::MusicSettingMainButton);
    ui->inputLineEdit->setStyleSheet(MusicObject::MusicLoginEditStyle);
    ui->outputLineEdit->setStyleSheet(MusicObject::MusicLoginEditStyle);

    ui->inputButton->setCursor(QCursor(Qt::PointingHandCursor));
    ui->outputButton->setCursor(QCursor(Qt::PointingHandCursor));
    ui->transformButton->setCursor(QCursor(Qt::PointingHandCursor));

    connect(ui->inputButton,SIGNAL(clicked()),SLOT(initInputPath()));
    connect(ui->outputButton,SIGNAL(clicked()),SLOT(initOutputPath()));
    connect(ui->transformButton,SIGNAL(clicked()),SLOT(startTransform()));
    connect(m_process,SIGNAL(finished(int)),SLOT(transformFinish(int)));

    ui->folderBox->setStyleSheet(MusicObject::MusicSettingCheckButton);
    connect(ui->folderBox,SIGNAL(clicked(bool)),SLOT(folderBoxChecked(bool)));
    initControlParameter();

}

MusicTransformWidget::~MusicTransformWidget()
{
    delete m_movie;
    delete m_process;
    delete ui;
}

void MusicTransformWidget::initControlParameter()
{
    ui->formatCombo->addItems(QStringList()<<"MP3"<<"WAV"<<"WMA"
                              <<"OGG"<<"FLAC"<<"AC3"<<"AAC");
    ui->kbpsCombo->addItems(QStringList()<<"32"<<"48"<<"56"<<"64"<<"80"
                    <<"96"<<"112"<<"128"<<"192"<<"224"<<"256"<<"320");
    ui->hzCombo->addItems(QStringList()<<"8000"<<"12050"<<"16000"
                    <<"22050"<<"24000"<<"32000"<<"44100"<<"48000");
    ui->msCombo->addItems(QStringList()<<"Mono"<<"Stereo");

    ui->kbpsCombo->setCurrentIndex(7);
    ui->hzCombo->setCurrentIndex(6);
}

void MusicTransformWidget::initInputPath()
{
    QString path;
    if(!ui->folderBox->isChecked())
    {
        path =  QFileDialog::getOpenFileName(
                this, "" , "./",
                "Files (*.mp3 *.wav *.wma *.ogg *.flac *.ac3 *.aac)");
        if(path.isEmpty())
            return;
        ui->listWidget->addItem(QFontMetrics(font()).elidedText(path, Qt::ElideLeft,215));
        m_path<<path;
    }
    else
    {
        QFileDialog dialog(this);
        dialog.setFileMode(QFileDialog::Directory );
        dialog.setViewMode(QFileDialog::Detail);
        if(dialog.exec())
        {
            path = dialog.directory().absolutePath();
            QList<QFileInfo> file(dialog.directory().entryInfoList());
            for(int i=0; i<file.count(); ++i)
            {
                if(file[i].isFile())
                   m_path<<file[i].absoluteFilePath();
            }

//            ui->listWidget->addItems(m_path);
            for(int i=0; i<m_path.count(); ++i)
                ui->listWidget->addItem(QFontMetrics(font()).elidedText(m_path[i],
                                                                        Qt::ElideLeft,215));
        }
    }

    if(!path.isEmpty())
        ui->inputLineEdit->setText(path);
}

void MusicTransformWidget::initOutputPath()
{
    QString path =  QFileDialog::getExistingDirectory(this, "" , "./");
    if(!path.isEmpty())
        ui->outputLineEdit->setText(path);
}

QString MusicTransformWidget::getTransformSongName() const
{
    if(m_path.isEmpty())
        return QString();
    QString str = m_path[0];
    str.replace("\\","/");
    str = str.split('/').back().split('.').front();
    return str;
}

void MusicTransformWidget::transformFinish(int)
{
#ifdef Q_OS_WIN
    mciSendString(TEXT("close sound.wav"),NULL,0,NULL);
    mciSendString(TEXT("open  sound.wav"),NULL,0,NULL);
    mciSendString(TEXT("play  sound.wav"),NULL,0,NULL);
#endif
    m_path.removeAt(0);
    ui->listWidget->clear();
    if(!m_path.isEmpty())
    {
        for(int i=0; i<m_path.count(); ++i)
            ui->listWidget->addItem(QFontMetrics(font()).elidedText(m_path[i],
                                                                    Qt::ElideLeft,215));
        if(!processTransform(MAKE_TRANSFORM))
            return;
    }
    else
    {
        setCheckedControl(true);
        ui->loadingLabel->hide();
        delete m_movie;
        m_movie = NULL;
    }
}

bool MusicTransformWidget::processTransform(const QString& para)
{
    if(m_path.isEmpty())
        return false;

    QString in = m_path[0].trimmed();
    QString out = ui->outputLineEdit->text().trimmed();

    if(in.isEmpty() || out.isEmpty() )
        return false;

    if(ui->formatCombo->currentText() == "OGG")
        ui->msCombo->setCurrentIndex(1);

    qDebug()<<ui->formatCombo->currentText()
            <<ui->kbpsCombo->currentText()
            <<ui->hzCombo->currentText()
            <<QString::number(ui->msCombo->currentIndex() + 1);

    m_process->start(para, QStringList()<<"-i"<<in<<"-y"
                     <<"-ab"<<ui->kbpsCombo->currentText()+ "k"
                     <<"-ar"<<ui->hzCombo->currentText()
                     <<"-ac"<<QString::number(ui->msCombo->currentIndex()+1)
                     <<QString("%1/%2-Transed.%3").arg(out).arg(getTransformSongName())
                       .arg(ui->formatCombo->currentText().toLower()) );
    return true;
}

void MusicTransformWidget::startTransform()
{
    if(!QFile(MAKE_TRANSFORM).exists())
        return;

    if(!processTransform(MAKE_TRANSFORM))
        return;
    ///////////////////////////////////////////////////////////
    ui->loadingLabel->show();
    ui->loadingLabel->setMovie(m_movie = new QMovie(":/image/loading",QByteArray(),this));
    m_movie->start();
    setCheckedControl(false);
}

void MusicTransformWidget::folderBoxChecked(bool)
{
    ui->inputLineEdit->clear();
    ui->listWidget->clear();
    m_path.clear();
}

void MusicTransformWidget::setCheckedControl(bool enable)
{
    ui->inputButton->setEnabled(enable);
    ui->inputLineEdit->setEnabled(enable);
    ui->outputButton->setEnabled(enable);
    ui->outputLineEdit->setEnabled(enable);
    ui->formatCombo->setEnabled(enable);
    ui->kbpsCombo->setEnabled(enable);
    ui->hzCombo->setEnabled(enable);
    ui->msCombo->setEnabled(enable);
    ui->folderBox->setEnabled(enable);
    ui->transformButton->setEnabled(enable);
}
<|endoftext|>


<commit_before>#include <armadillo>
#include <vector>
#include <set>
#include <boost/algorithm/cxx11/any_of.hpp>

using namespace arma;
using namespace std;

// matriz distancias

// nodoArbolInicial = rand()
// ListaNodosArbol = {nodoArbolInicial}

// Un NodoArbol sabe:
//  * El camino recorrido (vector<int>)
//  * El costo de ese camino
struct Camino {
    int ciudadFinal;
    vector<int> camino;
    double costoCamino;
};

bool operator<(const Camino& lhs, const Camino& rhs)
{
    return lhs.costoCamino < rhs.costoCamino;
}

class ArbolBusqueda {
public:
    ArbolBusqueda(string rutaArchivoDistancias);

    vector<int> hacerBusqueda();

private:
    set<Camino> listaCaminos;
    unsigned int cantidadCiudades;
    mat distancias;
};

ArbolBusqueda::ArbolBusqueda(string rutaArchivoDistancias)
{
    distancias.load(rutaArchivoDistancias);

    if (!distancias.is_square())
        throw runtime_error("La matriz leída no es cuadrada");

    cantidadCiudades = distancias.n_rows;

    Camino nodoInicial;
    nodoInicial.ciudadFinal = randi(1, distr_param(1, cantidadCiudades)).at(0);
    nodoInicial.camino.push_back(nodoInicial.ciudadFinal);
    nodoInicial.costoCamino = 0;

    listaCaminos.insert(nodoInicial);
}

vector<int> ArbolBusqueda::hacerBusqueda()
{
    while (!listaCaminos.empty()) {
        // bucle:
        //  1 - Saco el primer elemento de la lista
        //      Si no hay elementos, no encontré una solución
        Camino camino = *listaCaminos.begin();
        listaCaminos.erase(listaCaminos.begin());

        //  2 - Me fijo si es un estado objetivo
        //      Si es un estado objetivo, encontré la solución
        // El camino va a ser la solución si la cantidad de nodos es igual
        // a la cantidad de ciudades.
        if (camino.camino.size() == cantidadCiudades)
            return camino.camino;

        //  3 - Expando los vecinos a los que puede ir y los meto en ListaNodos Arbol
        //      Los nuevos Nodos son insertados para que lista quede ordenada por
        //      el costo de cada camino
        //      Si no hay nodos a expandir, no inserto nada
        vector<int> ciudadesCandidatas;
        for (unsigned int i = 1; i <= cantidadCiudades; ++i) {
            if (!boost::algorithm::any_of_equal(camino.camino, i))
                ciudadesCandidatas.push_back(i);
        }

        // Generar caminos nuevos
        for (int ciudad : ciudadesCandidatas) {
            Camino nuevoCamino{camino};
            nuevoCamino.ciudadFinal = ciudad;
            nuevoCamino.camino.push_back(ciudad);
            nuevoCamino.costoCamino += distancias.at(camino.ciudadFinal,
                                                     nuevoCamino.ciudadFinal);
        }
    }

    // Si se llegó hasta acá, es porque no se encontró una solución
    throw runtime_error("No se encontró una solución");
}
<commit_msg>Guia 4 - Ejercicio 3: Continuar implementación de costo_uniforme<commit_after>#include <armadillo>
#include <vector>
#include <set>
#include <boost/algorithm/cxx11/none_of.hpp>

using namespace arma;
using namespace std;

// matriz distancias

// nodoArbolInicial = rand()
// ListaNodosArbol = {nodoArbolInicial}

// Un NodoArbol sabe:
//  * El camino recorrido (vector<int>)
//  * El costo de ese camino
struct Camino {
    int ciudadFinal;
    vector<int> recorrido;
    double costoCamino;
};

bool operator<(const Camino& lhs, const Camino& rhs)
{
    return lhs.costoCamino < rhs.costoCamino;
}

class ArbolBusqueda {
public:
    ArbolBusqueda(string rutaArchivoDistancias);

    vector<int> hacerBusqueda();

private:
    set<Camino> listaCaminos;
    unsigned int cantidadCiudades;
    mat distancias;
};

ArbolBusqueda::ArbolBusqueda(string rutaArchivoDistancias)
{
    distancias.load(rutaArchivoDistancias);

    if (!distancias.is_square())
        throw runtime_error("La matriz leída no es cuadrada");

    cantidadCiudades = distancias.n_rows;

    Camino nodoInicial;
    nodoInicial.ciudadFinal = randi(1, distr_param(1, cantidadCiudades)).at(0);
    nodoInicial.recorrido.push_back(nodoInicial.ciudadFinal);
    nodoInicial.costoCamino = 0;

    listaCaminos.insert(nodoInicial);
}

vector<int> ArbolBusqueda::hacerBusqueda()
{
    while (!listaCaminos.empty()) {
        //  1 - Saco el primer elemento de la lista
        //      Si no hay elementos, no encontré una solución
        Camino camino = *listaCaminos.begin();
        listaCaminos.erase(listaCaminos.begin());

        //  2 - Me fijo si es un estado objetivo
        //      Si es un estado objetivo, encontré la solución
        // El camino va a ser la solución si la cantidad de nodos es igual
        // a la cantidad de ciudades.
        if (camino.recorrido.size() == cantidadCiudades)
            return camino.recorrido;

        //  3 - Expando los vecinos a los que puede ir y los meto en listaCaminos.
        //      Los nuevos Caminos son insertados para que lista quede ordenada por
        //      el costo de cada camino.
        //      Si no hay vecinos a expandir, no inserto nada.
        for (unsigned int ciudad = 1; ciudad <= cantidadCiudades; ++ciudad) {

            // Si la ciudad no está en el recorrido hecho, entonces puedo viajar
            // a esa ciudad.
            if (boost::algorithm::none_of_equal(camino.recorrido, ciudad)) {

                // Creo un nuevo camino en base al actual
                Camino nuevoCamino{camino};

                // Actualizo el nuevo camino con la información sobre la
                // nueva ciudad a la que se viajó.
                nuevoCamino.ciudadFinal = ciudad;
                nuevoCamino.recorrido.push_back(ciudad);
                nuevoCamino.costoCamino += distancias.at(camino.ciudadFinal - 1,
                                                         nuevoCamino.ciudadFinal - 1);

                // Inserto el nuevo camino
                listaCaminos.insert(nuevoCamino);
            }
        }
    }

    // Si se llegó hasta acá, es porque no se encontró una solución
    throw runtime_error("No se encontró una solución");
}
<|endoftext|>