/***************************************************************************
 *  tests/mng/test_block_manager2.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *
 **************************************************************************/

#include <iostream>
#include <stxxl/mng>

#define BLOCK_SIZE (1024 * 1024 * 32)

typedef stxxl::typed_block<BLOCK_SIZE, int> block_type;
template class stxxl::typed_block<BLOCK_SIZE, int>; // forced instantiation

int main()
{
    stxxl::int64 totalsize = 0;
    stxxl::config* config = stxxl::config::get_instance();

    for (size_t i = 0; i < config->disks_number(); ++i)
        totalsize += config->disk_size(i);

    stxxl::unsigned_type totalblocks =
        (stxxl::unsigned_type)(totalsize / block_type::raw_size);

    STXXL_MSG("external memory: " << totalsize << " bytes  ==  " << totalblocks << " blocks");

    stxxl::BIDArray<BLOCK_SIZE> b5a(totalblocks / 5);
    stxxl::BIDArray<BLOCK_SIZE> b5b(totalblocks / 5);
    stxxl::BIDArray<BLOCK_SIZE> b5c(totalblocks / 5);
    stxxl::BIDArray<BLOCK_SIZE> b5d(totalblocks / 5);
    stxxl::BIDArray<BLOCK_SIZE> b2(totalblocks / 2);

    stxxl::block_manager* bm = stxxl::block_manager::get_instance();

    STXXL_MSG("get 4 x " << totalblocks / 5);
    bm->new_blocks(stxxl::striping(), b

    bm->new_blocks(stxxl::striping(), b5b.begin(), b5b.end());
    bm->new_blocks(stxxl::striping(), b5c.begin(), b5c.end());
    bm->new_blocks(stxxl::striping(), b5d.begin(), b5d.end());

    STXXL_MSG("free 2 x " << totalblocks / 5);
    bm->delete_blocks(b5a.begin(), b5a.end());
    bm->delete_blocks(b5c.begin(), b5c.end());

    // the external memory should now be fragmented enough,
    // s.t. the following request needs to be split into smaller ones
    STXXL_MSG("get 1 x " << totalblocks / 2);
    bm->new_blocks(stxxl::striping(), b2.begin(), b2.end());

    bm->delete_blocks(b5b.begin(), b5b.end());
    bm->delete_blocks(b5d.begin(), b5d.end());

    bm->delete_blocks(b2.begin(), b2.end());
}


void demprep(UserInterface &ui, Pvl *log)

#include <iomanip>

#include "Distance.h"
#include "ProcessByLine.h"
#include "TProjection.h"
#include "SpecialPixel.h"
#include "LineManager.h"
#include "History.h"
#include "Table.h"
#include "Pvl.h"
#include "UserInterface.h"

using namespace std;

namespace Isis{

  void DoWrap(Buffer &in);
  void GetStats(Buffer &in, Buffer &out);

  Cube *ocube;

  int leftPad;
  int rightPad;
  int topPad;
  int bottomPad;
  int inl;
  Statistics inCubeStats;
  Statistics outCubeStats;

{
    // We will be using a mosaic technique so get the size of the input file
    ProcessByLine p;

    CubeAttributeInput &inputAtt = ui.GetInputAttribute("FROM");
    Cube *icube = p.SetInputCube(ui.GetFileName("FROM"), inputAtt);
    int ins = icube->sampleCount();
    inl = icube->lineCount();
    int inb = icube->bandCount();
    outCubeStats.Reset();

    PvlGroup mapgrp = icube->label()->findGroup("Mapping", Pvl::Traverse);
    bool hasExtents = false;
    bool isGlobal = false;
    double minLat,maxLat,minLon,maxLon;
    if (mapgrp.hasKeyword("MinimumLatitude") && mapgrp.hasKeyword("MaximumLatitude") &&
        mapgrp.hasKeyword("MinimumLongitude") && mapgrp.hasKeyword("MaximumLongitude")) {
      hasExtents = true;
      minLat = mapgrp["MinimumLatitude"];
      maxLat = mapgrp["MaximumLatitude"];
      minLon = mapgrp["MinimumLongitude"];
      maxLon = mapgrp["MaximumLongitude"];
      if ((maxLat - minLat) >= 180.0 && (maxLon - minLon) >= 360.0) isGlobal = true;
    }

    TProjection *proj = (TProjection *) icube->projection();
    if(proj == NULL) {
      IString message = "The input cube must be a DEM file, which means it must be projected. ";
      message += "This file is not map projected.";
      throw IException(IException::User, message, _FILEINFO_);
    }

    if(!proj->IsEquatorialCylindrical()) {
      CubeAttributeOutput &att = ui.GetOutputAttribute("TO");
      ocube = p.SetOutputCube(ui.GetFileName("TO"), att);
      p.StartProcess(GetStats);

      PvlGroup demRange("Results");
      demRange += PvlKeyword("MinimumRadius", toString(inCubeStats.Minimum()), "meters");
      demRange += PvlKeyword("MaximumRadius", toString(inCubeStats.Maximum()), "meters");
      if (log){
        log->addGroup(demRange);
      }

      // Store min/max radii values in new ShapeModelStatistics table
      QString shp_name = "ShapeModelStatistics";
      TableField fmin("MinimumRadius",Isis::TableField::Double);
      TableField fmax("MaximumRadius",Isis::TableField::Double);

      TableRecord record;
      record += fmin;
      record += fmax;

      Table table(shp_name,record);

      record[0] = Distance(inCubeStats.Minimum(),
                           Distance::Meters).kilometers();
      record[1] = Distance(inCubeStats.Maximum(),
                           Distance::Meters).kilometers();
      table += record;

      ocube->write(table);
      p.EndProcess();
      return;
    }

    if (proj->LatitudeTypeString() != "Planetocentric") {
      IString message = "The input cube must have Planetocentric latitude type.";
      throw IException(IException::User, message, _FILEINFO_);
    }

    // Determine if the file is global
    bool isPadded = false;
    int insideImage = 0;
    if (!hasExtents) {
      if (proj->LongitudeDomainString() == "360") {
        proj->SetGround(90.0,0.0);
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(90.0,360.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,0.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,360.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
        }
        if (proj->IsGood() && insideImage == 4) isGlobal = true;
      } else {
        proj->SetGround(90.0,-180.0);
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(90.0,180.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,-180.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,180.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
        }
        if (proj->IsGood() && insideImage == 4) isGlobal = true;
      }
    }

    if (isGlobal) {
      if (proj->LongitudeDomainString() == "360") {
        if (proj->LongitudeDirectionString() == "PositiveEast") {
          proj->SetGround(90.0,0.0);
        } else {
          proj->SetGround(90.0,360.0);
        }
        if (proj->WorldX() >= 1.0 && proj->WorldY() >= 1.0) isPadded = true;
      } else {
        if (proj->LongitudeDirectionString() == "PositiveEast") {
          proj->SetGround(90.0,-180.0);
        } else {
          proj->SetGround(90.0,180.0);
        }
        if (proj->WorldX() >= 1.0 && proj->WorldY() >= 1.0) isPadded = true;
      }
    }

    // If the file isn't global, then determine if it contains either
    // the south or north pole
    bool hasSPole = false;
    bool hasNPole = false;
    if (!isGlobal) {
      proj->SetGround(90.0,0.0);
      if (proj->IsGood()) {
        if (proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
          hasNPole = true;
          if (proj->WorldY() >= 1.0) isPadded = true;
        }
      }
      proj->SetGround(-90.0,0.0);
      if (proj->IsGood()) {
        if (proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
          hasSPole = true;
          if (proj->WorldY() <= inl) isPadded = true;
        }
      }
    }

    // Set the padding parameters
    leftPad = 0;
    rightPad = 0;
    topPad = 0;
    bottomPad = 0;

    if (isGlobal && !isPadded) {
      leftPad = 1;
      rightPad = 1;
      topPad = 1;
      bottomPad = 1;
    }
    if (!isGlobal && !isPadded) {
      leftPad = 0;
      rightPad = 0;
      if (hasNPole) {
        topPad = 1;
      } else {
        topPad = 0;
      }
      if (hasSPole) {
        bottomPad = 1;
      } else {
        bottomPad = 0;
      }
    }

    // Compute the output size
    int ns = ins + leftPad + rightPad;
    int nl = inl + topPad + bottomPad;
    int nb = inb;

    double upperLeftCorner = mapgrp["UpperLeftCornerX"];
    upperLeftCorner -= leftPad * proj->Resolution();
    mapgrp.addKeyword(PvlKeyword("UpperLeftCornerX", toString(upperLeftCorner), "meters"),
                      Pvl::Replace);

    upperLeftCorner = mapgrp["UpperLeftCornerY"];
    upperLeftCorner += topPad * proj->Resolution();
    mapgrp.addKeyword(PvlKeyword("UpperLeftCornerY", toString(upperLeftCorner), "meters"),
                      Pvl::Replace);

    CubeAttributeOutput &att = ui.GetOutputAttribute("TO");
    ocube = p.SetOutputCube(ui.GetFileName("TO"), att, ns, nl, nb);
    // Make sure everything is propagated and closed
    p.EndProcess();

    // Now we'll really be processing our input cube
    p.SetInputCube(ui.GetFileName("FROM"), inputAtt);

    // We need to create the output file
    ocube = new Cube();
    ocube->open(FileName(ui.GetFileName("TO")).expanded(), "rw");

    p.StartProcess(DoWrap);

    // Update mapping grp
    ocube->putGroup(mapgrp);

    PvlGroup demRange("Results");
    demRange += PvlKeyword("MinimumRadius", toString(outCubeStats.Minimum()), "meters");
    demRange += PvlKeyword("MaximumRadius", toString(outCubeStats.Maximum()), "meters");
    if (log){
      log->addGroup(demRange);
    }

    // Store min/max radii values in new ShapeModelStatistics table
    QString shp_name = "ShapeModelStatistics";
    TableField fmin("MinimumRadius",Isis::TableField::Double);
    TableField fmax("MaximumRadius",Isis::TableField::Double);

    TableRecord record;
    record += fmin;
    record += fmax;

    Table table(shp_name,record);

    record[0] = Distance(outCubeStats.Minimum(),
                         Distance::Meters).kilometers();
    record[1] = Distance(outCubeStats.Maximum(),
                         Distance::Meters).kilometers();
    table += record;

    ocube->write(table);

    p.EndProcess();
    ocube->close();
    delete ocube;
  }

  void GetStats(Buffer &in, Buffer &out) {
    inCubeStats.AddData(&in[0], in.size());
    for (int i=0; i<in.size(); i++) {
      out[i] = in[i];
    }
  }

  void DoWrap(Buffer &in) {
    LineManager outMan(*ocube);

    int inputSize = in.size();
    outMan.SetLine(in.Line() + topPad);
    int outputSize = outMan.size();

    Statistics inputLineStats;

    // We only need stats for the first and last lines of the input cube...
    if ((topPad == 1 && in.Line() == 1) || (bottomPad == 1 && in.Line() == inl)) {
      for(int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
        int inputIndex = outputIndex - leftPad;
        if(inputIndex < 0) {
          inputLineStats.AddData(in[inputIndex + inputSize]);
        }
        else if(inputIndex < inputSize) {
          inputLineStats.AddData(in[inputIndex]);
        }
        else {
          inputLineStats.AddData(in[inputIndex - inputSize]);
        }
      }
    }

    // Write top pad?
    if (topPad == 1 && in.Line() == 1) {
      double average = inputLineStats.Average(); //may be Isis::NULL8
      for(int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
        int inputIndex = outputIndex - leftPad;
        if (average == Isis::NULL8) {
          if(inputIndex < 0) {
            outMan[outputIndex] = in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = in[inputIndex];
          }
          else {
            outMan[outputIndex] = in[inputIndex - inputSize];
          }
        }
        else {
          if(inputIndex < 0) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex];
          }
          else {
            outMan[outputIndex] = 2.0 * average - in[inputIndex - inputSize];
          }
        }
      }
      outMan.SetLine(1);

      outCubeStats.AddData(&outMan[0], outMan.size());
      ocube->write(outMan);
      outMan.SetLine(2);
    }

    // Copy most data
    for(int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
      int inputIndex = outputIndex - leftPad;
      if(inputIndex < 0) {
        outMan[outputIndex] = in[inputIndex + inputSize];
      }
      else if(inputIndex < inputSize) {
        outMan[outputIndex] = in[inputIndex];
      }
      else {
        outMan[outputIndex] = in[inputIndex - inputSize];
      }
    }

    outCubeStats.AddData(&outMan[0], outMan.size());
    ocube->write(outMan);

    // Write bottom pad?
    if (bottomPad == 1 && in.Line() == inl) {
      double average = inputLineStats.Average(); //may be Isis::NULL8
      for (int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
      int inputIndex = outputIndex - leftPad;
        if (average == Isis::NULL8) {
          if(inputIndex < 0) {
            outMan[outputIndex] = in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = in[inputIndex];
          }
          else {
            outMan[outputIndex] = in[inputIndex - inputSize];
          }
        }
        else {
          if(inputIndex < 0) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex];
          }
          else {
            outMan[outputIndex] = 2.0 * average - in[inputIndex - inputSize];
          }
        }
      }
      outMan.SetLine(inl + topPad + bottomPad);
      outCubeStats.AddData(&outMan[0], outMan.size());
      ocube->write(outMan);
    }
  }
}


{
    inCubeStats.AddData(&in[0], in.size());
    for (int i=0; i<in.size(); i++) {
      out[i] = in[i];
    }
  }

#include <iomanip>

#include "Distance.h"
#include "ProcessByLine.h"
#include "TProjection.h"
#include "SpecialPixel.h"
#include "LineManager.h"
#include "History.h"
#include "Table.h"
#include "Pvl.h"
#include "UserInterface.h"

using namespace std;

namespace Isis{

  void DoWrap(Buffer &in);
  void GetStats(Buffer &in, Buffer &out);

  Cube *ocube;

  int leftPad;
  int rightPad;
  int topPad;
  int bottomPad;
  int inl;
  Statistics inCubeStats;
  Statistics outCubeStats;

  void demprep(UserInterface &ui, Pvl *log) {
    // We will be using a mosaic technique so get the size of the input file
    ProcessByLine p;

    CubeAttributeInput &inputAtt = ui.GetInputAttribute("FROM");
    Cube *icube = p.SetInputCube(ui.GetFileName("FROM"), inputAtt);
    int ins = icube->sampleCount();
    inl = icube->lineCount();
    int inb = icube->bandCount();
    outCubeStats.Reset();

    PvlGroup mapgrp = icube->label()->findGroup("Mapping", Pvl::Traverse);
    bool hasExtents = false;
    bool isGlobal = false;
    double minLat,maxLat,minLon,maxLon;
    if (mapgrp.hasKeyword("MinimumLatitude") && mapgrp.hasKeyword("MaximumLatitude") &&
        mapgrp.hasKeyword("MinimumLongitude") && mapgrp.hasKeyword("MaximumLongitude")) {
      hasExtents = true;
      minLat = mapgrp["MinimumLatitude"];
      maxLat = mapgrp["MaximumLatitude"];
      minLon = mapgrp["MinimumLongitude"];
      maxLon = mapgrp["MaximumLongitude"];
      if ((maxLat - minLat) >= 180.0 && (maxLon - minLon) >= 360.0) isGlobal = true;
    }

    TProjection *proj = (TProjection *) icube->projection();
    if(proj == NULL) {
      IString message = "The input cube must be a DEM file, which means it must be projected. ";
      message += "This file is not map projected.";
      throw IException(IException::User, message, _FILEINFO_);
    }

    if(!proj->IsEquatorialCylindrical()) {
      CubeAttributeOutput &att = ui.GetOutputAttribute("TO");
      ocube = p.SetOutputCube(ui.GetFileName("TO"), att);
      p.StartProcess(GetStats);

      PvlGroup demRange("Results");
      demRange += PvlKeyword("MinimumRadius", toString(inCubeStats.Minimum()), "meters");
      demRange += PvlKeyword("MaximumRadius", toString(inCubeStats.Maximum()), "meters");
      if (log){
        log->addGroup(demRange);
      }

      // Store min/max radii values in new ShapeModelStatistics table
      QString shp_name = "ShapeModelStatistics";
      TableField fmin("MinimumRadius",Isis::TableField::Double);
      TableField fmax("MaximumRadius",Isis::TableField::Double);

      TableRecord record;
      record += fmin;
      record += fmax;

      Table table(shp_name,record);

      record[0] = Distance(inCubeStats.Minimum(),
                           Distance::Meters).kilometers();
      record[1] = Distance(inCubeStats.Maximum(),
                           Distance::Meters).kilometers();
      table += record;

      ocube->write(table);
      p.EndProcess();
      return;
    }

    if (proj->LatitudeTypeString() != "Planetocentric") {
      IString message = "The input cube must have Planetocentric latitude type.";
      throw IException(IException::User, message, _FILEINFO_);
    }

    // Determine if the file is global
    bool isPadded = false;
    int insideImage = 0;
    if (!hasExtents) {
      if (proj->LongitudeDomainString() == "360") {
        proj->SetGround(90.0,0.0);
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(90.0,360.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,0.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,360.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
        }
        if (proj->IsGood() && insideImage == 4) isGlobal = true;
      } else {
        proj->SetGround(90.0,-180.0);
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(90.0,180.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,-180.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,180.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
        }
        if (proj->IsGood() && insideImage == 4) isGlobal = true;
      }
    }

    if (isGlobal) {
      if (proj->LongitudeDomainString() == "360") {
        if (proj->LongitudeDirectionString() == "PositiveEast") {
          proj->SetGround(90.0,0.0);
        } else {
          proj->SetGround(90.0,360.0);
        }
        if (proj->WorldX() >= 1.0 && proj->WorldY() >= 1.0) isPadded = true;
      } else {
        if (proj->LongitudeDirectionString() == "PositiveEast") {
          proj->SetGround(90.0,-180.0);
        } else {
          proj->SetGround(90.0,180.0);
        }
        if (proj->WorldX() >= 1.0 && proj->WorldY() >= 1.0) isPadded = true;
      }
    }

    // If the file isn't global, then determine if it contains either
    // the south or north pole
    bool hasSPole = false;
    bool hasNPole = false;
    if (!isGlobal) {
      proj->SetGround(90.0,0.0);
      if (proj->IsGood()) {
        if (proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
          hasNPole = true;
          if (proj->WorldY() >= 1.0) isPadded = true;
        }
      }
      proj->SetGround(-90.0,0.0);
      if (proj->IsGood()) {
        if (proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
          hasSPole = true;
          if (proj->WorldY() <= inl) isPadded = true;
        }
      }
    }

    // Set the padding parameters
    leftPad = 0;
    rightPad = 0;
    topPad = 0;
    bottomPad = 0;

    if (isGlobal && !isPadded) {
      leftPad = 1;
      rightPad = 1;
      topPad = 1;
      bottomPad = 1;
    }
    if (!isGlobal && !isPadded) {
      leftPad = 0;
      rightPad = 0;
      if (hasNPole) {
        topPad = 1;
      } else {
        topPad = 0;
      }
      if (hasSPole) {
        bottomPad = 1;
      } else {
        bottomPad = 0;
      }
    }

    // Compute the output size
    int ns = ins + leftPad + rightPad;
    int nl = inl + topPad + bottomPad;
    int nb = inb;

    double upperLeftCorner = mapgrp["UpperLeftCornerX"];
    upperLeftCorner -= leftPad * proj->Resolution();
    mapgrp.addKeyword(PvlKeyword("UpperLeftCornerX", toString(upperLeftCorner), "meters"),
                      Pvl::Replace);

    upperLeftCorner = mapgrp["UpperLeftCornerY"];
    upperLeftCorner += topPad * proj->Resolution();
    mapgrp.addKeyword(PvlKeyword("UpperLeftCornerY", toString(upperLeftCorner), "meters"),
                      Pvl::Replace);

    CubeAttributeOutput &att = ui.GetOutputAttribute("TO");
    ocube = p.SetOutputCube(ui.GetFileName("TO"), att, ns, nl, nb);
    // Make sure everything is propagated and closed
    p.EndProcess();

    // Now we'll really be processing our input cube
    p.SetInputCube(ui.GetFileName("FROM"), inputAtt);

    // We need to create the output file
    ocube = new Cube();
    ocube->open(FileName(ui.GetFileName("TO")).expanded(), "rw");

    p.StartProcess(DoWrap);

    // Update mapping grp
    ocube->putGroup(mapgrp);

    PvlGroup demRange("Results");
    demRange += PvlKeyword("MinimumRadius", toString(outCubeStats.Minimum()), "meters");
    demRange += PvlKeyword("MaximumRadius", toString(outCubeStats.Maximum()), "meters");
    if (log){
      log->addGroup(demRange);
    }

    // Store min/max radii values in new ShapeModelStatistics table
    QString shp_name = "ShapeModelStatistics";
    TableField fmin("MinimumRadius",Isis::TableField::Double);
    TableField fmax("MaximumRadius",Isis::TableField::Double);

    TableRecord record;
    record += fmin;
    record += fmax;

    Table table(shp_name,record);

    record[0] = Distance(outCubeStats.Minimum(),
                         Distance::Meters).kilometers();
    record[1] = Distance(outCubeStats.Maximum(),
                         Distance::Meters).kilometers();
    table += record;

    ocube->write(table);

    p.EndProcess();
    ocube->close();
    delete ocube;
  }

  void GetStats(Buffer &in, Buffer &out)

  void DoWrap(Buffer &in) {
    LineManager outMan(*ocube);

    int inputSize = in.size();
    outMan.SetLine(in.Line() + topPad);
    int outputSize = outMan.size();

    Statistics inputLineStats;

    // We only need stats for the first and last lines of the input cube...
    if ((topPad == 1 && in.Line() == 1) || (bottomPad == 1 && in.Line() == inl)) {
      for(int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
        int inputIndex = outputIndex - leftPad;
        if(inputIndex < 0) {
          inputLineStats.AddData(in[inputIndex + inputSize]);
        }
        else if(inputIndex < inputSize) {
          inputLineStats.AddData(in[inputIndex]);
        }
        else {
          inputLineStats.AddData(in[inputIndex - inputSize]);
        }
      }
    }

    // Write top pad?
    if (topPad == 1 && in.Line() == 1) {
      double average = inputLineStats.Average(); //may be Isis::NULL8
      for(int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
        int inputIndex = outputIndex - leftPad;
        if (average == Isis::NULL8) {
          if(inputIndex < 0) {
            outMan[outputIndex] = in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = in[inputIndex];
          }
          else {
            outMan[outputIndex] = in[inputIndex - inputSize];
          }
        }
        else {
          if(inputIndex < 0) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex];
          }
          else {
            outMan[outputIndex] = 2.0 * average - in[inputIndex - inputSize];
          }
        }
      }
      outMan.SetLine(1);

      outCubeStats.AddData(&outMan[0], outMan.size());
      ocube->write(outMan);
      outMan.SetLine(2);
    }

    // Copy most data
    for(int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
      int inputIndex = outputIndex - leftPad;
      if(inputIndex < 0) {
        outMan[outputIndex] = in[inputIndex + inputSize];
      }
      else if(inputIndex < inputSize) {
        outMan[outputIndex] = in[inputIndex];
      }
      else {
        outMan[outputIndex] = in[inputIndex - inputSize];
      }
    }

    outCubeStats.AddData(&outMan[0], outMan.size());
    ocube->write(outMan);

    // Write bottom pad?
    if (bottomPad == 1 && in.Line() == inl) {
      double average = inputLineStats.Average(); //may be Isis::NULL8
      for (int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
      int inputIndex = outputIndex - leftPad;
        if (average == Isis::NULL8) {
          if(inputIndex < 0) {
            outMan[outputIndex] = in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = in[inputIndex];
          }
          else {
            outMan[outputIndex] = in[inputIndex - inputSize];
          }
        }
        else {
          if(inputIndex < 0) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex];
          }
          else {
            outMan[outputIndex] = 2.0 * average - in[inputIndex - inputSize];
          }
        }
      }
      outMan.SetLine(inl + topPad + bottomPad);
      outCubeStats.AddData(&outMan[0], outMan.size());
      ocube->write(outMan);
    }
  }
}


#include <iomanip>

#include "Distance.h"
#include "ProcessByLine.h"
#include "TProjection.h"
#include "SpecialPixel.h"
#include "LineManager.h"
#include "History.h"
#include "Table.h"
#include "Pvl.h"
#include "UserInterface.h"

using namespace std;

namespace Isis{

  void DoWrap(Buffer &in);
  void GetStats(Buffer &in, Buffer &out);

  Cube *ocube;

  int leftPad;
  int rightPad;
  int topPad;
  int bottomPad;
  int inl;
  Statistics inCubeStats;
  Statistics outCubeStats;

  void demprep(UserInterface &ui, Pvl *log) {
    // We will be using a mosaic technique so get the size of the input file
    ProcessByLine p;

    CubeAttributeInput &inputAtt = ui.GetInputAttribute("FROM");
    Cube *icube = p.SetInputCube(ui.GetFileName("FROM"), inputAtt);
    int ins = icube->sampleCount();
    inl = icube->lineCount();
    int inb = icube->bandCount();
    outCubeStats.Reset();

    PvlGroup mapgrp = icube->label()->findGroup("Mapping", Pvl::Traverse);
    bool hasExtents = false;
    bool isGlobal = false;
    double minLat,maxLat,minLon,maxLon;
    if (mapgrp.hasKeyword("MinimumLatitude") && mapgrp.hasKeyword("MaximumLatitude") &&
        mapgrp.hasKeyword("MinimumLongitude") && mapgrp.hasKeyword("MaximumLongitude")) {
      hasExtents = true;
      minLat = mapgrp["MinimumLatitude"];
      maxLat = mapgrp["MaximumLatitude"];
      minLon = mapgrp["MinimumLongitude"];
      maxLon = mapgrp["MaximumLongitude"];
      if ((maxLat - minLat) >= 180.0 && (maxLon - minLon) >= 360.0) isGlobal = true;
    }

    TProjection *proj = (TProjection *) icube->projection();
    if(proj == NULL) {
      IString message = "The input cube must be a DEM file, which means it must be projected. ";
      message += "This file is not map projected.";
      throw IException(IException::User, message, _FILEINFO_);
    }

    if(!proj->IsEquatorialCylindrical()) {
      CubeAttributeOutput &att = ui.GetOutputAttribute("TO");
      ocube = p.SetOutputCube(ui.GetFileName("TO"), att);
      p.StartProcess(GetStats);

      PvlGroup demRange("Results");
      demRange += PvlKeyword("MinimumRadius", toString(inCubeStats.Minimum()), "meters");
      demRange += PvlKeyword("MaximumRadius", toString(inCubeStats.Maximum()), "meters");
      if (log){
        log->addGroup(demRange);
      }

      // Store min/max radii values in new ShapeModelStatistics table
      QString shp_name = "ShapeModelStatistics";
      TableField fmin("MinimumRadius",Isis::TableField::Double);
      TableField fmax("MaximumRadius",Isis::TableField::Double);

      TableRecord record;
      record += fmin;
      record += fmax;

      Table table(shp_name,record);

      record[0] = Distance(inCubeStats.Minimum(),
                           Distance::Meters).kilometers();
      record[1] = Distance(inCubeStats.Maximum(),
                           Distance::Meters).kilometers();
      table += record;

      ocube->write(table);
      p.EndProcess();
      return;
    }

    if (proj->LatitudeTypeString() != "Planetocentric") {
      IString message = "The input cube must have Planetocentric latitude type.";
      throw IException(IException::User, message, _FILEINFO_);
    }

    // Determine if the file is global
    bool isPadded = false;
    int insideImage = 0;
    if (!hasExtents) {
      if (proj->LongitudeDomainString() == "360") {
        proj->SetGround(90.0,0.0);
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(90.0,360.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,0.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,360.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
        }
        if (proj->IsGood() && insideImage == 4) isGlobal = true;
      } else {
        proj->SetGround(90.0,-180.0);
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(90.0,180.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,-180.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
          proj->SetGround(-90.0,180.0);
        }
        if (proj->IsGood()) {
          if (proj->WorldX() > 0.0 && proj->WorldX() < ins+1 &&
              proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
            insideImage = insideImage + 1;
          }
        }
        if (proj->IsGood() && insideImage == 4) isGlobal = true;
      }
    }

    if (isGlobal) {
      if (proj->LongitudeDomainString() == "360") {
        if (proj->LongitudeDirectionString() == "PositiveEast") {
          proj->SetGround(90.0,0.0);
        } else {
          proj->SetGround(90.0,360.0);
        }
        if (proj->WorldX() >= 1.0 && proj->WorldY() >= 1.0) isPadded = true;
      } else {
        if (proj->LongitudeDirectionString() == "PositiveEast") {
          proj->SetGround(90.0,-180.0);
        } else {
          proj->SetGround(90.0,180.0);
        }
        if (proj->WorldX() >= 1.0 && proj->WorldY() >= 1.0) isPadded = true;
      }
    }

    // If the file isn't global, then determine if it contains either
    // the south or north pole
    bool hasSPole = false;
    bool hasNPole = false;
    if (!isGlobal) {
      proj->SetGround(90.0,0.0);
      if (proj->IsGood()) {
        if (proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
          hasNPole = true;
          if (proj->WorldY() >= 1.0) isPadded = true;
        }
      }
      proj->SetGround(-90.0,0.0);
      if (proj->IsGood()) {
        if (proj->WorldY() > 0.0 && proj->WorldY() < inl+1) {
          hasSPole = true;
          if (proj->WorldY() <= inl) isPadded = true;
        }
      }
    }

    // Set the padding parameters
    leftPad = 0;
    rightPad = 0;
    topPad = 0;
    bottomPad = 0;

    if (isGlobal && !isPadded) {
      leftPad = 1;
      rightPad = 1;
      topPad = 1;
      bottomPad = 1;
    }
    if (!isGlobal && !isPadded) {
      leftPad = 0;
      rightPad = 0;
      if (hasNPole) {
        topPad = 1;
      } else {
        topPad = 0;
      }
      if (hasSPole) {
        bottomPad = 1;
      } else {
        bottomPad = 0;
      }
    }

    // Compute the output size
    int ns = ins +

    int nl = inl + topPad + bottomPad;
    int nb = inb;

    double upperLeftCorner = mapgrp["UpperLeftCornerX"];
    upperLeftCorner -= leftPad * proj->Resolution();
    mapgrp.addKeyword(PvlKeyword("UpperLeftCornerX", toString(upperLeftCorner), "meters"),
                      Pvl::Replace);

    upperLeftCorner = mapgrp["UpperLeftCornerY"];
    upperLeftCorner += topPad * proj->Resolution();
    mapgrp.addKeyword(PvlKeyword("UpperLeftCornerY", toString(upperLeftCorner), "meters"),
                      Pvl::Replace);

    CubeAttributeOutput &att = ui.GetOutputAttribute("TO");
    ocube = p.SetOutputCube(ui.GetFileName("TO"), att, ns, nl, nb);
    // Make sure everything is propagated and closed
    p.EndProcess();

    // Now we'll really be processing our input cube
    p.SetInputCube(ui.GetFileName("FROM"), inputAtt);

    // We need to create the output file
    ocube = new Cube();
    ocube->open(FileName(ui.GetFileName("TO")).expanded(), "rw");

    p.StartProcess(DoWrap);

    // Update mapping grp
    ocube->putGroup(mapgrp);

    PvlGroup demRange("Results");
    demRange += PvlKeyword("MinimumRadius", toString(outCubeStats.Minimum()), "meters");
    demRange += PvlKeyword("MaximumRadius", toString(outCubeStats.Maximum()), "meters");
    if (log){
      log->addGroup(demRange);
    }

    // Store min/max radii values in new ShapeModelStatistics table
    QString shp_name = "ShapeModelStatistics";
    TableField fmin("MinimumRadius",Isis::TableField::Double);
    TableField fmax("MaximumRadius",Isis::TableField::Double);

    TableRecord record;
    record += fmin;
    record += fmax;

    Table table(shp_name,record);

    record[0] = Distance(outCubeStats.Minimum(),
                         Distance::Meters).kilometers();
    record[1] = Distance(outCubeStats.Maximum(),
                         Distance::Meters).kilometers();
    table += record;

    ocube->write(table);

    p.EndProcess();
    ocube->close();
    delete ocube;
  }

  void GetStats(Buffer &in, Buffer &out) {
    inCubeStats.AddData(&in[0], in.size());
    for (int i=0; i<in.size(); i++) {
      out[i] = in[i];
    }
  }

  void DoWrap(Buffer &in) {
    LineManager outMan(*ocube);

    int inputSize = in.size();
    outMan.SetLine(in.Line() + topPad);
    int outputSize = outMan.size();

    Statistics inputLineStats;

    // We only need stats for the first and last lines of the input cube...
    if ((topPad == 1 && in.Line() == 1) || (bottomPad == 1 && in.Line() == inl)) {
      for(int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
        int inputIndex = outputIndex - leftPad;
        if(inputIndex < 0) {
          inputLineStats.AddData(in[inputIndex + inputSize]);
        }
        else if(inputIndex < inputSize) {
          inputLineStats.AddData(in[inputIndex]);
        }
        else {
          inputLineStats.AddData(in[inputIndex - inputSize]);
        }
      }
    }

    // Write top pad?
    if (topPad == 1 && in.Line() == 1) {
      double average = inputLineStats.Average(); //may be Isis::NULL8
      for(int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
        int inputIndex = outputIndex - leftPad;
        if (average == Isis::NULL8) {
          if(inputIndex < 0) {
            outMan[outputIndex] = in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = in[inputIndex];
          }
          else {
            outMan[outputIndex] = in[inputIndex - inputSize];
          }
        }
        else {
          if(inputIndex < 0) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex];
          }
          else {
            outMan[outputIndex] = 2.0 * average - in[inputIndex - inputSize];
          }
        }
      }
      outMan.SetLine(1);

      outCubeStats.AddData(&outMan[0], outMan.size());
      ocube->write(outMan);
      outMan.SetLine(2);
    }

    // Copy most data
    for(int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
      int inputIndex = outputIndex - leftPad;
      if(inputIndex < 0) {
        outMan[outputIndex] = in[inputIndex + inputSize];
      }
      else if(inputIndex < inputSize) {
        outMan[outputIndex] = in[inputIndex];
      }
      else {
        outMan[outputIndex] = in[inputIndex - inputSize];
      }
    }

    outCubeStats.AddData(&outMan[0], outMan.size());
    ocube->write(outMan);

    // Write bottom pad?
    if (bottomPad == 1 && in.Line() == inl) {
      double average = inputLineStats.Average(); //may be Isis::NULL8
      for (int outputIndex = 0; outputIndex < outputSize; outputIndex++) {
      int inputIndex = outputIndex - leftPad;
        if (average == Isis::NULL8) {
          if(inputIndex < 0) {
            outMan[outputIndex] = in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = in[inputIndex];
          }
          else {
            outMan[outputIndex] = in[inputIndex - inputSize];
          }
        }
        else {
          if(inputIndex < 0) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex + inputSize];
          }
          else if(inputIndex < inputSize) {
            outMan[outputIndex] = 2.0 * average - in[inputIndex];
          }
          else {
            outMan[outputIndex] = 2.0 * average - in[inputIndex - inputSize];
          }
        }
      }
      outMan.SetLine(inl + topPad + bottomPad);
      outCubeStats.AddData(&outMan[0], outMan.size());
      ocube->write(outMan);
    }
  }
}


StageSHAVEsRequirements getSHAVEsRequirementsImpl() const override

#include <vpu/frontend/frontend.hpp>
#include <vpu/stages/post_op_stage.hpp>

namespace vpu {

namespace {

class MishStage final : public PostOpStage {
public:
    using PostOpStage::PostOpStage;

private:
    StagePtr cloneImpl() const override {
        return std::make_shared<MishStage>(*this);
    }

    void serializeParamsImpl(BlobSerializer&) const override {
    }

{
        return StageSHAVEsRequirements::NeedMax;
    }
};

}  // namespace

void FrontEnd::parseMish(const Model& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs) const {
    VPU_THROW_UNLESS(inputs.size() == 1,
                     "Mish stage with name %s must have only 1 input, "
                     "actually provided %d", layer->name, inputs.size());
    VPU_THROW_UNLESS(outputs.size() == 1,
                     "Mish stage with name %s must have only 1 output, "
                     "actually provided %d", layer->name, outputs.size());

    model->addNewStage<MishStage>(layer->name, StageType::Mish, layer, inputs, outputs);
}

}  // namespace vpu


{
    VPU_THROW_UNLESS(inputs.size() == 1,
                     "Mish stage with name %s must have only 1 input, "
                     "actually provided %d", layer->name, inputs.size());
    VPU_THROW_UNLESS(outputs.size() == 1,
                     "Mish stage with name %s must have only 1 output, "
                     "actually provided %d", layer->name, outputs.size());

    model->addNewStage<MishStage>(layer->name, StageType::Mish, layer, inputs, outputs);
}

#include <vpu/frontend/frontend.hpp>
#include <vpu/stages/post_op_stage.hpp>

namespace vpu {

namespace {

class MishStage final : public PostOpStage {
public:
    using PostOpStage::PostOpStage;

private:
    StagePtr cloneImpl() const override {
        return std::make_shared<MishStage>(*this);
    }

    void serializeParamsImpl(BlobSerializer&) const override {
    }

    StageSHAVEsRequirements getSHAVEsRequirementsImpl() const override {
        return StageSHAVEsRequirements::NeedMax;
    }
};

}  // namespace

void FrontEnd::parseMish(const Model& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs) const


#include <vpu/frontend/frontend.hpp>
#include <vpu/stages/post_op_stage.hpp>

namespace vpu {

namespace {

class MishStage final : public PostOpStage {
public:
    using PostOpStage::PostOpStage;

private:
    StagePtr cloneImpl() const override {
        return std::make_shared<MishStage>(*this);
    }

    void serializeParamsImpl(BlobSerializer&) const override {
    }

    StageSHAVEsRequirements getSHAVEsRequirementsImpl() const override {
        return StageSHAVEsRequire

    }
};

}  // namespace

void FrontEnd::parseMish(const Model& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs) const {
    VPU_THROW_UNLESS(inputs.size() == 1,
                     "Mish stage with name %s must have only 1 input, "
                     "actually provided %d", layer->name, inputs.size());
    VPU_THROW_UNLESS(outputs.size() == 1,
                     "Mish stage with name %s must have only 1 output, "
                     "actually provided %d", layer->name, outputs.size());

    model->addNewStage<MishStage>(layer->name, StageType::Mish, layer, inputs, outputs);
}

}  // namespace vpu


void QSettingsWrapper::remove(const QString &param1)

/**************************************************************************
**
**
** This file is part of the Qt Installer Framework.
**
**
**************************************************************************/

#include "qsettingswrapper.h"
#include "permissionsettings.h"

#include <QStringList>

namespace QInstaller {

/*!
    \inmodule QtInstallerFramework
    \class QInstaller::QSettingsWrapper
    \internal
*/

class QSettingsWrapper::Private
{
public:
    Private(const QString &organization, const QString &application)
        : m_application(application)
        , m_organization(organization)
        , m_scope(QSettings::UserScope)
        , m_format(QSettings::NativeFormat)
        , settings(organization, application)
    {
    }

    Private(QSettings::Scope scope, const QString &organization, const QString &application)
        : m_application(application)
        , m_organization(organization)
        , m_scope(scope)
        , m_format(QSettings::NativeFormat)
        , settings(scope, organization, application)
    {
    }

    Private(QSettings::Format format, QSettings::Scope scope, const QString &organization,
        const QString &application)
        : m_application(application)
        , m_organization(organization)
        , m_scope(scope)
        , m_format(format)
        , settings(format, scope, organization, application)
    {
    }

    Private(const QString &fileName, QSettings::Format format)
        : m_filename(fileName)
        , m_format(format)
        , settings(fileName, format)
    {
        m_scope = settings.scope();
        m_application = settings.applicationName();
        m_organization = settings.organizationName();
    }

    QString m_filename;
    QString m_application;
    QString m_organization;
    QSettings::Scope m_scope;
    QSettings::Format m_format;
    PermissionSettings settings;
};

QSettingsWrapper::QSettingsWrapper(const QString &organization, const QString &application,
        QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(organization, application))
{
}

QSettingsWrapper::QSettingsWrapper(QSettingsWrapper::Scope scope, const QString &organization,
        const QString &application, QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(static_cast<QSettings::Scope>(scope), organization, application))
{
}

QSettingsWrapper::QSettingsWrapper(QSettingsWrapper::Format format, QSettingsWrapper::Scope scope,
        const QString &organization, const QString &application, QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(static_cast<QSettings::Format>(format), static_cast<QSettings::Scope> (scope),
        organization, application))
{
}

QSettingsWrapper::QSettingsWrapper(const QString &fileName, QSettingsWrapper::Format format,
        QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(fileName, static_cast<QSettings::Format>(format)))
{
}

QSettingsWrapper::~QSettingsWrapper()
{
    delete d;
}

QStringList QSettingsWrapper::allKeys() const
{
    if (createSocket())
        return callRemoteMethod<QStringList>(QLatin1String(Protocol::QSettingsAllKeys));
    return d->settings.allKeys();
}

QString QSettingsWrapper::applicationName() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsApplicationName));
    return d->settings.applicationName();
}

void QSettingsWrapper::beginGroup(const QString &param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsBeginGroup), param1, dummy);
    else
        d->settings.beginGroup(param1);
}

int QSettingsWrapper::beginReadArray(const QString &param1)
{
    if (createSocket())
        return callRemoteMethod<qint32>(QLatin1String(Protocol::QSettingsBeginReadArray), param1);
    return d->settings.beginReadArray(param1);
}

void QSettingsWrapper::beginWriteArray(const QString &param1, int param2)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsBeginWriteArray), param1, qint32(param2));
    else
        d->settings.beginWriteArray(param1, param2);
}

QStringList QSettingsWrapper::childGroups() const
{
    if (createSocket())
        return callRemoteMethod<QStringList>(QLatin1String(Protocol::QSettingsChildGroups));
    return d->settings.childGroups();
}

QStringList QSettingsWrapper::childKeys() const
{
    if (createSocket())
        return callRemoteMethod<QStringList>(QLatin1String(Protocol::QSettingsChildKeys));
    return d->settings.childKeys();
}

void QSettingsWrapper::clear()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsClear));
    else d->settings.clear();
}

bool QSettingsWrapper::contains(const QString &param1) const
{
    if (createSocket())
        return callRemoteMethod<bool>(QLatin1String(Protocol::QSettingsContains), param1);
    return d->settings.contains(param1);
}

void QSettingsWrapper::endArray()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsEndArray));
    else
        d->settings.endArray();
}

void QSettingsWrapper::endGroup()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsEndGroup));
    else
        d->settings.endGroup();
}

bool QSettingsWrapper::fallbacksEnabled() const
{
    if (createSocket())
        return callRemoteMethod<bool>(QLatin1String(Protocol::QSettingsFallbacksEnabled));
    return d->settings.fallbacksEnabled();
}

QString QSettingsWrapper::fileName() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsFileName));
    return d->settings.fileName();
}

QSettingsWrapper::Format QSettingsWrapper::format() const
{
    // No need to talk to the server, we've setup the local settings object the same way.
    return static_cast<QSettingsWrapper::Format>(d->settings.format());
}

QString QSettingsWrapper::group() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsGroup));
    return d->settings.group();
}

bool QSettingsWrapper::isWritable() const
{
    if (createSocket())
        return callRemoteMethod<bool>(QLatin1String(Protocol::QSettingsIsWritable));
    return d->settings.isWritable();
}

QString QSettingsWrapper::organizationName() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsOrganizationName));
    return d->settings.organizationName();
}

{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsRemove), param1, dummy);
    else
        d->settings.remove(param1);
}

QSettingsWrapper::Scope QSettingsWrapper::scope() const
{
    // No need to talk to the server, we've setup the local settings object the same way.
    return static_cast<QSettingsWrapper::Scope>(d->settings.scope());
}

void QSettingsWrapper::setArrayIndex(int param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSetArrayIndex), qint32(param1), dummy);
    else
        d->settings.setArrayIndex(param1);
}

void QSettingsWrapper::setFallbacksEnabled(bool param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSetFallbacksEnabled), param1, dummy);
    else
        d->settings.setFallbacksEnabled(param1);
}

void QSettingsWrapper::setValue(const QString &param1, const QVariant &param2)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSetValue), param1, param2);
    else
        d->settings.setValue(param1, param2);
}

QSettingsWrapper::Status QSettingsWrapper::status() const
{
    if (createSocket()) {
        return static_cast<QSettingsWrapper::Status>
            (callRemoteMethod<qint32>(QLatin1String(Protocol::QSettingsStatus)));
    }
    return static_cast<QSettingsWrapper::Status>(d->settings.status());
}

void QSettingsWrapper::sync()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSync));
    else
        d->settings.sync();
}

QVariant QSettingsWrapper::value(const QString &param1, const QVariant &param2) const
{
    if (createSocket())
        return callRemoteMethod<QVariant>(QLatin1String(Protocol::QSettingsValue), param1, param2);
    return d->settings.value(param1, param2);
}

bool QSettingsWrapper::createSocket() const
{
    if ((d->m_format != QSettings::NativeFormat) && (d->m_format != QSettings::IniFormat)) {
        Q_ASSERT_X(false, Q_FUNC_INFO, "Settings wrapper only supports QSettingsWrapper::NativeFormat"
                   " and QSettingsWrapper::IniFormat.");
    }
    return (const_cast<QSettingsWrapper *>(this))->connectToServer(QVariantList()
        << d->m_application << d->m_organization << d->m_scope << d->m_format << d->m_filename);
}

} // namespace QInstaller


/**************************************************************************
**
**
** This file is part of the Qt Installer Framework.
**
**
**************************************************************************/

#include "qsettingswrapper.h"
#include "permissionsettings.h"

#include <QStringList>

namespace QInstaller {

/*!
    \inmodule QtInstallerFramework
    \class QInstaller::QSettingsWrapper
    \internal
*/

class QSettingsWrapper::Private
{
public:
    Private(const QString &organization, const QString &application)
        : m_application(application)
        , m_organization(organization)
        , m_scope(QSettings::UserScope)
        , m_format(QSettings::NativeFormat)
        , settings(organization, application)
    {
    }

    Private(QSettings::Scope scope, const QString &organization, const QString &application)
        : m_application(application)
        , m_organization(organization)
        , m_scope(scope)
        , m_format(QSettings::NativeFormat)
        , settings(scope, organization, application)
    {
    }

    Private(QSettings::Format format, QSettings::Scope scope, const QString &organization,
        const QString &application)
        : m_application(application)
        , m_organization(organization)
        , m_scope(scope)
        , m_format(format)
        , settings(format, scope, organization, application)
    {
    }

    Private(const QString &fileName, QSettings::Format format)
        : m_filename(fileName)
        , m_format(format)
        , settings(fileName, format)
    {
        m_scope = settings.scope();
        m_application = settings.applicationName();
        m_organization = settings.organizationName();
    }

    QString m_filename;
    QString m_application;
    QString m_organization;
    QSettings::Scope m_scope;
    QSettings::Format m_format;
    PermissionSettings settings;
};

QSettingsWrapper::QSettingsWrapper(const QString &organization, const QString &application,
        QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(organization, application))
{
}

QSettingsWrapper::QSettingsWrapper(QSettingsWrapper::Scope scope, const QString &organization,
        const QString &application, QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(static_cast<QSettings::Scope>(scope), organization, application))
{
}

QSettingsWrapper::QSettingsWrapper(QSettingsWrapper::Format format, QSettingsWrapper::Scope scope,
        const QString &organization, const QString &application, QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(static_cast<QSettings::Format>(format), static_cast<QSettings::Scope> (scope),
        organization, application))

QSettingsWrapper::QSettingsWrapper(const QString &fileName, QSettingsWrapper::Format format,
        QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(fileName, static_cast<QSettings::Format>(format)))
{
}

QSettingsWrapper::~QSettingsWrapper()
{
    delete d;
}

QStringList QSettingsWrapper::allKeys() const
{
    if (createSocket())
        return callRemoteMethod<QStringList>(QLatin1String(Protocol::QSettingsAllKeys));
    return d->settings.allKeys();
}

QString QSettingsWrapper::applicationName() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsApplicationName));
    return d->settings.applicationName();
}

void QSettingsWrapper::beginGroup(const QString &param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsBeginGroup), param1, dummy);
    else
        d->settings.beginGroup(param1);
}

int QSettingsWrapper::beginReadArray(const QString &param1)
{
    if (createSocket())
        return callRemoteMethod<qint32>(QLatin1String(Protocol::QSettingsBeginReadArray), param1);
    return d->settings.beginReadArray(param1);
}

void QSettingsWrapper::beginWriteArray(const QString &param1, int param2)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsBeginWriteArray), param1, qint32(param2));
    else
        d->settings.beginWriteArray(param1, param2);
}

QStringList QSettingsWrapper::childGroups() const
{
    if (createSocket())
        return callRemoteMethod<QStringList>(QLatin1String(Protocol::QSettingsChildGroups));
    return d->settings.childGroups();
}

QStringList QSettingsWrapper::childKeys() const
{
    if (createSocket())
        return callRemoteMethod<QStringList>(QLatin1String(Protocol::QSettingsChildKeys));
    return d->settings.childKeys();
}

void QSettingsWrapper::clear()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsClear));
    else d->settings.clear();
}

bool QSettingsWrapper::contains(const QString &param1) const
{
    if (createSocket())
        return callRemoteMethod<bool>(QLatin1String(Protocol::QSettingsContains), param1);
    return d->settings.contains(param1);
}

void QSettingsWrapper::endArray()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsEndArray));
    else
        d->settings.endArray();
}

void QSettingsWrapper::endGroup()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsEndGroup));
    else
        d->settings.endGroup();
}

bool QSettingsWrapper::fallbacksEnabled() const
{
    if (createSocket())
        return callRemoteMethod<bool>(QLatin1String(Protocol::QSettingsFallbacksEnabled));
    return d->settings.fallbacksEnabled();
}

QString QSettingsWrapper::fileName() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsFileName));
    return d->settings.fileName();
}

QSettingsWrapper::Format QSettingsWrapper::format() const
{
    // No need to talk to the server, we've setup the local settings object the same way.
    return static_cast<QSettingsWrapper::Format>(d->settings.format());
}

QString QSettingsWrapper::group() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsGroup));
    return d->settings.group();
}

bool QSettingsWrapper::isWritable() const
{
    if (createSocket())
        return callRemoteMethod<bool>(QLatin1String(Protocol::QSettingsIsWritable));
    return d->settings.isWritable();
}

QString QSettingsWrapper::organizationName() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsOrganizationName));
    return d->settings.organizationName();
}

void QSettingsWrapper::remove(const QString &param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsRemove), param1, dummy);
    else
        d->settings.remove(param1);
}

QSettingsWrapper::Scope QSettingsWrapper::scope() const
{
    // No need to talk to the server, we've setup the local settings object the same way.
    return static_cast<QSettingsWrapper::Scope>(d->settings.scope());
}

void QSettingsWrapper::setArrayIndex(int param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSetArrayIndex), qint32(param1), dummy);
    else
        d->settings.setArrayIndex(param1);
}

void QSettingsWrapper::setFallbacksEnabled(bool param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSetFallbacksEnabled), param1, dummy);
    else
        d->settings.setFallbacksEnabled(param1);
}

void QSettingsWrapper::setValue(const QString &param1, const QVariant &param2)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSetValue), param1, param2);
    else
        d->settings.setValue(param1, param2);
}

QSettingsWrapper::Status QSettingsWrapper::status() const
{
    if (createSocket()) {
        return static_cast<QSettingsWrapper::Status>
            (callRemoteMethod<qint32>(QLatin1String(Protocol::QSettingsStatus)));
    }
    return static_cast<QSettingsWrapper::Status>(d->settings.status());
}

void QSettingsWrapper::sync()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSync));
    else
        d->settings.sync();
}

QVariant QSettingsWrapper::value(const QString &param1, const QVariant &param2) const
{
    if (createSocket())
        return callRemoteMethod<QVariant>(QLatin1String(Protocol::QSettingsValue), param1, param2);
    return d->settings.value(param1, param2);
}

bool QSettingsWrapper::createSocket() const
{
    if ((d->m_format != QSettings::NativeFormat) && (d->m_format != QSettings::IniFormat)) {
        Q_ASSERT_X(false, Q_FUNC_INFO, "Settings wrapper only supports QSettingsWrapper::NativeFormat"
                   " and QSettingsWrapper::IniFormat.");
    }
    return (const_cast<QSettingsWrapper *>(this))->connectToServer(QVariantList()
        << d->m_application << d->m_organization << d->m_scope << d->m_format << d->m_filename);
}

} // namespace QInstaller


/**************************************************************************
**
**
** This file is part of the Qt Installer Framework.
**
**
**************************************************************************/

#include "qsettingswrapper.h"
#include "permissionsettings.h"

#include <QStringList>

namespace QInstaller {

/*!
    \inmodule QtInstallerFramework
    \class QInstaller::QSettingsWrapper
    \internal
*/

class QSettingsWrapper::Private
{
public:
    Private(const QString &organization, const QString &application)
        : m_application(application)
        , m_organization(organization)
        , m_scope(QSettings::UserScope)
        , m_format(QSettings::NativeFormat)
        , settings(organization, application)
    {
    }

    Private(QSettings::Scope scope, const QString &organization, const QString &application)
        : m_application(application)
        , m_organization(organization)
        , m_scope(scope)
        , m_format(QSettings::NativeFormat)
        , settings(scope, organization, application)
    {
    }

    Private(QSettings::Format format, QSettings::Scope scope, const QString &organization,
        const QString &application)
        : m_application(application)
        , m_organization(organization)
        , m_scope(scope)
        , m_format(format)
        , settings(format, scope, organization, application)
    {
    }

    Private(const QString &fileName, QSettings::Format format)
        : m_filename(fileName)
        , m_format(format)
        , settings(fileName, format)
    {
        m_scope = settings.scope();
        m_application = settings.applicationName();
        m_organization = settings.organizationName();
    }

    QString m_filename;
    QString m_application;
    QString m_organization;
    QSettings::Scope m_scope;
    QSettings::Format m_format;
    PermissionSettings settings;
};

QSettingsWrapper::QSettingsWrapper(const QString &organization, const QString &application,
        QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(organization, application))
{
}

QSettingsWrapper::QSettingsWrapper(QSettingsWrapper::Scope scope, const QString &organization,
        const QString &application, QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(static_cast<QSettings::Scope>(scope), organization, application))
{
}

QSettingsWrapper::QSettingsWrapper(QSettingsWrapper::Format format, QSettingsWrapper::Scope scope,
        const QString &organization, const QString &application, QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(static_cast<QSettings::Format>(format), static_cast<QSettings::Scope> (scope),
        organization, application))
{
}

QSettingsWrapper::QSettingsWrapper(const QString &fileName, QSettingsWrapper::Format format,
        QObject *parent)
    : RemoteObject(QLatin1String(Protocol::QSettings), parent)
    , d(new Private(fileName, static_cast<QSettings::Format>(format)))
{
}

QSettingsWrapper::~QSettingsWrapper()
{
    delete d;
}

QStringList QSettingsWrapper::allKeys() const
{
    if (createSocket())
        return callRemoteMethod<QStringList>(QLatin1String(Protocol::QSettingsAllKeys));
    return d->settings.allKeys();
}

QString QSettingsWrapper::applicationName() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsApplicationName));
    return d->settings.applicationName();
}

void QSettingsWrapper::beginGroup(const QString &param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsBeginGroup), param1, dummy);
    else
        d->settings.beginGroup(param1);
}

int QSettingsWrapper::beginReadArray(const QString &param1)
{
    if (createSocket())
        return callRemoteMethod<qint32>(QLatin1String(Protocol::QSettingsBeginReadArray), param1);
    return d->settings.beginReadArray(param1);
}

void QSettingsWrapper::beginWriteArray(const QString &param1, int param2)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsBeginWriteArray), param1, qint32(param2));
    else
        d->settings.beginWriteArray(param1, param2);
}

QStringList QSettingsWrapper::childGroups() const
{
    if (createSocket())
        return callRemoteMethod<QStringList>(QLatin1String(Protocol::QSettingsChildGroups));
    return d->settings.childGroups();
}

QStringList QSettingsWrapper::childKeys() const
{
    if (createSocket())
        return callRemoteMethod<QStringList>(QLatin1String(Protocol::QSettingsChildKeys));
    return d->settings.childKeys();
}

void QSettingsWrapper::clear()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsClear));
    else d->settings.clear();
}

bool QSettingsWrapper::contains(const QString &param1) const
{
    if (createSocket())
        return callRemoteMethod<bool>(QLatin1String(Protocol::QSettingsContains), param1);
    return d->settings.contains(param1);
}

void QSettingsWrapper::endArray()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsEndArray));
    else
        d->settings.endArray();
}

void QSettingsWrapper::endGroup()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsEndGroup));
    else
        d->settings.endGroup();
}

bool QSettingsWrapper::fallbacksEnabled() const
{
    if (createSocket())
        return callRemoteMethod<bool>(QLatin1String(Protocol::QSettingsFallbacksEnabled));
    return d->settings.fallbacksEnabled();
}

QString QSettingsWrapper::fileName() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsFileName));
    return d->settings.fileName();
}

QSettingsWrapper::Format QSettingsWrapper::format() const
{
    // No need to talk to the server, we've setup the local settings object the same way.
    return static_cast<QSettingsWrapper::Format>(d->settings.format());
}

QString QSettingsWrapper::group() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsGroup));
    return d->settings.gr

}

bool QSettingsWrapper::isWritable() const
{
    if (createSocket())
        return callRemoteMethod<bool>(QLatin1String(Protocol::QSettingsIsWritable));
    return d->settings.isWritable();
}

QString QSettingsWrapper::organizationName() const
{
    if (createSocket())
        return callRemoteMethod<QString>(QLatin1String(Protocol::QSettingsOrganizationName));
    return d->settings.organizationName();
}

void QSettingsWrapper::remove(const QString &param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsRemove), param1, dummy);
    else
        d->settings.remove(param1);
}

QSettingsWrapper::Scope QSettingsWrapper::scope() const
{
    // No need to talk to the server, we've setup the local settings object the same way.
    return static_cast<QSettingsWrapper::Scope>(d->settings.scope());
}

void QSettingsWrapper::setArrayIndex(int param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSetArrayIndex), qint32(param1), dummy);
    else
        d->settings.setArrayIndex(param1);
}

void QSettingsWrapper::setFallbacksEnabled(bool param1)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSetFallbacksEnabled), param1, dummy);
    else
        d->settings.setFallbacksEnabled(param1);
}

void QSettingsWrapper::setValue(const QString &param1, const QVariant &param2)
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSetValue), param1, param2);
    else
        d->settings.setValue(param1, param2);
}

QSettingsWrapper::Status QSettingsWrapper::status() const
{
    if (createSocket()) {
        return static_cast<QSettingsWrapper::Status>
            (callRemoteMethod<qint32>(QLatin1String(Protocol::QSettingsStatus)));
    }
    return static_cast<QSettingsWrapper::Status>(d->settings.status());
}

void QSettingsWrapper::sync()
{
    if (createSocket())
        callRemoteMethod(QLatin1String(Protocol::QSettingsSync));
    else
        d->settings.sync();
}

QVariant QSettingsWrapper::value(const QString &param1, const QVariant &param2) const
{
    if (createSocket())
        return callRemoteMethod<QVariant>(QLatin1String(Protocol::QSettingsValue), param1, param2);
    return d->settings.value(param1, param2);
}

bool QSettingsWrapper::createSocket() const
{
    if ((d->m_format != QSettings::NativeFormat) && (d->m_format != QSettings::IniFormat)) {
        Q_ASSERT_X(false, Q_FUNC_INFO, "Settings wrapper only supports QSettingsWrapper::NativeFormat"
                   " and QSettingsWrapper::IniFormat.");
    }
    return (const_cast<QSettingsWrapper *>(this))->connectToServer(QVariantList()
        << d->m_application << d->m_organization << d->m_scope << d->m_format << d->m_filename);
}

} // namespace QInstaller


//                     The LLVM Compiler Infrastructure

// type_traits

// extent

#include <type_traits>

#include "test_macros.h"

template <class T, unsigned A>
void test_extent()
{
    static_assert((std::extent<T>::value == A), "");
    static_assert((std::extent<const T>::value == A), "");
    static_assert((std::extent<volatile T>::value == A), "");
    static_assert((std::extent<const volatile T>::value == A), "");
#if TEST_STD_VER > 14
    static_assert((std::extent_v<T> == A), "");
    static_assert((std::extent_v<const T> == A), "");
    static_assert((std::extent_v<volatile T> == A), "");
    static_assert((std::extent_v<const volatile T> == A), "");
#endif
}

template <class T, unsigned A>

{
    static_assert((std::extent<T, 1>::value == A), "");
    static_assert((std::extent<const T, 1>::value == A), "");
    static_assert((std::extent<volatile T, 1>::value == A), "");
    static_assert((std::extent<const volatile T, 1>::value == A), "");
#if TEST_STD_VER > 14
    static_assert((std::extent_v<T, 1> == A), "");
    static_assert((std::extent_v<const T, 1> == A), "");
    static_assert((std::extent_v<volatile T, 1> == A), "");
    static_assert((std::extent_v<const volatile T, 1> == A), "");
#endif
}

class Class
{
public:
    ~Class();
};

int main()
{
    test_extent<void, 0>();
    test_extent<int&, 0>();
    test_extent<Class, 0>();
    test_extent<int*, 0>();
    test_extent<const int*, 0>();
    test_extent<int, 0>();
    test_extent<double, 0>();
    test_extent<bool, 0>();
    test_extent<unsigned, 0>();

    test_extent<int[2], 2>();
    test_extent<int[2][4], 2>();
    test_extent<int[][4], 0>();

    test_extent1<int, 0>();
    test_extent1<int[2], 0>();
    test_extent1<int[2][4], 4>();
    test_extent1<int[][4], 4>();
}


{
    test_extent<void, 0>();
    test_extent<int&, 0>();
    test_extent<Class, 0>();
    test_extent<int*, 0>();
    test_extent<const int*, 0>();
    test_extent<int, 0>();
    test_extent<double, 0>();
    test_extent<bool, 0>();
    test_extent<unsigned, 0>();

    test_extent<int[2], 2>();
    test_extent<int[2][4], 2>();
    test_extent<int[][4], 0>();

    test_extent1<int, 0>();
    test_extent1<int[2], 0>();
    test_extent1<int[2][4], 4>();
    test_extent1<int[][4], 4>();
}

//                     The LLVM Compiler Infrastructure

// type_traits

// extent

#include <type_traits>

#include "test_macros.h"

template <class T, unsigned A>
void test_extent()
{
    static_assert((std::extent<T>::value == A), "");
    static_assert((std::extent<const T>::value == A), "");
    static_assert((std::extent<volatile T>::value == A), "");
    static_assert((std::extent<const volatile T>::value == A), "");
#if TEST_STD_VER > 14
    static_assert((std::extent_v<T> == A), "");
    static_assert((std::extent_v<const T> == A), "");
    static_assert((std::extent_v<volatile T> == A), "");
    static_assert((std::extent_v<const volatile T> == A), "");
#endif
}

template <class T, unsigned A>
void test_extent1()
{
    static_assert((std::extent<T, 1>::value == A), "");
    static_assert((std::extent<const T, 1>::value == A), "");
    static_assert((std::extent<volatile T, 1>::value == A), "");
    static_assert((std::extent<const volatile T, 1>::value == A), "");
#if TEST_STD_VER > 14
    static_assert((std::extent_v<T, 1> == A), "");
    static_assert((std::extent_v<const T, 1> == A), "");
    static_assert((std::extent_v<volatile T, 1> == A), "");
    static_assert((std::extent_v<const volatile T, 1> == A), "");
#endif
}

class Class
{
public:
    ~Class();
};

int main()


//                     The LLVM Compiler Infrastructure

// type_traits

// extent

#include <type_traits>

#include "test_macros.h"

template <class T, unsigned A>
void test_extent()
{
    static_assert((std::extent<T>::value == A), "");
    static_assert((std::extent<const T>::value == A), "");
    static_assert((std::extent<volatile T>::value == A), "");
    static_assert((std::extent<const volatile T>::value == A), "");
#if TEST_STD_VER > 14
    static_assert((std::extent_v<T> == A), "");
    static_assert((std::extent_v<const T> == A), "");
    static_assert((std::extent_v<volatile T> == A), "");
    static_assert((std::extent_v<const volatile T> == A), "");
#endif
}

template <class T, unsigned A>
void test_extent1()
{
    static_assert((std::extent<T, 1>::value == A), "");
    static_assert((std::extent<const T, 1>::value == A), "");
    static_assert((std::extent<volatile T, 1>::value == A), "");
    static_assert((std::extent<const volatile T, 1>::value == A), "");
#if TEST_STD_VER > 14
    static_assert((std::extent_v<T, 1> == A), "");
    static_assert((std::extent_v<const T, 1> == A), "");
    static_assert((std::extent_v<volatile T, 1> == A), "");
    static_assert((std::extent_v<const volatile T, 1> == A), "");
#endif
}

class Class
{
public:
    ~Class();
};

int main()
{
    test_extent<void, 0>();
    test_extent<int&, 0>();
    test_extent<Class, 0>();
    test_extent<int*, 0>();
    test_extent<const int*, 0>();
    test_extent<int, 0>();
    test_extent<double, 0>();

    test_extent<unsigned, 0>();

    test_extent<int[2], 2>();
    test_extent<int[2][4], 2>();
    test_extent<int[][4], 0>();

    test_extent1<int, 0>();
    test_extent1<int[2], 0>();
    test_extent1<int[2][4], 4>();
    test_extent1<int[][4], 4>();
}


virtual SkOperand2::OpType getReturnType(int /*index*/, SkOperand2* operand)

/*
 *
 */
#include "SkAnimatorScript2.h"
#include "SkAnimateBase.h"
#include "SkAnimateMaker.h"
#include "SkDisplayTypes.h"
#include "SkExtras.h"
#include "SkMemberInfo.h"
#include "SkOpArray.h"
#include "SkParse.h"
#include "SkScript2.h"
#include "SkScriptCallBack.h"

static const SkDisplayEnumMap gEnumMaps[] = {
    { SkType_AddMode, "indirect|immediate" },
    { SkType_Align, "left|center|right" },
    { SkType_ApplyMode, "immediate|once" },
    { SkType_ApplyTransition, "reverse" },
    { SkType_BitmapEncoding, "jpeg|png" },
    { SkType_BitmapFormat, "none|A1|A8|Index8|RGB16|RGB32" },
    { SkType_Boolean, "false|true" },
    { SkType_Cap, "butt|round|square" },
    { SkType_EventCode, "none|up|down|left|right|back|end|OK|send|leftSoftKey|rightSoftKey|key0|key1|key2|key3|key4|key5|key6|key7|key8|key9|star|hash" },
    { SkType_EventKind, "none|keyChar|keyPress|mouseDown|mouseDrag|mouseMove|mouseUp|onEnd|onLoad|user" },
    { SkType_EventMode, "deferred|immediate" },
    { SkType_FillType, "winding|evenOdd" },
    { SkType_FilterType, "none|bilinear" },
    { SkType_FromPathMode, "normal|angle|position" },
    { SkType_Join, "miter|round|blunt" },
    { SkType_MaskFilterBlurStyle, "normal|solid|outer|inner" },
    { SkType_PathDirection, "cw|ccw" },
    { SkType_Style, "fill|stroke|strokeAndFill" },
    { SkType_TextBoxAlign, "start|center|end" },
    { SkType_TextBoxMode, "oneLine|lineBreak" },
    { SkType_TileMode, "clamp|repeat|mirror" },
    { SkType_Xfermode, "clear|src|dst|srcOver|dstOver|srcIn|dstIn|srcOut|dstOut|"
        "srcATop|dstATop|xor|darken|lighten" },
};

static int gEnumMapCount = SK_ARRAY_COUNT(gEnumMaps);

class SkAnimatorScript_Box : public SkScriptCallBackConvert {
public:
    SkAnimatorScript_Box() {}

    ~SkAnimatorScript_Box() {
        for (SkDisplayable** dispPtr = fTrackDisplayable.begin(); dispPtr < fTrackDisplayable.end(); dispPtr++)
            delete *dispPtr;
    }

    virtual bool convert(SkOperand2::OpType type, SkOperand2* operand) {
        SkDisplayable* displayable;
        switch (type) {
            case SkOperand2::kArray: {
                SkDisplayArray* boxedValue = new SkDisplayArray(*operand->fArray);
                displayable = boxedValue;
                } break;
            case SkOperand2::kS32: {
                SkDisplayInt* boxedValue = new SkDisplayInt;
                displayable = boxedValue;
                boxedValue->value = operand->fS32;
                } break;
            case SkOperand2::kScalar: {
                SkDisplayFloat* boxedValue = new SkDisplayFloat;
                displayable = boxedValue;
                boxedValue->value = operand->fScalar;
                } break;
            case SkOperand2::kString: {
                SkDisplayString* boxedValue = new SkDisplayString(*operand->fString);
                displayable = boxedValue;
                } break;
            case SkOperand2::kObject:
                return true;
            default:
                SkASSERT(0);
                return false;
        }
        track(displayable);
        operand->fObject = (void*) displayable;
        return true;
    }

    virtual SkOperand2::OpType getReturnType(int index) {
        return SkOperand2::kObject;
    }

    virtual Type getType() const {
        return kBox;
    }

    void track(SkDisplayable* displayable) {
        SkASSERT(fTrackDisplayable.find(displayable) < 0);
        *fTrackDisplayable.append() = displayable;
    }

    SkTDDisplayableArray fTrackDisplayable;
};

class SkAnimatorScript_Enum : public SkScriptCallBackProperty {
public:
    SkAnimatorScript_Enum(const char* tokens) : fTokens(tokens) {}

    virtual bool getConstValue(const char* name, int len, SkOperand2* value) {
        return SkAnimatorScript2::MapEnums(fTokens, name, len, &value->fS32);
    }

private:
    const char* fTokens;
};

    // !!! if type is string, call invoke
    // if any other type, return original value
        // distinction is undone: could do this by returning index == 0 only if param is string
        // still, caller of getParamTypes will attempt to convert param to string (I guess)
class SkAnimatorScript_Eval : public SkScriptCallBackFunction {
public:
    SkAnimatorScript_Eval(SkAnimatorScript2* engine) : fEngine(engine) {}

    virtual bool getIndex(const char* name, int len, size_t* result) {
        if (SK_LITERAL_STR_EQUAL("eval", name, len) != 0)
            return false;
        *result = 0;
        return true;
    }

    virtual void getParamTypes(SkIntArray(SkOperand2::OpType)* types) {
        types->setCount(1);
        SkOperand2::OpType* type = types->begin();
        type[0] = SkOperand2::kString;
    }

    virtual bool invoke(size_t index, SkOpArray* params, SkOperand2* answer) {
        SkAnimatorScript2 engine(fEngine->getMaker(), fEngine->getWorking(),
            SkAnimatorScript2::ToDisplayType(fEngine->getReturnType()));
        SkOperand2* op = params->begin();
        const char* script = op->fString->c_str();
        SkScriptValue2 value;
        return engine.evaluateScript(&script, &value);
        SkASSERT(value.fType == fEngine->getReturnType());
        *answer = value.fOperand;
        return true;
    }

private:
    SkAnimatorScript2* fEngine;
};

class SkAnimatorScript_ID : public SkScriptCallBackProperty {
public:
    SkAnimatorScript_ID(SkAnimatorScript2* engine) : fEngine(engine) {}

    virtual bool getIndex(const char* token, int len, size_t* result) {
        SkDisplayable* displayable;
        bool success = fEngine->getMaker().find(token, len, &displayable);
        if (success == false) {
            *result = 0;
        } else {
            *result = (size_t) displayable;
            SkDisplayable* working = fEngine->getWorking();
            if (displayable->canContainDependents() && working && working->isAnimate()) {
                SkAnimateBase* animator = (SkAnimateBase*) working;
                if (animator->isDynamic()) {
                    SkDisplayDepend* depend = (SkDisplayDepend* ) displayable;
                    depend->addDependent(working);
                }
            }
        }
        return true;
    }

    virtual bool getResult(size_t ref, SkOperand2* answer) {
        answer->fObject = (void*) ref;
        return true;
    }

    virtual SkOperand2::OpType getReturnType(size_t index) {
        return index == 0 ? SkOperand2::kString : SkOperand2::kObject;
    }

private:
    SkAnimatorScript2* fEngine;
};

class SkAnimatorScript_Member : public SkScriptCallBackMember {
public:

    SkAnimatorScript_Member(SkAnimatorScript2* engine) : fEngine(engine) {}

    bool getMemberReference(const char* member, size_t len, void* object, SkScriptValue2* ref) {
        SkDisplayable* displayable = (SkDisplayable*) object;
        SkString name(member, len);
        SkDisplayable* named = displayable->contains(name);
        if (named) {
            ref->fType = SkOperand2::kObject;
            ref->fOperand.fObject = named;
            return true;
        }
        const SkMemberInfo* info = displayable->getMember(name.c_str());
        if (info == NULL)
            return false;    // !!! add additional error info?
        ref->fType = SkAnimatorScript2::ToOpType(info->getType());
        ref->fOperand.fObject = (void*) info;
        return true;
    }

    bool invoke(size_t ref, void* object, SkOperand2* value) {
        const SkMemberInfo* info = (const SkMemberInfo* ) ref;
        SkDisplayable* displayable = (SkDisplayable*) object;
        if (info->fType == SkType_MemberProperty) {
            if (displayable->getProperty2(info->propertyIndex(), value) == false) {
                return false;
            }
        }
        return fEngine->evalMemberCommon(info, displayable, value);
    }

    SkAnimatorScript2* fEngine;
};

class SkAnimatorScript_MemberFunction : public SkScriptCallBackMemberFunction {
public:
    SkAnimatorScript_MemberFunction(SkAnimatorScript2* engine) : fEngine(engine) {}

    bool getMemberReference(const char* member, size_t len, void* object, SkScriptValue2* ref) {
        SkDisplayable* displayable = (SkDisplayable*) object;
        SkString name(member, len);
        const SkMemberInfo* info = displayable->getMember(name.c_str());
        if (info == NULL || info->fType != SkType_MemberFunction)
            return false;    // !!! add additional error info?
        ref->fType = SkAnimatorScript2::ToOpType(info->getType());
        ref->fOperand.fObject = (void*) info;
        return true;
    }

    virtual void getParamTypes(SkIntArray(SkOperand2::OpType)* types) {
        types->setCount(3);
        SkOperand2::OpType* type = types->begin();
        type[0] = type[1] = type[2] = SkOperand2::kS32;
    }

    bool invoke(size_t ref, void* object, SkOpArray* params, SkOperand2* value)
    {
        const SkMemberInfo* info = (const SkMemberInfo* ) ref;
        SkDisplayable* displayable = (SkDisplayable*) object;
        displayable->executeFunction2(displayable, info->functionIndex(), params, info->getType(),
            value);
        return fEngine->evalMemberCommon(info, displayable, value);
    }

    SkAnimatorScript2* fEngine;
};

class SkAnimatorScript_NamedColor : public SkScriptCallBackProperty {
public:
    virtual bool getConstValue(const char* name, int len, SkOperand2* value) {
        return SkParse::FindNamedColor(name, len, (SkColor*) &value->fS32) != NULL;
    }
};

class SkAnimatorScript_RGB : public SkScriptCallBackFunction {
public:
    virtual bool getIndex(const char* name, int len, size_t* result) {
        if (SK_LITERAL_STR_EQUAL("rgb", name, len) != 0)
            return false;
        *result = 0;
        return true;
    }

    virtual void getParamTypes(SkIntArray(SkOperand2::OpType)* types) {
        types->setCount(3);
        SkOperand2::OpType* type = types->begin();
        type[0] = type[1] = type[2] = SkOperand2::kS32;
    }

    virtual bool invoke(size_t index, SkOpArray* params, SkOperand2* answer) {
        SkASSERT(index == 0);
        unsigned result = 0xFF000000;
        int shift = 16;
        for (int index = 0; index < 3; index++) {
            result |= SkClampMax(params->begin()[index].fS32, 255) << shift;
            shift -= 8;
        }
        answer->fS32 = result;
        return true;
    }

};

class SkAnimatorScript_Unbox : public SkScriptCallBackConvert {
public:
    SkAnimatorScript_Unbox(SkAnimatorScript2* engine) : fEngine(engine) {}

    virtual bool convert(SkOperand2::OpType type, SkOperand2* operand) {
        SkASSERT(type == SkOperand2::kObject);
        SkDisplayable* displayable = (SkDisplayable*) operand->fObject;
        switch (displayable->getType()) {
            case SkType_Array: {
                SkDisplayArray* boxedValue = (SkDisplayArray*) displayable;
                operand->fArray = new SkOpArray(SkAnimatorScript2::ToOpType(boxedValue->values.getType()));
                int count = boxedValue->values.count();
                operand->fArray->setCount(count);
                memcpy(operand->fArray->begin(), boxedValue->values.begin(), count * sizeof(SkOperand2));
                fEngine->track(operand->fArray);
                } break;
            case SkType_Boolean: {
                SkDisplayBoolean* boxedValue = (SkDisplayBoolean*) displayable;
                operand->fS32 = boxedValue->value;
                } break;
            case SkType_Int: {
                SkDisplayInt* boxedValue = (SkDisplayInt*) displayable;
                operand->fS32 = boxedValue->value;
                } break;
            case SkType_Float: {
                SkDisplayFloat* boxedValue = (SkDisplayFloat*) displayable;
                operand->fScalar = boxedValue->value;
                } break;
            case SkType_String: {
                SkDisplayString* boxedValue = (SkDisplayString*) displayable;
                operand->fString = SkNEW_ARGS(SkString, (boxedValue->value));
                } break;
            default: {
                const char* id;
                bool success = fEngine->getMaker().findKey(displayable, &id);
                SkASSERT(success);
                operand->fString = SkNEW_ARGS(SkString, (id));
            }
        }
        return true;
    }

{
        SkDisplayable* displayable = (SkDisplayable*) operand->fObject;
        switch (displayable->getType()) {
            case SkType_Array:
                return SkOperand2::kArray;
            case SkType_Int:
                return SkOperand2::kS32;
            case SkType_Float:
                return SkOperand2::kScalar;
            case SkType_String:
            default:
                return SkOperand2::kString;
        }
    }

    virtual Type getType() const {
        return kUnbox;
    }

    SkAnimatorScript2* fEngine;
};

SkAnimatorScript2::SkAnimatorScript2(SkAnimateMaker& maker, SkDisplayable* working, SkDisplayTypes type) :
        SkScriptEngine2(ToOpType(type)), fMaker(maker), fWorking(working) {
    *fCallBackArray.append() = new SkAnimatorScript_Member(this);
    *fCallBackArray.append() = new SkAnimatorScript_MemberFunction(this);
    *fCallBackArray.append() = new SkAnimatorScript_Box();
    *fCallBackArray.append() = new SkAnimatorScript_Unbox(this);
    *fCallBackArray.append() = new SkAnimatorScript_ID(this);
    if (type == SkType_ARGB) {
        *fCallBackArray.append() = new SkAnimatorScript_RGB();
        *fCallBackArray.append() = new SkAnimatorScript_NamedColor();
    }
    if (SkDisplayType::IsEnum(&maker, type)) {
        // !!! for SpiderMonkey, iterate through the enum values, and map them to globals
        const SkDisplayEnumMap& map = GetEnumValues(type);
        *fCallBackArray.append() = new SkAnimatorScript_Enum(map.fValues);
    }
    *fCallBackArray.append() = new SkAnimatorScript_Eval(this);
#if 0        // !!! no extra support for now
    for (SkExtras** extraPtr = maker.fExtras.begin(); extraPtr < maker.fExtras.end(); extraPtr++) {
        SkExtras* extra = *extraPtr;
        if (extra->fExtraCallBack)
            *fCallBackArray.append() = new propertyCallBack(extra->fExtraCallBack, extra->fExtraStorage);
    }
#endif
}

SkAnimatorScript2::~SkAnimatorScript2() {
    SkScriptCallBack** end = fCallBackArray.end();
    for (SkScriptCallBack** ptr = fCallBackArray.begin(); ptr < end; ptr++)
        delete *ptr;
}

bool SkAnimatorScript2::evalMemberCommon(const SkMemberInfo* info,
        SkDisplayable* displayable, SkOperand2* value) {
    SkDisplayTypes original;
    SkDisplayTypes type = original = (SkDisplayTypes) info->getType();
    if (info->fType == SkType_Array)
        type = SkType_Array;
    switch (type) {
        case SkType_ARGB:
            type = SkType_Int;
        case SkType_Boolean:
        case SkType_Int:
        case SkType_MSec:
        case SkType_Float:
            SkASSERT(info->getCount() == 1);
            if (info->fType != SkType_MemberProperty && info->fType != SkType_MemberFunction)
                value->fS32 = *(int32_t*) info->memberData(displayable);    // OK for SkScalar too
            if (type == SkType_MSec) {
                value->fScalar = value->fS32 * 0.001f;
                type = SkType_Float;
            }
            break;
        case SkType_String: {
            SkString* displayableString;
            if (info->fType != SkType_MemberProperty && info->fType != SkType_MemberFunction) {
                info->getString(displayable, &displayableString);
                value->fString = new SkString(*displayableString);
            }
            } break;
        case SkType_Array: {
            SkASSERT(info->fType != SkType_MemberProperty); // !!! incomplete
            SkTDOperandArray* displayableArray = (SkTDOperandArray*) info->memberData(displayable);
            if (displayable->getType() == SkType_Array) {
                SkDisplayArray* typedArray = (SkDisplayArray*) displayable;
                original = typedArray->values.getType();
            }
            SkASSERT(original != SkType_Unknown);
            SkOpArray* array = value->fArray = new SkOpArray(ToOpType(original));
            track(array);
            int count = displayableArray->count();
            if (count > 0) {
                array->setCount(count);
                memcpy(array->begin(), displayableArray->begin(), count * sizeof(SkOperand2));
            }
            } break;
        default:
            SkASSERT(0); // unimplemented
    }
    return true;
}

const SkDisplayEnumMap& SkAnimatorScript2::GetEnumValues(SkDisplayTypes type) {
    int index = SkTSearch<SkDisplayTypes>(&gEnumMaps[0].fType, gEnumMapCount, type,
        sizeof(SkDisplayEnumMap));
    SkASSERT(index >= 0);
    return gEnumMaps[index];
}

SkDisplayTypes SkAnimatorScript2::ToDisplayType(SkOperand2::OpType type) {
    int val = type;
    switch (val) {
        case SkOperand2::kNoType:
            return SkType_Unknown;
        case SkOperand2::kS32:
            return SkType_Int;
        case SkOperand2::kScalar:
            return SkType_Float;
        case SkOperand2::kString:
            return SkType_String;
        case SkOperand2::kArray:
            return SkType_Array;
        case SkOperand2::kObject:
            return SkType_Displayable;
        default:
            SkASSERT(0);
            return SkType_Unknown;
    }
}

SkOperand2::OpType SkAnimatorScript2::ToOpType(SkDisplayTypes type) {
    if (SkDisplayType::IsDisplayable(NULL /* fMaker */, type))
        return SkOperand2::kObject;
    if (SkDisplayType::IsEnum(NULL /* fMaker */, type))
        return SkOperand2::kS32;
    switch (type) {
        case SkType_ARGB:
        case SkType_MSec:
        case SkType_Int:
            return SkOperand2::kS32;
        case SkType_Float:
        case SkType_Point:
        case SkType_3D_Point:
            return SkOperand2::kScalar;
        case SkType_Base64:
        case SkType_DynamicString:
        case SkType_String:
            return SkOperand2::kString;
        case SkType_Array:
            return SkOperand2::kArray;
        case SkType_Unknown:
            return SkOperand2::kNoType;
        default:
            SkASSERT(0);
            return SkOperand2::kNoType;
    }
}

bool SkAnimatorScript2::MapEnums(const char* ptr, const char* match, size_t len, int* value) {
    int index = 0;
    bool more = true;
    do {
        const char* last = strchr(ptr, '|');
        if (last == NULL) {
            last = &ptr[strlen(ptr)];
            more = false;
        }
        size_t length = last - ptr;
        if (len == length && strncmp(ptr, match, length) == 0) {
            *value = index;
            return true;
        }
        index++;
        ptr = last + 1;
    } while (more);
    return false;
}

#if defined SK_DEBUG

#include "SkAnimator.h"

static const char scriptTestSetup[]  =
"<screenplay>"
    "<apply>"
        "<paint>"
            "<emboss id='emboss' direction='[1,1,1]'  />"
        "</paint>"
        "<animateField id='animation' field='direction' target='emboss' from='[1,1,1]' to='[-1,1,1]' dur='1'/>"
        "<set lval='direction[0]' target='emboss' to='-1' />"
    "</apply>"
    "<color id='testColor' color='0 ? rgb(0,0,0) : rgb(255,255,255)' />"
    "<color id='xColor' color='rgb(12,34,56)' />"
    "<typedArray id='emptyArray' />"
    "<typedArray id='intArray' values='[1, 4, 6]' />"
    "<s32 id='idx' value='2' />"
    "<s32 id='idy' value='2' />"
    "<string id='alpha' value='abc' />"
    "<rectangle id='testRect' left='Math.cos(0)' top='2' right='12' bottom='5' />"
    "<event id='evt'>"
        "<input name='x' />"
        "<apply scope='idy'>"
            "<set field='value' to='evt.x.s32' />"
        "</apply>"
    "</event>"
"</screenplay>";

static const SkScriptNAnswer scriptTests[]  = {
    {    "alpha+alpha", SkType_String, 0, 0, "abcabc" },
    {    "0 ? Math.sin(0) : 1", SkType_Int, 1 },
    {    "intArray[4]", SkType_Unknown },
    {    "emptyArray[4]", SkType_Unknown },
    {    "idx", SkType_Int, 2 },
    {    "intArray.length", SkType_Int, 3 },
    {    "intArray.values[0]", SkType_Int, 1 },
    {    "intArray[0]", SkType_Int, 1 },
    {    "idx.value", SkType_Int, 2 },
    {    "alpha.value", SkType_String, 0, 0, "abc" },
    {    "alpha", SkType_String, 0, 0, "abc" },
    {    "alpha.value+alpha.value", SkType_String, 0, 0, "abcabc" },
    {    "alpha+idx", SkType_String, 0, 0, "abc2" },
    {    "idx+alpha", SkType_String, 0, 0, "2abc" },
    {    "intArray[idx]", SkType_Int, 6 },
    {    "alpha.slice(1,2)", SkType_String, 0, 0, "b" },
    {    "alpha.value.slice(1,2)", SkType_String, 0, 0, "b" },
    {    "Math.sin(0)", SkType_Float, 0, SkIntToScalar(0) },
    {    "testRect.left+2", SkType_Float, 0, SkIntToScalar(3) },
    {    "0 ? intArray[0] : 1", SkType_Int, 1 },
    {    "0 ? intArray.values[0] : 1", SkType_Int, 1 },
    {    "0 ? idx : 1", SkType_Int, 1 },
    {    "0 ? idx.value : 1", SkType_Int, 1 },
    {    "0 ? alpha.slice(1,2) : 1", SkType_Int, 1 },
    {    "0 ? alpha.value.slice(1,2) : 1", SkType_Int, 1 },
    { "idy", SkType_Int, 3 }
};

#define SkScriptNAnswer_testCount    SK_ARRAY_COUNT(scriptTests)

void SkAnimatorScript2::UnitTest() {
#if defined(SK_SUPPORT_UNITTEST)
    SkAnimator animator;
    SkASSERT(animator.decodeMemory(scriptTestSetup, sizeof(scriptTestSetup)-1));
    SkEvent evt;
    evt.setString("id", "evt");
    evt.setS32("x", 3);
    animator.doUserEvent(evt);
    // set up animator with memory script above, then run value tests
    for (int index = 0; index < SkScriptNAnswer_testCount; index++) {
        SkAnimatorScript2 engine(*animator.fMaker, NULL, scriptTests[index].fType);
        SkScriptValue2 value;
        const char* script = scriptTests[index].fScript;
        bool success = engine.evaluateScript(&script, &value);
        if (success == false) {
            SkASSERT(scriptTests[index].fType == SkType_Unknown);
            continue;
        }
        SkASSERT(value.fType == ToOpType(scriptTests[index].fType));
        SkScalar error;
        switch (value.fType) {
            case SkOperand2::kS32:
                SkASSERT(value.fOperand.fS32 == scriptTests[index].fIntAnswer);
                break;
            case SkOperand2::kScalar:
                error = SkScalarAbs(value.fOperand.fScalar - scriptTests[index].fScalarAnswer);
                SkASSERT(error < SK_Scalar1 / 10000);
                break;
            case SkOperand2::kString:
                SkASSERT(value.fOperand.fString->equals(scriptTests[index].fStringAnswer));
                break;
            default:
                SkASSERT(0);
        }
    }
#endif
}

#endif