<commit_before>/** Copyright (c) 2013, Sean Kasun */

#include <algorithm>

#include "./chunk.h"
#include "./flatteningconverter.h"
#include "./blockidentifier.h"

template<typename _ValueT>
inline void* safeMemCpy(void* __dest, const std::vector<_ValueT>& __src, size_t __len)
{
  const size_t src_data_size = (sizeof(_ValueT) * __src.size());
    if (__len > src_data_size)
    {
      __len = src_data_size; // this happens sometimes and I guess its then actually a bug in the load() implementation. But this way it at least doesn't crash randomly.
    }

    return memcpy(__dest, &__src[0], __len);
}

quint16 getBits(const unsigned char *data, int pos, int n) {
//  quint16 result = 0;
  int arrIndex = pos/8;
  int bitIndex = pos%8;
  quint32 loc =
    data[arrIndex]   << 24 |
    data[arrIndex+1] << 16 |
    data[arrIndex+2] << 8  |
    data[arrIndex+3];

  return ((loc >> (32-bitIndex-n)) & ((1 << n) -1));
}

Chunk::Chunk()
  : version(0)
  , highest(0)
  , loaded(false)
  , rendering(false)
{}

Chunk::~Chunk() {
  if (loaded) {
    for (int i = 0; i < 16; i++)
      if (sections[i]) {
        if (sections[i]->paletteLength > 0) {
          delete[] sections[i]->palette;
        }
        sections[i]->paletteLength = 0;
        sections[i]->palette = NULL;

        delete sections[i];
        sections[i] = NULL;
      }
  }
}

int Chunk::get_biome(int x, int z) {
  return get_biome(x, 64, z);
}

int Chunk::get_biome(int x, int y, int z) {
  int offset;

  if (this->version >= 2203) {
    // Minecraft 1.15 has Y dependand Biome
    int x_idx = x >> 2;
    int y_idx = y >> 2;
    int z_idx = z >> 2;
    offset = x_idx + 4*z_idx + 16*y_idx;
  } else {
    // Minecraft <1.15 has fixed Biome per collumn
    offset = x + 16*z;
  }

  return get_biome(offset);
}

int Chunk::get_biome(int offset) {
  return this->biomes[offset];
}

void Chunk::load(const NBT &nbt) {
  renderedAt = -1;  // impossible.
  renderedFlags = 0;  // no flags
  for (int i = 0; i < 16; i++)
    this->sections[i] = NULL;

  if (nbt.has("DataVersion"))
    this->version = nbt.at("DataVersion")->toInt();
  const Tag * level = nbt.at("Level");
  chunkX = level->at("xPos")->toInt();
  chunkZ = level->at("zPos")->toInt();

  // load Biome data
  if (level->has("Biomes")) {
    const Tag_Int_Array * biomes = dynamic_cast<const Tag_Int_Array*>(level->at("Biomes"));
    if (biomes) {  // Biomes is a Tag_Int_Array
      if ((this->version >= 2203)) {
        // raw copy Biome data
        safeMemCpy(this->biomes, biomes->toIntArray(), sizeof(int)*1024);
      } else if ((this->version >= 1519)) {
        // raw copy Biome data
        safeMemCpy(this->biomes, biomes->toIntArray(), sizeof(int)*256);
      }
    } else {  // Biomes is not a Tag_Int_Array
      const Tag_Byte_Array * biomes = dynamic_cast<const Tag_Byte_Array*>(level->at("Biomes"));
      // convert quint8 to quint32
      auto rawBiomes = biomes->toByteArray();
      for (int i=0; i<256; i++) {
        this->biomes[i] = rawBiomes[i];
      }
    }
  } else {  // no Biome data present
    for (int i=0; i<16*16*4; i++)
      this->biomes[i] = -1;
  }

  // load available Sections
  if (level->has("Sections")) {
    auto sections = level->at("Sections");
    int numSections = sections->length();
    // loop over all stored Sections, they are not guarantied to be ordered or consecutive
    for (int s = 0; s < numSections; s++) {
      const Tag * section = sections->at(s);
      int idx = section->at("Y")->toInt();
      // only sections 0..15 contain block data
      if ((idx >=0) && (idx <16)) {
        ChunkSection *cs = new ChunkSection();
        if (this->version >= 1519) {
          loadSection1519(cs, section);
        } else {
          loadSection1343(cs, section);
        }

        this->sections[idx] = cs;
      }
    }
  }

  // parse Structures that start in this Chunk
  if (version >= 1519) {
    if (level->has("Structures")) {
      auto nbtListStructures = level->at("Structures");
      auto structurelist     = GeneratedStructure::tryParseChunk(nbtListStructures);
      for (auto it = structurelist.begin(); it != structurelist.end(); ++it) {
        emit structureFound(*it);
      }
    }
  }

  // parse Entities
  if (level->has("Entities")) {
    auto entitylist = level->at("Entities");
    int numEntities = entitylist->length();
    for (int i = 0; i < numEntities; ++i) {
      auto e = Entity::TryParse(entitylist->at(i));
      if (e)
        entities.insertMulti(e->type(), e);
    }
  }

  // check for the highest block in this chunk
  // todo: use highmap from stored NBT data
  findHighestBlock();

  loaded = true; // needs to be at the end!
}

void Chunk::findHighestBlock()
{
  for (int i = 15; i >= 0; i--) {
    if (this->sections[i]) {
      for (int j = 4095; j >= 0; j--) {
        if (this->sections[i]->blocks[j]) {
          highest = i * 16 + (j >> 8);
          return;
        }
      }
    }
  }
}

const Chunk::EntityMap &Chunk::getEntityMap() const {
  return entities;
}

const ChunkSection *Chunk::getSectionByY(int y) const {
  size_t section_idx = static_cast<size_t>(y) >> 4;
  if (section_idx >= sections.size())
    return nullptr;

  return sections[section_idx];
}

uint Chunk::getBlockHid(int x, int y, int z) const {
  const ChunkSection * const section = getSectionByY(y);
  if (!section) {
    return 0;
  }

  const PaletteEntry& pdata = section->getPaletteEntry(x, y, z);

  return pdata.hid;
}

// supported DataVersions:
//    0 = 1.8 and below
//
//  169 = 1.9
//  175 = 1.9.1
//  176 = 1.9.2
//  183 = 1.9.3
//  184 = 1.9.4
//
//  510 = 1.10
//  511 = 1.10.1
//  512 = 1.10.2
//
//  819 = 1.11
//  921 = 1.11.1
//  922 = 1.11.2
//
// 1139 = 1.12
// 1241 = 1.12.1
// 1343 = 1.12.2
//
// 1519 = 1.13
// 1628 = 1.13.1
// 2203 = 1.15.19w36a
void Chunk::loadSection1343(ChunkSection *cs, const Tag *section) {
  // copy raw data
  quint8 blocks[4096];
  quint8 data[2048];
  safeMemCpy(blocks, section->at("Blocks")->toByteArray(), 4096);
  safeMemCpy(data,   section->at("Data")->toByteArray(),   2048);
  safeMemCpy(cs->blockLight, section->at("BlockLight")->toByteArray(), 2048);

  // convert old BlockID + data into virtual ID
  for (int i = 0; i < 4096; i++) {
    int d = data[i>>1];         // get raw data (two nibbles)
    if (i & 1) d >>= 4;         // get one nibble of data
    cs->blocks[i] = blocks[i] | ((d & 0x0f) << 8);
  }

  // parse optional "Add" part for higher block IDs in mod packs
  if (section->has("Add")) {
    auto raw = section->at("Add")->toByteArray();
    for (int i = 0; i < 2048; i++) {
      cs->blocks[i * 2] |= (raw[i] & 0xf) << 8;
      cs->blocks[i * 2 + 1] |= (raw[i] & 0xf0) << 4;
    }
  }

  // link to Converter palette
  cs->paletteLength = 0;
  cs->palette = FlatteningConverter::Instance().getPalette();
}

// Chunk format after "The Flattening" version 1509
void Chunk::loadSection1519(ChunkSection *cs, const Tag *section) {
  BlockIdentifier &bi = BlockIdentifier::Instance();
  // decode Palette to be able to map BlockStates
  if (section->has("Palette")) {
    auto rawPalette = section->at("Palette");
    cs->paletteLength = rawPalette->length();
    cs->palette = new PaletteEntry[cs->paletteLength];
    for (int j = 0; j < rawPalette->length(); j++) {
      // get name and hash it to hid
      cs->palette[j].name = rawPalette->at(j)->at("Name")->toString();
      uint hid  = qHash(cs->palette[j].name);
      // copy all other properties
      if (rawPalette->at(j)->has("Properties"))
      cs->palette[j].properties = rawPalette->at(j)->at("Properties")->getData().toMap();

      // check vor variants
      BlockInfo const & block = bi.getBlockInfo(hid);
      if (block.hasVariants()) {
      // test all available properties
      for (auto key : cs->palette[j].properties.keys()) {
        QString vname = cs->palette[j].name + ":" + key + ":" + cs->palette[j].properties[key].toString();
        uint vhid = qHash(vname);
        if (bi.hasBlockInfo(vhid))
          hid = vhid; // use this vaiant instead
        }
      }
      // store hash of found variant
      cs->palette[j].hid  = hid;
    }
  } else {
    // create a dummy palette
    cs->palette = new PaletteEntry[1];
    cs->palette[0].name = "minecraft:air";
    cs->palette[0].hid  = 0;
  }

  // map BlockStates to BlockData
  // todo: bit fidling looks very complicated -> find easier code
  if (section->has("BlockStates")) {
    auto raw = section->at("BlockStates")->toLongArray();
    int blockStatesLength = section->at("BlockStates")->length();
    unsigned char *byteData = new unsigned char[8*blockStatesLength];
    safeMemCpy(byteData, raw, 8*blockStatesLength);
    std::reverse(byteData, byteData+(8*blockStatesLength));
    int bitSize = (blockStatesLength)*64/4096;
    for (int i = 0; i < 4096; i++) {
      cs->blocks[4095-i] = getBits(byteData, i*bitSize, bitSize);
    }
    delete[] byteData;
  } else {
    // set everything to 0 (minecraft:air)
    memset(cs->blocks, 0, sizeof(cs->blocks));
  }

    // copy Light data
//  if (section->has("SkyLight")) {
//    safeMemCpy(cs->skyLight, section->at("SkyLight")->toByteArray(), 2048);
//  }
  if (section->has("BlockLight")) {
    safeMemCpy(cs->blockLight, section->at("BlockLight")->toByteArray(), 2048);
  }
}

const PaletteEntry & ChunkSection::getPaletteEntry(int x, int y, int z) const {
  int xoffset = (x & 0x0f);
  int yoffset = (y & 0x0f) << 8;
  int zoffset = z << 4;
  return palette[blocks[xoffset + yoffset + zoffset]];
}

const PaletteEntry & ChunkSection::getPaletteEntry(int offset, int y) const {
  int yoffset = (y & 0x0f) << 8;
  return palette[blocks[offset + yoffset]];
}

//quint8 ChunkSection::getSkyLight(int x, int y, int z) {
//  int xoffset = x;
//  int yoffset = (y & 0x0f) << 8;
//  int zoffset = z << 4;
//  int value = skyLight[(xoffset + yoffset + zoffset) / 2];
//  if (x & 1) value >>= 4;
//  return value & 0x0f;
//}

//quint8 ChunkSection::getSkyLight(int offset, int y) {
//  int yoffset = (y & 0x0f) << 8;
//  int value = skyLight[(offset + yoffset) / 2];
//  if (offset & 1) value >>= 4;
//  return value & 0x0f;
//}

quint8 ChunkSection::getBlockLight(int x, int y, int z) const {
  int xoffset = x;
  int yoffset = (y & 0x0f) << 8;
  int zoffset = z << 4;
  int value = blockLight[(xoffset + yoffset + zoffset) / 2];
  if (x & 1) value >>= 4;
  return value & 0x0f;
}

quint8 ChunkSection::getBlockLight(int offset, int y) const {
  int yoffset = (y & 0x0f) << 8;
  int value = blockLight[(offset + yoffset) / 2];
  if (offset & 1) value >>= 4;
  return value & 0x0f;
}
<commit_msg>don't use underscores in names<commit_after>/** Copyright (c) 2013, Sean Kasun */

#include <algorithm>

#include "./chunk.h"
#include "./flatteningconverter.h"
#include "./blockidentifier.h"

template<typename ValueT>
inline void* safeMemCpy(void* dest, const std::vector<ValueT>& srcVec, size_t length)
{
  const size_t src_data_size = (sizeof(ValueT) * srcVec.size());
    if (length > src_data_size)
    {
      length = src_data_size; // this happens sometimes and I guess its then actually a bug in the load() implementation. But this way it at least doesn't crash randomly.
    }

    return memcpy(dest, &srcVec[0], length);
}

quint16 getBits(const unsigned char *data, int pos, int n) {
//  quint16 result = 0;
  int arrIndex = pos/8;
  int bitIndex = pos%8;
  quint32 loc =
    data[arrIndex]   << 24 |
    data[arrIndex+1] << 16 |
    data[arrIndex+2] << 8  |
    data[arrIndex+3];

  return ((loc >> (32-bitIndex-n)) & ((1 << n) -1));
}

Chunk::Chunk()
  : version(0)
  , highest(0)
  , loaded(false)
  , rendering(false)
{}

Chunk::~Chunk() {
  if (loaded) {
    for (int i = 0; i < 16; i++)
      if (sections[i]) {
        if (sections[i]->paletteLength > 0) {
          delete[] sections[i]->palette;
        }
        sections[i]->paletteLength = 0;
        sections[i]->palette = NULL;

        delete sections[i];
        sections[i] = NULL;
      }
  }
}

int Chunk::get_biome(int x, int z) {
  return get_biome(x, 64, z);
}

int Chunk::get_biome(int x, int y, int z) {
  int offset;

  if (this->version >= 2203) {
    // Minecraft 1.15 has Y dependand Biome
    int x_idx = x >> 2;
    int y_idx = y >> 2;
    int z_idx = z >> 2;
    offset = x_idx + 4*z_idx + 16*y_idx;
  } else {
    // Minecraft <1.15 has fixed Biome per collumn
    offset = x + 16*z;
  }

  return get_biome(offset);
}

int Chunk::get_biome(int offset) {
  return this->biomes[offset];
}

void Chunk::load(const NBT &nbt) {
  renderedAt = -1;  // impossible.
  renderedFlags = 0;  // no flags
  for (int i = 0; i < 16; i++)
    this->sections[i] = NULL;

  if (nbt.has("DataVersion"))
    this->version = nbt.at("DataVersion")->toInt();
  const Tag * level = nbt.at("Level");
  chunkX = level->at("xPos")->toInt();
  chunkZ = level->at("zPos")->toInt();

  // load Biome data
  if (level->has("Biomes")) {
    const Tag_Int_Array * biomes = dynamic_cast<const Tag_Int_Array*>(level->at("Biomes"));
    if (biomes) {  // Biomes is a Tag_Int_Array
      if ((this->version >= 2203)) {
        // raw copy Biome data
        safeMemCpy(this->biomes, biomes->toIntArray(), sizeof(int)*1024);
      } else if ((this->version >= 1519)) {
        // raw copy Biome data
        safeMemCpy(this->biomes, biomes->toIntArray(), sizeof(int)*256);
      }
    } else {  // Biomes is not a Tag_Int_Array
      const Tag_Byte_Array * biomes = dynamic_cast<const Tag_Byte_Array*>(level->at("Biomes"));
      // convert quint8 to quint32
      auto rawBiomes = biomes->toByteArray();
      for (int i=0; i<256; i++) {
        this->biomes[i] = rawBiomes[i];
      }
    }
  } else {  // no Biome data present
    for (int i=0; i<16*16*4; i++)
      this->biomes[i] = -1;
  }

  // load available Sections
  if (level->has("Sections")) {
    auto sections = level->at("Sections");
    int numSections = sections->length();
    // loop over all stored Sections, they are not guarantied to be ordered or consecutive
    for (int s = 0; s < numSections; s++) {
      const Tag * section = sections->at(s);
      int idx = section->at("Y")->toInt();
      // only sections 0..15 contain block data
      if ((idx >=0) && (idx <16)) {
        ChunkSection *cs = new ChunkSection();
        if (this->version >= 1519) {
          loadSection1519(cs, section);
        } else {
          loadSection1343(cs, section);
        }

        this->sections[idx] = cs;
      }
    }
  }

  // parse Structures that start in this Chunk
  if (version >= 1519) {
    if (level->has("Structures")) {
      auto nbtListStructures = level->at("Structures");
      auto structurelist     = GeneratedStructure::tryParseChunk(nbtListStructures);
      for (auto it = structurelist.begin(); it != structurelist.end(); ++it) {
        emit structureFound(*it);
      }
    }
  }

  // parse Entities
  if (level->has("Entities")) {
    auto entitylist = level->at("Entities");
    int numEntities = entitylist->length();
    for (int i = 0; i < numEntities; ++i) {
      auto e = Entity::TryParse(entitylist->at(i));
      if (e)
        entities.insertMulti(e->type(), e);
    }
  }

  // check for the highest block in this chunk
  // todo: use highmap from stored NBT data
  findHighestBlock();

  loaded = true; // needs to be at the end!
}

void Chunk::findHighestBlock()
{
  for (int i = 15; i >= 0; i--) {
    if (this->sections[i]) {
      for (int j = 4095; j >= 0; j--) {
        if (this->sections[i]->blocks[j]) {
          highest = i * 16 + (j >> 8);
          return;
        }
      }
    }
  }
}

const Chunk::EntityMap &Chunk::getEntityMap() const {
  return entities;
}

const ChunkSection *Chunk::getSectionByY(int y) const {
  size_t section_idx = static_cast<size_t>(y) >> 4;
  if (section_idx >= sections.size())
    return nullptr;

  return sections[section_idx];
}

uint Chunk::getBlockHid(int x, int y, int z) const {
  const ChunkSection * const section = getSectionByY(y);
  if (!section) {
    return 0;
  }

  const PaletteEntry& pdata = section->getPaletteEntry(x, y, z);

  return pdata.hid;
}

// supported DataVersions:
//    0 = 1.8 and below
//
//  169 = 1.9
//  175 = 1.9.1
//  176 = 1.9.2
//  183 = 1.9.3
//  184 = 1.9.4
//
//  510 = 1.10
//  511 = 1.10.1
//  512 = 1.10.2
//
//  819 = 1.11
//  921 = 1.11.1
//  922 = 1.11.2
//
// 1139 = 1.12
// 1241 = 1.12.1
// 1343 = 1.12.2
//
// 1519 = 1.13
// 1628 = 1.13.1
// 2203 = 1.15.19w36a
void Chunk::loadSection1343(ChunkSection *cs, const Tag *section) {
  // copy raw data
  quint8 blocks[4096];
  quint8 data[2048];
  safeMemCpy(blocks, section->at("Blocks")->toByteArray(), 4096);
  safeMemCpy(data,   section->at("Data")->toByteArray(),   2048);
  safeMemCpy(cs->blockLight, section->at("BlockLight")->toByteArray(), 2048);

  // convert old BlockID + data into virtual ID
  for (int i = 0; i < 4096; i++) {
    int d = data[i>>1];         // get raw data (two nibbles)
    if (i & 1) d >>= 4;         // get one nibble of data
    cs->blocks[i] = blocks[i] | ((d & 0x0f) << 8);
  }

  // parse optional "Add" part for higher block IDs in mod packs
  if (section->has("Add")) {
    auto raw = section->at("Add")->toByteArray();
    for (int i = 0; i < 2048; i++) {
      cs->blocks[i * 2] |= (raw[i] & 0xf) << 8;
      cs->blocks[i * 2 + 1] |= (raw[i] & 0xf0) << 4;
    }
  }

  // link to Converter palette
  cs->paletteLength = 0;
  cs->palette = FlatteningConverter::Instance().getPalette();
}

// Chunk format after "The Flattening" version 1509
void Chunk::loadSection1519(ChunkSection *cs, const Tag *section) {
  BlockIdentifier &bi = BlockIdentifier::Instance();
  // decode Palette to be able to map BlockStates
  if (section->has("Palette")) {
    auto rawPalette = section->at("Palette");
    cs->paletteLength = rawPalette->length();
    cs->palette = new PaletteEntry[cs->paletteLength];
    for (int j = 0; j < rawPalette->length(); j++) {
      // get name and hash it to hid
      cs->palette[j].name = rawPalette->at(j)->at("Name")->toString();
      uint hid  = qHash(cs->palette[j].name);
      // copy all other properties
      if (rawPalette->at(j)->has("Properties"))
      cs->palette[j].properties = rawPalette->at(j)->at("Properties")->getData().toMap();

      // check vor variants
      BlockInfo const & block = bi.getBlockInfo(hid);
      if (block.hasVariants()) {
      // test all available properties
      for (auto key : cs->palette[j].properties.keys()) {
        QString vname = cs->palette[j].name + ":" + key + ":" + cs->palette[j].properties[key].toString();
        uint vhid = qHash(vname);
        if (bi.hasBlockInfo(vhid))
          hid = vhid; // use this vaiant instead
        }
      }
      // store hash of found variant
      cs->palette[j].hid  = hid;
    }
  } else {
    // create a dummy palette
    cs->palette = new PaletteEntry[1];
    cs->palette[0].name = "minecraft:air";
    cs->palette[0].hid  = 0;
  }

  // map BlockStates to BlockData
  // todo: bit fidling looks very complicated -> find easier code
  if (section->has("BlockStates")) {
    auto raw = section->at("BlockStates")->toLongArray();
    int blockStatesLength = section->at("BlockStates")->length();
    unsigned char *byteData = new unsigned char[8*blockStatesLength];
    safeMemCpy(byteData, raw, 8*blockStatesLength);
    std::reverse(byteData, byteData+(8*blockStatesLength));
    int bitSize = (blockStatesLength)*64/4096;
    for (int i = 0; i < 4096; i++) {
      cs->blocks[4095-i] = getBits(byteData, i*bitSize, bitSize);
    }
    delete[] byteData;
  } else {
    // set everything to 0 (minecraft:air)
    memset(cs->blocks, 0, sizeof(cs->blocks));
  }

    // copy Light data
//  if (section->has("SkyLight")) {
//    safeMemCpy(cs->skyLight, section->at("SkyLight")->toByteArray(), 2048);
//  }
  if (section->has("BlockLight")) {
    safeMemCpy(cs->blockLight, section->at("BlockLight")->toByteArray(), 2048);
  }
}

const PaletteEntry & ChunkSection::getPaletteEntry(int x, int y, int z) const {
  int xoffset = (x & 0x0f);
  int yoffset = (y & 0x0f) << 8;
  int zoffset = z << 4;
  return palette[blocks[xoffset + yoffset + zoffset]];
}

const PaletteEntry & ChunkSection::getPaletteEntry(int offset, int y) const {
  int yoffset = (y & 0x0f) << 8;
  return palette[blocks[offset + yoffset]];
}

//quint8 ChunkSection::getSkyLight(int x, int y, int z) {
//  int xoffset = x;
//  int yoffset = (y & 0x0f) << 8;
//  int zoffset = z << 4;
//  int value = skyLight[(xoffset + yoffset + zoffset) / 2];
//  if (x & 1) value >>= 4;
//  return value & 0x0f;
//}

//quint8 ChunkSection::getSkyLight(int offset, int y) {
//  int yoffset = (y & 0x0f) << 8;
//  int value = skyLight[(offset + yoffset) / 2];
//  if (offset & 1) value >>= 4;
//  return value & 0x0f;
//}

quint8 ChunkSection::getBlockLight(int x, int y, int z) const {
  int xoffset = x;
  int yoffset = (y & 0x0f) << 8;
  int zoffset = z << 4;
  int value = blockLight[(xoffset + yoffset + zoffset) / 2];
  if (x & 1) value >>= 4;
  return value & 0x0f;
}

quint8 ChunkSection::getBlockLight(int offset, int y) const {
  int yoffset = (y & 0x0f) << 8;
  int value = blockLight[(offset + yoffset) / 2];
  if (offset & 1) value >>= 4;
  return value & 0x0f;
}
<|endoftext|>


<commit_before>#include "AddCoupledEqSpeciesKernelsAction.h"
#include "Parser.h"
#include "FEProblem.h"
#include "Factory.h"
#include "MooseEnum.h"

#include <sstream>
#include <stdexcept>

// libMesh includes
#include "libmesh/libmesh.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/equation_systems.h"
#include "libmesh/nonlinear_implicit_system.h"
#include "libmesh/explicit_system.h"
#include "libmesh/string_to_enum.h"
#include "libmesh/fe.h"

// Regular expression includes
#include "pcrecpp.h"

template<>
InputParameters validParams<AddCoupledEqSpeciesKernelsAction>()
{
  InputParameters params = validParams<Action>();
  params.addRequiredParam<std::vector<NonlinearVariableName> >("primary_species", "The list of primary variables to add");
  params.addParam<std::string>("reactions", "The list of aqueous equilibrium reactions");
  params.addParam<std::string>("pressure","Checks if pressure is a primary variable");

  return params;
}

AddCoupledEqSpeciesKernelsAction::AddCoupledEqSpeciesKernelsAction(const std::string & name, InputParameters params) :
    Action(name, params)
{
}

void
AddCoupledEqSpeciesKernelsAction::act()
{
  // Reading primary species and reaction network from the input file
  std::vector<NonlinearVariableName> vars = getParam<std::vector<NonlinearVariableName> >("primary_species");
  std::string reactions = getParam<std::string>("reactions");

  // Getting ready for the parsing system
  pcrecpp::RE re_reactions("(.*?)"                     // the reaction network (any character until the equalibrium coefficient appears)
                           "\\s"                       // word boundary
                             "("                       // start capture
                               "-?"                    // optional minus sign
                                 "\\d+(?:\\.\\d*)?"    // digits followed by optional decimal and more 0 or more digits
                             ")"
                           "\\b"                       // word boundary
                           "(?:\\s+|$)"                // eat the whitespace
                           , pcrecpp::RE_Options().set_extended(true));

  pcrecpp::RE re_terms("(\\S+)");
  pcrecpp::RE re_coeff_and_species("(?: \\(? (.*?) \\)? )"  // match the leading coefficent
                                   "([A-Za-z].*)"           // match the species
                                   , pcrecpp::RE_Options().set_extended(true));

  pcrecpp::StringPiece input(reactions);

  pcrecpp::StringPiece single_reaction, term;
  Real equal_coeff;

  std::vector<std::vector<bool> > primary_participation(vars.size());
  std::vector<string> eq_species;
  std::vector<Real> weight;
  std::vector<Real> eq_const;
  std::vector<std::vector<Real> > sto_u(vars.size());
  std::vector<std::vector<std::vector<Real> > > sto_v(vars.size());
  std::vector<std::vector<std::vector<VariableName> > > coupled_v(vars.size());

  std::vector<std::vector<Real> > stos;
  std::vector<std::vector<std::string> > primary_species_involved;

  unsigned int n_reactions = 0;

  // Start parsing
  // Going into every single reaction
  while (re_reactions.FindAndConsume(&input, &single_reaction, &equal_coeff))
  {
    n_reactions += 1;
    Moose::out << "\n\n" << n_reactions << "_th reaction: " << single_reaction << std::endl;

    eq_const.push_back(equal_coeff);
    Moose::out << "\nEqualibrium: " << eq_const[n_reactions-1] << std::endl;

    // capture all of the terms
    std::string species, coeff_str;
    Real coeff;
    int sign = 1;
    bool secondary = false;

    std::vector<Real> local_stos;
    std::vector<std::string> local_species_list;

    // Going to find every single term in this reaction, sto_species combos and operators
    while (re_terms.FindAndConsume(&single_reaction, &term))
    {

      // Separating the sto from species
      if (re_coeff_and_species.PartialMatch(term, &coeff_str, &species))
      {
        if (coeff_str.length())
        {
          std::istringstream iss(coeff_str);
          iss >> coeff;
        }
        else
          coeff = 1.0;

        coeff *= sign;

        if (secondary)
        {
          eq_species.push_back(species);
        }
        else
        {
          local_stos.push_back(coeff);
          local_species_list.push_back(species);
          Moose::out << "\nSpecies: " << species << "\n"
                    << "Coeff: " << coeff << std::endl;
        }

        }
      // Finding the operators and assign value of -1.0 to "-" sign
      else if (term == "+" || term == "=" || term == "-")
      {
        if (term == "-")
        {
          sign = -1;
          term = "+";
        }
        else
          sign = 1;
        Moose::out << "Operator: " << term << "\n\n";

        if (term == "=")
          secondary = true;
      }
      else
        mooseError("Error parsing term: " << term.as_string());
    }

    Moose::out << "\nEquilibrium Species: " << eq_species[n_reactions-1] << std::endl;

    stos.push_back(local_stos);
    primary_species_involved.push_back(local_species_list);

  }

  if (n_reactions == 0) mooseError("No equilibrium reaction provided!");
  // End parsing

  Moose::out << "Number of reactions: " << n_reactions << std::endl;

  // Start picking out primary species and coupled primary species and assigning corresponding stoichiomentric coefficients
  for (unsigned int i=0; i < vars.size(); i++)
  {
    Moose::out << "\nPrimary species - " << vars[i] << std::endl;

    sto_u[i].resize(n_reactions);
    sto_v[i].resize(n_reactions);
    coupled_v[i].resize(n_reactions);
    weight.resize(n_reactions);

    primary_participation[i].resize(n_reactions, false);
    for (unsigned int j=0; j < n_reactions; j++)
    {
      for (unsigned int k=0; k < primary_species_involved[j].size(); k++)
      {
        if (primary_species_involved[j][k] == vars[i]) primary_participation[i][j] = true;
      }

      Moose::out << "\nPrimary species " << vars[i] << " participation in " << j << "_th reaction (0 or 1): " << primary_participation[i][j] << std::endl;

      if (primary_participation[i][j])
      {
        for (unsigned int k=0; k < primary_species_involved[j].size(); k++)
        {
          if (primary_species_involved[j][k] == vars[i])
          {
            sto_u[i][j] = stos[j][k];
            weight[j] = stos[j][k];
            Moose::out << "\nEq weight: " << weight[j] << std::endl;
          }
          else
          {
            sto_v[i][j].push_back(stos[j][k]);
            coupled_v[i][j].push_back(primary_species_involved[j][k]);
          }
        }

        Moose::out << "\n#Coupled species: " << coupled_v[i][j].size() << std::endl;
        Moose::out << "\nCoupled species: ";

        for (unsigned int m=0; m < coupled_v[i][j].size(); m++)
        {
          Moose::out <<  coupled_v[i][j][m] << "  " << std::endl;
        }

      }
    }
  }

  // Done parsing, adding kernels
  for (unsigned int i=0; i < vars.size(); i++)
  {

    //  Adding the coupled kernels if the primary species participates in this equilibrium reaction

    for (unsigned int j=0; j < eq_const.size(); j++)
    {
      if (primary_participation[i][j])
      {

          // Building kernels for equilbirium aqueous species
        InputParameters params_sub = _factory.getValidParams("CoupledBEEquilibriumSub");
        params_sub.set<NonlinearVariableName>("variable") = vars[i];
        params_sub.set<Real>("weight") = weight[j];
        params_sub.set<Real>("log_k") = eq_const[j];
        params_sub.set<Real>("sto_u") = sto_u[i][j];
        params_sub.set<std::vector<Real> >("sto_v") = sto_v[i][j];
        params_sub.set<std::vector<VariableName> >("v") = coupled_v[i][j];
        _problem->addKernel("CoupledBEEquilibriumSub", vars[i]+"_"+eq_species[j]+"_sub", params_sub);

        Moose::out << vars[i]+"_"+eq_species[j]+"_sub" << "\n";
        params_sub.print();

        InputParameters params_cd = _factory.getValidParams("CoupledDiffusionReactionSub");
        params_cd.set<NonlinearVariableName>("variable") = vars[i];
        params_cd.set<Real>("weight") = weight[j];
        params_cd.set<Real>("log_k") = eq_const[j];
        params_cd.set<Real>("sto_u") = sto_u[i][j];
        params_cd.set<std::vector<Real> >("sto_v") = sto_v[i][j];
        params_cd.set<std::vector<VariableName> >("v") = coupled_v[i][j];
        _problem->addKernel("CoupledDiffusionReactionSub", vars[i]+"_"+eq_species[j]+"_cd", params_cd);

        Moose::out << vars[i]+"_"+eq_species[j]+"_diff" << "\n";
        params_cd.print();

        Moose::out << "whether pressure is present" << _pars.isParamValid("pressure") << "\n";

        if (_pars.isParamValid("pressure"))
        {
          std::string p;
          p = getParam<std::string>("pressure");
          std::vector<VariableName> press(1);
          press[0] = p;
          Moose::out << "coupled gradient of p" << press[0] << "\n";

          InputParameters params_conv = _factory.getValidParams("CoupledConvectionReactionSub");
          params_conv.set<NonlinearVariableName>("variable") = vars[i];
          params_conv.set<Real>("weight") = weight[j];
          params_conv.set<Real>("log_k") = eq_const[j];
          params_conv.set<Real>("sto_u") = sto_u[i][j];
          params_conv.set<std::vector<Real> >("sto_v") = sto_v[i][j];
          params_conv.set<std::vector<VariableName> >("v") = coupled_v[i][j];
          // Pressure is required to be named as "pressure" if it is a primary variable
          params_conv.set<std::vector<VariableName> >("p") = press;
          _problem->addKernel("CoupledConvectionReactionSub", vars[i]+"_"+eq_species[j]+"_conv", params_conv);

          Moose::out << vars[i]+"_"+eq_species[j]+"_conv" << "\n";
          params_conv.print();
        }
      }
    }
  }
  Moose::out << "\n";
}
<commit_msg>Using ostringstream instead of Moose::out due to missing specialization - #2460<commit_after>#include "AddCoupledEqSpeciesKernelsAction.h"
#include "Parser.h"
#include "FEProblem.h"
#include "Factory.h"
#include "MooseEnum.h"

#include <sstream>
#include <stdexcept>

// libMesh includes
#include "libmesh/libmesh.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/equation_systems.h"
#include "libmesh/nonlinear_implicit_system.h"
#include "libmesh/explicit_system.h"
#include "libmesh/string_to_enum.h"
#include "libmesh/fe.h"

// Regular expression includes
#include "pcrecpp.h"

template<>
InputParameters validParams<AddCoupledEqSpeciesKernelsAction>()
{
  InputParameters params = validParams<Action>();
  params.addRequiredParam<std::vector<NonlinearVariableName> >("primary_species", "The list of primary variables to add");
  params.addParam<std::string>("reactions", "The list of aqueous equilibrium reactions");
  params.addParam<std::string>("pressure","Checks if pressure is a primary variable");

  return params;
}

AddCoupledEqSpeciesKernelsAction::AddCoupledEqSpeciesKernelsAction(const std::string & name, InputParameters params) :
    Action(name, params)
{
}

void
AddCoupledEqSpeciesKernelsAction::act()
{
  // Reading primary species and reaction network from the input file
  std::vector<NonlinearVariableName> vars = getParam<std::vector<NonlinearVariableName> >("primary_species");
  std::string reactions = getParam<std::string>("reactions");

  // Getting ready for the parsing system
  pcrecpp::RE re_reactions("(.*?)"                     // the reaction network (any character until the equalibrium coefficient appears)
                           "\\s"                       // word boundary
                             "("                       // start capture
                               "-?"                    // optional minus sign
                                 "\\d+(?:\\.\\d*)?"    // digits followed by optional decimal and more 0 or more digits
                             ")"
                           "\\b"                       // word boundary
                           "(?:\\s+|$)"                // eat the whitespace
                           , pcrecpp::RE_Options().set_extended(true));

  pcrecpp::RE re_terms("(\\S+)");
  pcrecpp::RE re_coeff_and_species("(?: \\(? (.*?) \\)? )"  // match the leading coefficent
                                   "([A-Za-z].*)"           // match the species
                                   , pcrecpp::RE_Options().set_extended(true));

  pcrecpp::StringPiece input(reactions);

  pcrecpp::StringPiece single_reaction, term;
  Real equal_coeff;

  std::vector<std::vector<bool> > primary_participation(vars.size());
  std::vector<string> eq_species;
  std::vector<Real> weight;
  std::vector<Real> eq_const;
  std::vector<std::vector<Real> > sto_u(vars.size());
  std::vector<std::vector<std::vector<Real> > > sto_v(vars.size());
  std::vector<std::vector<std::vector<VariableName> > > coupled_v(vars.size());

  std::vector<std::vector<Real> > stos;
  std::vector<std::vector<std::string> > primary_species_involved;

  unsigned int n_reactions = 0;

  // Start parsing
  // Going into every single reaction
  std::ostringstream oss;

  while (re_reactions.FindAndConsume(&input, &single_reaction, &equal_coeff))
  {
    n_reactions += 1;
    oss << "\n\n" << n_reactions << "_th reaction: " << single_reaction << std::endl;

    eq_const.push_back(equal_coeff);
    oss << "\nEqualibrium: " << eq_const[n_reactions-1] << std::endl;

    // capture all of the terms
    std::string species, coeff_str;
    Real coeff;
    int sign = 1;
    bool secondary = false;

    std::vector<Real> local_stos;
    std::vector<std::string> local_species_list;

    // Going to find every single term in this reaction, sto_species combos and operators
    while (re_terms.FindAndConsume(&single_reaction, &term))
    {

      // Separating the sto from species
      if (re_coeff_and_species.PartialMatch(term, &coeff_str, &species))
      {
        if (coeff_str.length())
        {
          std::istringstream iss(coeff_str);
          iss >> coeff;
        }
        else
          coeff = 1.0;

        coeff *= sign;

        if (secondary)
        {
          eq_species.push_back(species);
        }
        else
        {
          local_stos.push_back(coeff);
          local_species_list.push_back(species);
          oss << "\nSpecies: " << species << "\n"
                    << "Coeff: " << coeff << std::endl;
        }

        }
      // Finding the operators and assign value of -1.0 to "-" sign
      else if (term == "+" || term == "=" || term == "-")
      {
        if (term == "-")
        {
          sign = -1;
          term = "+";
        }
        else
          sign = 1;
        oss << "Operator: " << term << "\n\n";

        if (term == "=")
          secondary = true;
      }
      else
        mooseError("Error parsing term: " << term.as_string());
    }

    oss << "\nEquilibrium Species: " << eq_species[n_reactions-1] << std::endl;

    stos.push_back(local_stos);
    primary_species_involved.push_back(local_species_list);

  }

  if (n_reactions == 0) mooseError("No equilibrium reaction provided!");
  // End parsing

  oss << "Number of reactions: " << n_reactions << std::endl;

  // Start picking out primary species and coupled primary species and assigning corresponding stoichiomentric coefficients
  for (unsigned int i=0; i < vars.size(); i++)
  {
    oss << "\nPrimary species - " << vars[i] << std::endl;

    sto_u[i].resize(n_reactions);
    sto_v[i].resize(n_reactions);
    coupled_v[i].resize(n_reactions);
    weight.resize(n_reactions);

    primary_participation[i].resize(n_reactions, false);
    for (unsigned int j=0; j < n_reactions; j++)
    {
      for (unsigned int k=0; k < primary_species_involved[j].size(); k++)
      {
        if (primary_species_involved[j][k] == vars[i]) primary_participation[i][j] = true;
      }

      oss << "\nPrimary species " << vars[i] << " participation in " << j << "_th reaction (0 or 1): " << primary_participation[i][j] << std::endl;

      if (primary_participation[i][j])
      {
        for (unsigned int k=0; k < primary_species_involved[j].size(); k++)
        {
          if (primary_species_involved[j][k] == vars[i])
          {
            sto_u[i][j] = stos[j][k];
            weight[j] = stos[j][k];
            oss << "\nEq weight: " << weight[j] << std::endl;
          }
          else
          {
            sto_v[i][j].push_back(stos[j][k]);
            coupled_v[i][j].push_back(primary_species_involved[j][k]);
          }
        }

        oss << "\n#Coupled species: " << coupled_v[i][j].size() << std::endl;
        oss << "\nCoupled species: ";

        for (unsigned int m=0; m < coupled_v[i][j].size(); m++)
        {
          oss <<  coupled_v[i][j][m] << "  " << std::endl;
        }

      }
    }
  }

  // Done parsing, adding kernels
  for (unsigned int i=0; i < vars.size(); i++)
  {

    //  Adding the coupled kernels if the primary species participates in this equilibrium reaction

    for (unsigned int j=0; j < eq_const.size(); j++)
    {
      if (primary_participation[i][j])
      {

          // Building kernels for equilbirium aqueous species
        InputParameters params_sub = _factory.getValidParams("CoupledBEEquilibriumSub");
        params_sub.set<NonlinearVariableName>("variable") = vars[i];
        params_sub.set<Real>("weight") = weight[j];
        params_sub.set<Real>("log_k") = eq_const[j];
        params_sub.set<Real>("sto_u") = sto_u[i][j];
        params_sub.set<std::vector<Real> >("sto_v") = sto_v[i][j];
        params_sub.set<std::vector<VariableName> >("v") = coupled_v[i][j];
        _problem->addKernel("CoupledBEEquilibriumSub", vars[i]+"_"+eq_species[j]+"_sub", params_sub);

        oss << vars[i]+"_"+eq_species[j]+"_sub" << "\n";
        params_sub.print();

        InputParameters params_cd = _factory.getValidParams("CoupledDiffusionReactionSub");
        params_cd.set<NonlinearVariableName>("variable") = vars[i];
        params_cd.set<Real>("weight") = weight[j];
        params_cd.set<Real>("log_k") = eq_const[j];
        params_cd.set<Real>("sto_u") = sto_u[i][j];
        params_cd.set<std::vector<Real> >("sto_v") = sto_v[i][j];
        params_cd.set<std::vector<VariableName> >("v") = coupled_v[i][j];
        _problem->addKernel("CoupledDiffusionReactionSub", vars[i]+"_"+eq_species[j]+"_cd", params_cd);

        oss << vars[i]+"_"+eq_species[j]+"_diff" << "\n";
        params_cd.print();

        oss << "whether pressure is present" << _pars.isParamValid("pressure") << "\n";

        if (_pars.isParamValid("pressure"))
        {
          std::string p;
          p = getParam<std::string>("pressure");
          std::vector<VariableName> press(1);
          press[0] = p;
          oss << "coupled gradient of p" << press[0] << "\n";

          InputParameters params_conv = _factory.getValidParams("CoupledConvectionReactionSub");
          params_conv.set<NonlinearVariableName>("variable") = vars[i];
          params_conv.set<Real>("weight") = weight[j];
          params_conv.set<Real>("log_k") = eq_const[j];
          params_conv.set<Real>("sto_u") = sto_u[i][j];
          params_conv.set<std::vector<Real> >("sto_v") = sto_v[i][j];
          params_conv.set<std::vector<VariableName> >("v") = coupled_v[i][j];
          // Pressure is required to be named as "pressure" if it is a primary variable
          params_conv.set<std::vector<VariableName> >("p") = press;
          _problem->addKernel("CoupledConvectionReactionSub", vars[i]+"_"+eq_species[j]+"_conv", params_conv);

          oss << vars[i]+"_"+eq_species[j]+"_conv" << "\n";
          params_conv.print();
        }
      }
    }
  }
  oss << "\n";
  Moose::out << oss.str();
}
<|endoftext|>


<commit_before><commit_msg>sal: fix osl_setCommandArgs() on WNT<commit_after><|endoftext|>


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

#include "chrome/browser/chromeos/options/language_chewing_config_view.h"

#include "app/combobox_model.h"
#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/language_library.h"
#include "chrome/browser/chromeos/options/language_config_util.h"
#include "chrome/browser/chromeos/preferences.h"
#include "chrome/browser/profile.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/window/window.h"

namespace chromeos {

LanguageChewingConfigView::LanguageChewingConfigView(Profile* profile)
    : OptionsPageView(profile), contents_(NULL) {
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    chewing_boolean_prefs_[i].Init(
        kChewingBooleanPrefs[i].pref_name, profile->GetPrefs(), this);
    chewing_boolean_checkboxes_[i] = NULL;
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    current.multiple_choice_pref.Init(
        kChewingMultipleChoicePrefs[i].pref_name, profile->GetPrefs(), this);
    current.combobox_model =
        new LanguageComboboxModel<const char*>(&kChewingMultipleChoicePrefs[i]);
    current.combobox = NULL;
  }

  hsu_sel_key_type_.multiple_choice_pref.Init(
      kChewingHsuSelKeyType.pref_name, profile->GetPrefs(), this);
  hsu_sel_key_type_.combobox_model =
      new LanguageComboboxModel<int>(&kChewingHsuSelKeyType);
  hsu_sel_key_type_.combobox = NULL;

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    chewing_integer_prefs_[i].Init(
        kChewingIntegerPrefs[i].pref_name, profile->GetPrefs(), this);
    chewing_integer_sliders_[i] = NULL;
  }
}

LanguageChewingConfigView::~LanguageChewingConfigView() {
}

void LanguageChewingConfigView::ButtonPressed(
    views::Button* sender, const views::Event& event) {
  views::Checkbox* checkbox = static_cast<views::Checkbox*>(sender);
  const int pref_id = checkbox->tag();
  DCHECK(pref_id >= 0 && pref_id < static_cast<int>(kNumChewingBooleanPrefs));
  chewing_boolean_prefs_[pref_id].SetValue(checkbox->checked());
}

void LanguageChewingConfigView::ItemChanged(
    views::Combobox* sender, int prev_index, int new_index) {
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    if (current.combobox == sender) {
      const std::wstring config_value =
          UTF8ToWide(current.combobox_model->GetConfigValueAt(new_index));
      LOG(INFO) << "Changing Chewing pref to " << config_value;
      // Update the Chrome pref.
      current.multiple_choice_pref.SetValue(config_value);
      break;
    }
  }
  if (hsu_sel_key_type_.combobox == sender) {
    const int config_value =
        hsu_sel_key_type_.combobox_model->GetConfigValueAt(new_index);
    LOG(INFO) << "Changing Chewing pref to " << config_value;
    // Update the Chrome pref.
    hsu_sel_key_type_.multiple_choice_pref.SetValue(config_value);
  }
}

void LanguageChewingConfigView::SliderValueChanged(views::Slider* sender) {
  size_t pref_id;
  for (pref_id = 0; pref_id < kNumChewingIntegerPrefs; ++pref_id) {
    if (chewing_integer_sliders_[pref_id] == sender)
      break;
  }
  DCHECK(pref_id < kNumChewingIntegerPrefs);
  chewing_integer_prefs_[pref_id].SetValue(sender->value());
}

void LanguageChewingConfigView::Layout() {
  // Not sure why but this is needed to show contents in the dialog.
  contents_->SetBounds(0, 0, width(), height());
}

std::wstring LanguageChewingConfigView::GetWindowTitle() const {
  return l10n_util::GetString(
      IDS_OPTIONS_SETTINGS_LANGUAGES_CHEWING_SETTINGS_TITLE);
}

gfx::Size LanguageChewingConfigView::GetPreferredSize() {
  return gfx::Size(views::Window::GetLocalizedContentsSize(
      IDS_LANGUAGES_INPUT_DIALOG_WIDTH_CHARS,
      IDS_LANGUAGES_INPUT_DIALOG_HEIGHT_LINES));
}

void LanguageChewingConfigView::InitControlLayout() {
  using views::ColumnSet;
  using views::GridLayout;

  contents_ = new views::View;
  AddChildView(contents_);

  GridLayout* layout = new GridLayout(contents_);
  layout->SetInsets(kPanelVertMargin, kPanelHorizMargin,
                    kPanelVertMargin, kPanelHorizMargin);
  contents_->SetLayoutManager(layout);

  const int kColumnSetId = 0;
  ColumnSet* column_set = layout->AddColumnSet(kColumnSetId);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0,
                        GridLayout::USE_PREF, 0, 0);

  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    chewing_boolean_checkboxes_[i] = new views::Checkbox(
        l10n_util::GetString(kChewingBooleanPrefs[i].message_id));
    chewing_boolean_checkboxes_[i]->set_listener(this);
    chewing_boolean_checkboxes_[i]->set_tag(i);
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    current.combobox = new LanguageCombobox(current.combobox_model);
    current.combobox->set_listener(this);
  }
  hsu_sel_key_type_.combobox =
      new LanguageCombobox(hsu_sel_key_type_.combobox_model);
  hsu_sel_key_type_.combobox->set_listener(this);

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    chewing_integer_sliders_[i] = new views::Slider(
        kChewingIntegerPrefs[i].min_pref_value,
        kChewingIntegerPrefs[i].max_pref_value,
        1,
        static_cast<views::Slider::StyleFlags>(
            views::Slider::STYLE_DRAW_VALUE |
            views::Slider::STYLE_UPDATE_ON_RELEASE),
        this);
  }
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    layout->StartRow(0, kColumnSetId);
    layout->AddView(chewing_boolean_checkboxes_[i]);
  }

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    layout->StartRow(0, kColumnSetId);
    layout->AddView(new views::Label(
        l10n_util::GetString(kChewingIntegerPrefs[i].message_id)));
    layout->AddView(chewing_integer_sliders_[i]);
  }
  NotifyPrefChanged();

  // Show the comboboxes.
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    const ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    layout->StartRow(0, kColumnSetId);
    layout->AddView(new views::Label(current.combobox_model->GetLabel()));
    layout->AddView(current.combobox);
  }
  layout->StartRow(0, kColumnSetId);
  layout->AddView(
      new views::Label(hsu_sel_key_type_.combobox_model->GetLabel()));
  layout->AddView(hsu_sel_key_type_.combobox);
}

void LanguageChewingConfigView::Observe(NotificationType type,
                                        const NotificationSource& source,
                                        const NotificationDetails& details) {
  if (type == NotificationType::PREF_CHANGED) {
    NotifyPrefChanged();
  }
}

void LanguageChewingConfigView::NotifyPrefChanged() {
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    const bool checked = chewing_boolean_prefs_[i].GetValue();
    chewing_boolean_checkboxes_[i]->SetChecked(checked);
  }
  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    const int value = chewing_integer_prefs_[i].GetValue();
    chewing_integer_sliders_[i]->SetValue(value);
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    const std::wstring value = current.multiple_choice_pref.GetValue();
    for (int i = 0; i < current.combobox_model->num_items(); ++i) {
      if (UTF8ToWide(current.combobox_model->GetConfigValueAt(i)) == value) {
        current.combobox->SetSelectedItem(i);
        break;
      }
    }
  }
  const int value = hsu_sel_key_type_.multiple_choice_pref.GetValue();
  for (int i = 0; i < hsu_sel_key_type_.combobox_model->num_items(); ++i) {
    if (hsu_sel_key_type_.combobox_model->GetConfigValueAt(i) == value) {
      hsu_sel_key_type_.combobox->SetSelectedItem(i);
      break;
    }
  }
}

}  // namespace chromeos
<commit_msg>Fix chewing layout<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/options/language_chewing_config_view.h"

#include "app/combobox_model.h"
#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/language_library.h"
#include "chrome/browser/chromeos/options/language_config_util.h"
#include "chrome/browser/chromeos/preferences.h"
#include "chrome/browser/profile.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/window/window.h"

namespace chromeos {

LanguageChewingConfigView::LanguageChewingConfigView(Profile* profile)
    : OptionsPageView(profile), contents_(NULL) {
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    chewing_boolean_prefs_[i].Init(
        kChewingBooleanPrefs[i].pref_name, profile->GetPrefs(), this);
    chewing_boolean_checkboxes_[i] = NULL;
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    current.multiple_choice_pref.Init(
        kChewingMultipleChoicePrefs[i].pref_name, profile->GetPrefs(), this);
    current.combobox_model =
        new LanguageComboboxModel<const char*>(&kChewingMultipleChoicePrefs[i]);
    current.combobox = NULL;
  }

  hsu_sel_key_type_.multiple_choice_pref.Init(
      kChewingHsuSelKeyType.pref_name, profile->GetPrefs(), this);
  hsu_sel_key_type_.combobox_model =
      new LanguageComboboxModel<int>(&kChewingHsuSelKeyType);
  hsu_sel_key_type_.combobox = NULL;

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    chewing_integer_prefs_[i].Init(
        kChewingIntegerPrefs[i].pref_name, profile->GetPrefs(), this);
    chewing_integer_sliders_[i] = NULL;
  }
}

LanguageChewingConfigView::~LanguageChewingConfigView() {
}

void LanguageChewingConfigView::ButtonPressed(
    views::Button* sender, const views::Event& event) {
  views::Checkbox* checkbox = static_cast<views::Checkbox*>(sender);
  const int pref_id = checkbox->tag();
  DCHECK(pref_id >= 0 && pref_id < static_cast<int>(kNumChewingBooleanPrefs));
  chewing_boolean_prefs_[pref_id].SetValue(checkbox->checked());
}

void LanguageChewingConfigView::ItemChanged(
    views::Combobox* sender, int prev_index, int new_index) {
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    if (current.combobox == sender) {
      const std::wstring config_value =
          UTF8ToWide(current.combobox_model->GetConfigValueAt(new_index));
      LOG(INFO) << "Changing Chewing pref to " << config_value;
      // Update the Chrome pref.
      current.multiple_choice_pref.SetValue(config_value);
      break;
    }
  }
  if (hsu_sel_key_type_.combobox == sender) {
    const int config_value =
        hsu_sel_key_type_.combobox_model->GetConfigValueAt(new_index);
    LOG(INFO) << "Changing Chewing pref to " << config_value;
    // Update the Chrome pref.
    hsu_sel_key_type_.multiple_choice_pref.SetValue(config_value);
  }
}

void LanguageChewingConfigView::SliderValueChanged(views::Slider* sender) {
  size_t pref_id;
  for (pref_id = 0; pref_id < kNumChewingIntegerPrefs; ++pref_id) {
    if (chewing_integer_sliders_[pref_id] == sender)
      break;
  }
  DCHECK(pref_id < kNumChewingIntegerPrefs);
  chewing_integer_prefs_[pref_id].SetValue(sender->value());
}

void LanguageChewingConfigView::Layout() {
  // Not sure why but this is needed to show contents in the dialog.
  contents_->SetBounds(0, 0, width(), height());
}

std::wstring LanguageChewingConfigView::GetWindowTitle() const {
  return l10n_util::GetString(
      IDS_OPTIONS_SETTINGS_LANGUAGES_CHEWING_SETTINGS_TITLE);
}

gfx::Size LanguageChewingConfigView::GetPreferredSize() {
  return gfx::Size(views::Window::GetLocalizedContentsSize(
      IDS_LANGUAGES_INPUT_DIALOG_WIDTH_CHARS,
      IDS_LANGUAGES_INPUT_DIALOG_HEIGHT_LINES));
}

void LanguageChewingConfigView::InitControlLayout() {
  using views::ColumnSet;
  using views::GridLayout;

  contents_ = new views::View;
  AddChildView(contents_);

  GridLayout* layout = new GridLayout(contents_);
  layout->SetInsets(kPanelVertMargin, kPanelHorizMargin,
                    kPanelVertMargin, kPanelHorizMargin);
  contents_->SetLayoutManager(layout);

  const int kColumnSetId = 0;
  ColumnSet* column_set = layout->AddColumnSet(kColumnSetId);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 1,
                        GridLayout::USE_PREF, 0, 0);

  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    chewing_boolean_checkboxes_[i] = new views::Checkbox(
        l10n_util::GetString(kChewingBooleanPrefs[i].message_id));
    chewing_boolean_checkboxes_[i]->set_listener(this);
    chewing_boolean_checkboxes_[i]->set_tag(i);
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    current.combobox = new LanguageCombobox(current.combobox_model);
    current.combobox->set_listener(this);
  }
  hsu_sel_key_type_.combobox =
      new LanguageCombobox(hsu_sel_key_type_.combobox_model);
  hsu_sel_key_type_.combobox->set_listener(this);

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    chewing_integer_sliders_[i] = new views::Slider(
        kChewingIntegerPrefs[i].min_pref_value,
        kChewingIntegerPrefs[i].max_pref_value,
        1,
        static_cast<views::Slider::StyleFlags>(
            views::Slider::STYLE_DRAW_VALUE |
            views::Slider::STYLE_UPDATE_ON_RELEASE),
        this);
  }
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    layout->StartRow(0, kColumnSetId);
    layout->AddView(chewing_boolean_checkboxes_[i]);
  }

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    layout->StartRow(0, kColumnSetId);
    layout->AddView(new views::Label(
        l10n_util::GetString(kChewingIntegerPrefs[i].message_id)));
    layout->AddView(chewing_integer_sliders_[i]);
  }
  NotifyPrefChanged();

  // Show the comboboxes.
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    const ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    layout->StartRow(0, kColumnSetId);
    layout->AddView(new views::Label(current.combobox_model->GetLabel()));
    layout->AddView(current.combobox);
  }
  layout->StartRow(0, kColumnSetId);
  layout->AddView(
      new views::Label(hsu_sel_key_type_.combobox_model->GetLabel()));
  layout->AddView(hsu_sel_key_type_.combobox);
}

void LanguageChewingConfigView::Observe(NotificationType type,
                                        const NotificationSource& source,
                                        const NotificationDetails& details) {
  if (type == NotificationType::PREF_CHANGED) {
    NotifyPrefChanged();
  }
}

void LanguageChewingConfigView::NotifyPrefChanged() {
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    const bool checked = chewing_boolean_prefs_[i].GetValue();
    chewing_boolean_checkboxes_[i]->SetChecked(checked);
  }
  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    const int value = chewing_integer_prefs_[i].GetValue();
    chewing_integer_sliders_[i]->SetValue(value);
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    const std::wstring value = current.multiple_choice_pref.GetValue();
    for (int i = 0; i < current.combobox_model->num_items(); ++i) {
      if (UTF8ToWide(current.combobox_model->GetConfigValueAt(i)) == value) {
        current.combobox->SetSelectedItem(i);
        break;
      }
    }
  }
  const int value = hsu_sel_key_type_.multiple_choice_pref.GetValue();
  for (int i = 0; i < hsu_sel_key_type_.combobox_model->num_items(); ++i) {
    if (hsu_sel_key_type_.combobox_model->GetConfigValueAt(i) == value) {
      hsu_sel_key_type_.combobox->SetSelectedItem(i);
      break;
    }
  }
}

}  // namespace chromeos
<|endoftext|>


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

#include "chrome/browser/chromeos/status/power_menu_button.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_power_library.h"
#include "chrome/browser/chromeos/frame/browser_view.h"
#include "chrome/browser/chromeos/status/browser_status_area_view.h"
#include "chrome/browser/chromeos/view_ids.h"
#include "grit/theme_resources.h"

namespace chromeos {
using ::testing::AnyNumber;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::_;

class PowerMenuButtonTest : public CrosInProcessBrowserTest {
 protected:
  PowerMenuButtonTest() : CrosInProcessBrowserTest() {}

  virtual void SetUpInProcessBrowserTestFixture() {
    InitStatusAreaMocks();
    SetStatusAreaMocksExpectations();
  }

  PowerMenuButton* GetPowerMenuButton() {
    BrowserView* view = static_cast<BrowserView*>(browser()->window());
    PowerMenuButton* power = static_cast<BrowserStatusAreaView*>(view->
        GetViewByID(VIEW_ID_STATUS_AREA))->power_view();
    return power;
  }

  int CallPowerChangedAndGetIconId() {
    PowerMenuButton* power = GetPowerMenuButton();
    power->PowerChanged(mock_power_library_);
    return power->icon_id();
  }
};

IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryMissingTest) {
  EXPECT_CALL(*mock_power_library_, battery_is_present())
      .WillRepeatedly((Return(false)));
  EXPECT_EQ(IDR_STATUSBAR_BATTERY_MISSING, CallPowerChangedAndGetIconId());
}

IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryChargedTest) {
  EXPECT_CALL(*mock_power_library_, battery_is_present())
      .WillRepeatedly((Return(true)));
  EXPECT_CALL(*mock_power_library_, battery_fully_charged())
      .WillRepeatedly((Return(true)));
  EXPECT_CALL(*mock_power_library_, line_power_on())
      .WillRepeatedly((Return(true)));
  EXPECT_EQ(IDR_STATUSBAR_BATTERY_CHARGED, CallPowerChangedAndGetIconId());
}

// http://crbug.com/48912
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, FAILS_BatteryChargingTest) {
  EXPECT_CALL(*mock_power_library_, battery_is_present())
      .WillRepeatedly((Return(true)));
  EXPECT_CALL(*mock_power_library_, battery_fully_charged())
      .WillRepeatedly((Return(false)));
  EXPECT_CALL(*mock_power_library_, line_power_on())
      .WillRepeatedly((Return(true)));

  // Test the 12 battery charging states.
  int id = IDR_STATUSBAR_BATTERY_CHARGING_1;
  for (float precent = 6.0; precent < 100.0; precent += 8.0) {
    EXPECT_CALL(*mock_power_library_, battery_percentage())
        .WillRepeatedly((Return(precent)));
    EXPECT_EQ(id, CallPowerChangedAndGetIconId());
    id++;
  }
}

// http://crbug.com/48912
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, FAILS_BatteryDischargingTest) {
  EXPECT_CALL(*mock_power_library_, battery_is_present())
      .WillRepeatedly((Return(true)));
  EXPECT_CALL(*mock_power_library_, battery_fully_charged())
      .WillRepeatedly((Return(false)));
  EXPECT_CALL(*mock_power_library_, line_power_on())
      .WillRepeatedly((Return(false)));

  // Test the 12 battery discharing states.
  int id = IDR_STATUSBAR_BATTERY_DISCHARGING_1;
  for (float precent = 6.0; precent < 100.0; precent += 8.0) {
    EXPECT_CALL(*mock_power_library_, battery_percentage())
        .WillRepeatedly((Return(precent)));
    EXPECT_EQ(id, CallPowerChangedAndGetIconId());
    id++;
  }
}

}  // namespace chromeos
<commit_msg>Fix browser test broken by resource ID ordering change.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/status/power_menu_button.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_power_library.h"
#include "chrome/browser/chromeos/frame/browser_view.h"
#include "chrome/browser/chromeos/status/browser_status_area_view.h"
#include "chrome/browser/chromeos/view_ids.h"
#include "grit/theme_resources.h"

namespace chromeos {
using ::testing::AnyNumber;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::_;

class PowerMenuButtonTest : public CrosInProcessBrowserTest {
 protected:
  PowerMenuButtonTest() : CrosInProcessBrowserTest() {}

  virtual void SetUpInProcessBrowserTestFixture() {
    InitStatusAreaMocks();
    SetStatusAreaMocksExpectations();
  }

  PowerMenuButton* GetPowerMenuButton() {
    BrowserView* view = static_cast<BrowserView*>(browser()->window());
    PowerMenuButton* power = static_cast<BrowserStatusAreaView*>(view->
        GetViewByID(VIEW_ID_STATUS_AREA))->power_view();
    return power;
  }

  int CallPowerChangedAndGetIconId() {
    PowerMenuButton* power = GetPowerMenuButton();
    power->PowerChanged(mock_power_library_);
    return power->icon_id();
  }
};

IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryMissingTest) {
  EXPECT_CALL(*mock_power_library_, battery_is_present())
      .WillRepeatedly((Return(false)));
  EXPECT_EQ(IDR_STATUSBAR_BATTERY_MISSING, CallPowerChangedAndGetIconId());
}

IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryChargedTest) {
  EXPECT_CALL(*mock_power_library_, battery_is_present())
      .WillRepeatedly((Return(true)));
  EXPECT_CALL(*mock_power_library_, battery_fully_charged())
      .WillRepeatedly((Return(true)));
  EXPECT_CALL(*mock_power_library_, line_power_on())
      .WillRepeatedly((Return(true)));
  EXPECT_EQ(IDR_STATUSBAR_BATTERY_CHARGED, CallPowerChangedAndGetIconId());
}

IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryChargingTest) {
  EXPECT_CALL(*mock_power_library_, battery_is_present())
      .WillRepeatedly((Return(true)));
  EXPECT_CALL(*mock_power_library_, battery_fully_charged())
      .WillRepeatedly((Return(false)));
  EXPECT_CALL(*mock_power_library_, line_power_on())
      .WillRepeatedly((Return(true)));

  // Test the 12 battery charging states.
  // NOTE: Use an array rather than just calculating a resource number to avoid
  // creating implicit ordering dependencies on the resource values.
  static const int kChargingImages[] = {
    IDR_STATUSBAR_BATTERY_CHARGING_1,
    IDR_STATUSBAR_BATTERY_CHARGING_2,
    IDR_STATUSBAR_BATTERY_CHARGING_3,
    IDR_STATUSBAR_BATTERY_CHARGING_4,
    IDR_STATUSBAR_BATTERY_CHARGING_5,
    IDR_STATUSBAR_BATTERY_CHARGING_6,
    IDR_STATUSBAR_BATTERY_CHARGING_7,
    IDR_STATUSBAR_BATTERY_CHARGING_8,
    IDR_STATUSBAR_BATTERY_CHARGING_9,
    IDR_STATUSBAR_BATTERY_CHARGING_10,
    IDR_STATUSBAR_BATTERY_CHARGING_11,
    IDR_STATUSBAR_BATTERY_CHARGING_12,
  };
  size_t id = 0;
  for (float percent = 6.0; percent < 100.0; percent += 8.0) {
    EXPECT_CALL(*mock_power_library_, battery_percentage())
        .WillRepeatedly((Return(percent)));
    ASSERT_LT(id, arraysize(kChargingImages));
    EXPECT_EQ(kChargingImages[id], CallPowerChangedAndGetIconId());
    id++;
  }
}

IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryDischargingTest) {
  EXPECT_CALL(*mock_power_library_, battery_is_present())
      .WillRepeatedly((Return(true)));
  EXPECT_CALL(*mock_power_library_, battery_fully_charged())
      .WillRepeatedly((Return(false)));
  EXPECT_CALL(*mock_power_library_, line_power_on())
      .WillRepeatedly((Return(false)));

  // Test the 12 battery discharing states.
  // NOTE: Use an array rather than just calculating a resource number to avoid
  // creating implicit ordering dependencies on the resource values.
  static const int kDischargingImages[] = {
    IDR_STATUSBAR_BATTERY_DISCHARGING_1,
    IDR_STATUSBAR_BATTERY_DISCHARGING_2,
    IDR_STATUSBAR_BATTERY_DISCHARGING_3,
    IDR_STATUSBAR_BATTERY_DISCHARGING_4,
    IDR_STATUSBAR_BATTERY_DISCHARGING_5,
    IDR_STATUSBAR_BATTERY_DISCHARGING_6,
    IDR_STATUSBAR_BATTERY_DISCHARGING_7,
    IDR_STATUSBAR_BATTERY_DISCHARGING_8,
    IDR_STATUSBAR_BATTERY_DISCHARGING_9,
    IDR_STATUSBAR_BATTERY_DISCHARGING_10,
    IDR_STATUSBAR_BATTERY_DISCHARGING_11,
    IDR_STATUSBAR_BATTERY_DISCHARGING_12,
  };
  size_t id = 0;
  for (float percent = 6.0; percent < 100.0; percent += 8.0) {
    EXPECT_CALL(*mock_power_library_, battery_percentage())
        .WillRepeatedly((Return(percent)));
    ASSERT_LT(id, arraysize(kDischargingImages));
    EXPECT_EQ(kDischargingImages[id], CallPowerChangedAndGetIconId());
    id++;
  }
}

}  // namespace chromeos
<|endoftext|>


<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>"
// Copyright 2007      Inge Wallin  <ingwa@kde.org>"
//

#include "MarbleTest.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QTime>
#include <QtGui/QFileDialog>

#include <lib/MarbleWidget.h>
#include <lib/MarbleModel.h>

MarbleTest::MarbleTest( MarbleWidget* marbleWidget )
    : m_marbleWidget(marbleWidget)
{
}

void MarbleTest::timeDemo()
{
    m_marbleWidget->zoomView( 1500 );
//    m_marbleWidget->resize( 800, 600 );
    m_marbleWidget->centerOn( 9.4, 54.8 );
    QTime t;
    //m_marbleWidget->setMapTheme( "plain/plain.dgml" );
    //m_marbleWidget->setMapTheme( "bluemarble/bluemarble.dgml" );

/*
    m_marbleWidget->setShowGrid( false );
    m_marbleWidget->setShowPlaces( false );
    m_marbleWidget->setShowBorders( false );
    m_marbleWidget->setShowRivers( false );
    m_marbleWidget->setShowLakes( false );
*/

        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveRight();
            QCoreApplication::flush();
        }
        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveLeft();
            QCoreApplication::flush();
        }

    qDebug() << "Starting Performance Test";

    t.start();

    for ( int j = 0; j < 10; ++j ) {
        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveRight();
            QCoreApplication::flush();
        }
        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveLeft();
            QCoreApplication::flush();
        }
    }

    qDebug( "Timedemo finished in %ims", t.elapsed() );
    qDebug() <<  QString("= %1 fps").arg(200*1000/(double)(t.elapsed()));

}

void MarbleTest::gpsDemo(){
    //
    //set up for the test
    //
    qDebug("stopping polling now");

    m_marbleWidget->model()->stopPolling();
    m_marbleWidget->rotateTo( -15.2325, 58.3723 );

    m_marbleWidget->setShowGps( true );

    //get the gpx file
    QString fileName = QFileDialog::getOpenFileName(m_marbleWidget,
            "Open File", QString(),
            "GPS Data (*.gpx);;KML (*.kml)");

    if ( ! fileName.isNull() ) {
        QString extension = fileName.section( '.', -1 );

        if ( extension.compare( "gpx", Qt::CaseInsensitive ) == 0 ) {
            m_marbleWidget->openGpxFile( fileName );
        }
    }

    QTime t;
    QTime totalTime;

    QVector<int> movingStats;
    QVector<int> staticStats;
    int temp=0;
    int totalMoving =0;
    int totalStatic =0;

    //
    //Start the test
    //
    totalTime.start();
    for( int i = 0; i< 5 ; i++) {

        m_marbleWidget->zoomViewBy( 400 );
        totalMoving =0;
        totalStatic =0;
        m_marbleWidget->rotateTo( -15.2325, 58.3723 );

        for( int i = 0; i< 5 ;i++ ){
            if( i%2) {
                m_marbleWidget->moveLeft();
            } else {
                m_marbleWidget->moveRight();
            }
            t.start();
            m_marbleWidget->updateGps();
            temp = t.elapsed();
//             qDebug("time elapsed moving %d",temp);
            totalMoving += temp;

        }

        for( int i = 0; i< 10 ;i++ ){
            t.start();
            m_marbleWidget->updateGps();
            temp=t.elapsed();
//             qDebug("time elapsed static %d",t.elapsed());
            totalStatic+=temp;
        }

//         qDebug ( "average of moving is %d at %d zoom",
//                  (totalMoving/10), m_marbleWidget->zoom() );
//         qDebug( "average of static is %d at %d zoom",
//                 (totalStatic/10) , m_marbleWidget->zoom() );
        movingStats.append( totalMoving/10 );
        staticStats.append( totalStatic/10 );

    }
    qDebug("total test time: %d", totalTime.elapsed());

    qDebug("full moving stats: ") ;
    qDebug() << movingStats;

    qDebug("full static stats: ");
    qDebug() << staticStats;

}
<commit_msg>Test till 100 so we got to the range of 10ms in most systems (currently real results can be hidden by the accurary of the system) When I did that I got results from 27ms to 37ms. Adding 2 more tests helps lowering the jitter (52-57).  <commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>"
// Copyright 2007      Inge Wallin  <ingwa@kde.org>"
//

#include "MarbleTest.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QTime>
#include <QtGui/QFileDialog>

#include <lib/MarbleWidget.h>
#include <lib/MarbleModel.h>

MarbleTest::MarbleTest( MarbleWidget* marbleWidget )
    : m_marbleWidget(marbleWidget)
{
}

void MarbleTest::timeDemo()
{
    m_marbleWidget->show();
    m_marbleWidget->zoomView( 1500 );
//    m_marbleWidget->resize( 800, 600 );
    m_marbleWidget->centerOn( 9.4, 54.8 );
    QTime t;
    //m_marbleWidget->setMapTheme( "plain/plain.dgml" );
    //m_marbleWidget->setMapTheme( "bluemarble/bluemarble.dgml" );

/*
    m_marbleWidget->setShowGrid( false );
    m_marbleWidget->setShowPlaces( false );
    m_marbleWidget->setShowBorders( false );
    m_marbleWidget->setShowRivers( false );
    m_marbleWidget->setShowLakes( false );
*/
        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveUp();
            QCoreApplication::flush();
        }
        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveDown();
            QCoreApplication::flush();
        }

        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveRight();
            QCoreApplication::flush();
        }
        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveLeft();
            QCoreApplication::flush();
        }

    qDebug() << "Starting Performance Test";

    t.start();

    for ( int j = 0; j < 100; ++j ) {
        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveUp();
            QCoreApplication::flush();
        }
        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveDown();
            QCoreApplication::flush();
        }

        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveRight();
            QCoreApplication::flush();
        }
        for ( int k = 0; k < 10; ++k ) {
            m_marbleWidget->moveLeft();
            QCoreApplication::flush();
        }
    }

    qDebug( "Timedemo finished in %ims", t.elapsed() );
    qDebug() <<  QString("= %1 fps").arg(4000*1000/(double)(t.elapsed()));

}

void MarbleTest::gpsDemo(){
    //
    //set up for the test
    //
    qDebug("stopping polling now");

    m_marbleWidget->model()->stopPolling();
    m_marbleWidget->rotateTo( -15.2325, 58.3723 );

    m_marbleWidget->setShowGps( true );

    //get the gpx file
    QString fileName = QFileDialog::getOpenFileName(m_marbleWidget,
            "Open File", QString(),
            "GPS Data (*.gpx);;KML (*.kml)");

    if ( ! fileName.isNull() ) {
        QString extension = fileName.section( '.', -1 );

        if ( extension.compare( "gpx", Qt::CaseInsensitive ) == 0 ) {
            m_marbleWidget->openGpxFile( fileName );
        }
    }

    QTime t;
    QTime totalTime;

    QVector<int> movingStats;
    QVector<int> staticStats;
    int temp=0;
    int totalMoving =0;
    int totalStatic =0;

    //
    //Start the test
    //
    totalTime.start();
    for( int i = 0; i< 5 ; i++) {

        m_marbleWidget->zoomViewBy( 400 );
        totalMoving =0;
        totalStatic =0;
        m_marbleWidget->rotateTo( -15.2325, 58.3723 );

        for( int i = 0; i< 5 ;i++ ){
            if( i%2) {
                m_marbleWidget->moveLeft();
            } else {
                m_marbleWidget->moveRight();
            }
            t.start();
            m_marbleWidget->updateGps();
            temp = t.elapsed();
//             qDebug("time elapsed moving %d",temp);
            totalMoving += temp;

        }

        for( int i = 0; i< 10 ;i++ ){
            t.start();
            m_marbleWidget->updateGps();
            temp=t.elapsed();
//             qDebug("time elapsed static %d",t.elapsed());
            totalStatic+=temp;
        }

//         qDebug ( "average of moving is %d at %d zoom",
//                  (totalMoving/10), m_marbleWidget->zoom() );
//         qDebug( "average of static is %d at %d zoom",
//                 (totalStatic/10) , m_marbleWidget->zoom() );
        movingStats.append( totalMoving/10 );
        staticStats.append( totalStatic/10 );

    }
    qDebug("total test time: %d", totalTime.elapsed());

    qDebug("full moving stats: ") ;
    qDebug() << movingStats;

    qDebug("full static stats: ");
    qDebug() << staticStats;

}
<|endoftext|>


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

#include "chrome/browser/ui/views/frame/app_non_client_frame_view_aura.h"

#include "base/debug/stack_trace.h"
#include "chrome/browser/ui/views/frame/browser_frame.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "grit/ui_resources.h"
#include "ui/aura/window.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/base/hit_test.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/compositor/layer.h"
#include "ui/gfx/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/non_client_view.h"

namespace {
// The number of pixels to use as a hover zone at the top of the screen.
const int kTopMargin = 1;
// How long the hover animation takes if uninterrupted.
const int kHoverFadeDurationMs = 130;
// The number of pixels within the shadow to draw the buttons.
const int kShadowStart = 28;
}

class AppNonClientFrameViewAura::ControlView
    : public views::View, public views::ButtonListener {
 public:
  explicit ControlView(AppNonClientFrameViewAura* owner) :
      owner_(owner),
      close_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_CLOSE)),
      restore_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_RESTORE)) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    separator_ =
        *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SEPARATOR).ToSkBitmap();
    shadow_ = *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SHADOW).ToSkBitmap();
    AddChildView(close_button_);
    AddChildView(restore_button_);
  }

  virtual void Layout() OVERRIDE {
    restore_button_->SetPosition(gfx::Point(kShadowStart, 0));
    close_button_->SetPosition(
        gfx::Point(kShadowStart + close_button_->width() + separator_.width(),
                   0));
  }

  virtual gfx::Size GetPreferredSize() OVERRIDE {
    return gfx::Size(shadow_.width(), shadow_.height());
  }

  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
    views::View::OnPaint(canvas);
    canvas->DrawBitmapInt(
        separator_, restore_button_->x() + restore_button_->width(), 0);
    canvas->DrawBitmapInt(shadow_, 0, 0);
  }

  void ButtonPressed(
      views::Button* sender,
      const views::Event& event) OVERRIDE {
    if (sender == close_button_)
      owner_->Close();
    else if (sender == restore_button_)
      owner_->Restore();
  }

 private:
  // Gets an image representing 3 bitmaps laid out horizontally that will be
  // used as the normal, hot and pushed states for the created button.
  views::ImageButton* CreateImageButton(int resource_id) {
    views::ImageButton* button = new views::ImageButton(this);
    const SkBitmap* all_images =
        ResourceBundle::GetSharedInstance().GetImageNamed(
            resource_id).ToSkBitmap();
    int width = all_images->width() / 3;
    int height = all_images->height();

    SkBitmap normal, hot, pushed;
    all_images->extractSubset(
        &normal,
        SkIRect::MakeXYWH(0, 0, width, height));
    all_images->extractSubset(
        &hot,
        SkIRect::MakeXYWH(width, 0, width, height));
    all_images->extractSubset(
        &pushed,
        SkIRect::MakeXYWH(2 * width, 0, width, height));
    button->SetImage(views::CustomButton::BS_NORMAL, &normal);
    button->SetImage(views::CustomButton::BS_HOT, &hot);
    button->SetImage(views::CustomButton::BS_PUSHED, &pushed);

    button->SizeToPreferredSize();
    return button;
  }

  AppNonClientFrameViewAura* owner_;
  views::ImageButton* close_button_;
  views::ImageButton* restore_button_;
  SkBitmap separator_;
  SkBitmap shadow_;

  DISALLOW_COPY_AND_ASSIGN(ControlView);
};

class AppNonClientFrameViewAura::Host : public views::MouseWatcherHost {
 public:
  explicit Host(AppNonClientFrameViewAura* owner) : owner_(owner) {}
  virtual ~Host() {}

  virtual bool Contains(
      const gfx::Point& screen_point,
      views::MouseWatcherHost::MouseEventType type) {
    gfx::Rect top_margin = owner_->GetScreenBounds();
    top_margin.set_height(kTopMargin);
    gfx::Rect control_bounds = owner_->GetControlBounds();
    control_bounds.Inset(kShadowStart, 0, 0, kShadowStart);
    return top_margin.Contains(screen_point) ||
        control_bounds.Contains(screen_point);
  }

  AppNonClientFrameViewAura* owner_;

  DISALLOW_COPY_AND_ASSIGN(Host);
};

AppNonClientFrameViewAura::AppNonClientFrameViewAura(
    BrowserFrame* frame, BrowserView* browser_view)
    : BrowserNonClientFrameView(frame, browser_view),
      control_view_(new ControlView(this)),
      control_widget_(NULL),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          mouse_watcher_(new Host(this), this)) {
}

AppNonClientFrameViewAura::~AppNonClientFrameViewAura() {
  if (control_widget_) {
    control_widget_->Close();
  }
}

gfx::Rect AppNonClientFrameViewAura::GetBoundsForClientView() const {
  gfx::Rect bounds = GetLocalBounds();
  bounds.Inset(0, kTopMargin, 0,  0);
  return bounds;
}

gfx::Rect AppNonClientFrameViewAura::GetWindowBoundsForClientBounds(
    const gfx::Rect& client_bounds) const {
  gfx::Rect bounds = client_bounds;
  bounds.Inset(0, -kTopMargin, 0, 0);
  return bounds;
}

int AppNonClientFrameViewAura::NonClientHitTest(
    const gfx::Point& point) {
  return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;
}

void AppNonClientFrameViewAura::GetWindowMask(const gfx::Size& size,
                                              gfx::Path* window_mask) {
}

void AppNonClientFrameViewAura::ResetWindowControls() {
}

void AppNonClientFrameViewAura::UpdateWindowIcon() {
}

gfx::Rect AppNonClientFrameViewAura::GetBoundsForTabStrip(
    views::View* tabstrip) const {
  return gfx::Rect();
}

int AppNonClientFrameViewAura::GetHorizontalTabStripVerticalOffset(
    bool restored) const {
  return 0;
}

void AppNonClientFrameViewAura::UpdateThrobber(bool running) {
}

void AppNonClientFrameViewAura::OnMouseEntered(
    const views::MouseEvent& event) {
  if (!control_widget_) {
    control_widget_ = new views::Widget;
    views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
    params.parent = browser_view()->GetNativeHandle();
    params.transparent = true;
    control_widget_->Init(params);
    control_widget_->SetContentsView(control_view_);
    aura::Window* window = control_widget_->GetNativeView();
    gfx::Rect control_bounds = GetControlBounds();
    control_bounds.set_y(control_bounds.y() - control_bounds.height());
    window->SetBounds(control_bounds);
    control_widget_->Show();
  }

  ui::Layer* layer = control_widget_->GetNativeView()->layer();
  ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());
  scoped_setter.SetTransitionDuration(
      base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));
  layer->SetBounds(GetControlBounds());
  layer->SetOpacity(1);

  mouse_watcher_.Start();
}

void AppNonClientFrameViewAura::MouseMovedOutOfHost() {
  ui::Layer* layer = control_widget_->GetNativeView()->layer();

  ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());
  scoped_setter.SetTransitionDuration(
      base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));
  gfx::Rect control_bounds = GetControlBounds();
  control_bounds.set_y(control_bounds.y() - control_bounds.height());
  layer->SetBounds(control_bounds);
  layer->SetOpacity(0);
}

gfx::Rect AppNonClientFrameViewAura::GetControlBounds() const {
  gfx::Size preferred = control_view_->GetPreferredSize();
  gfx::Point location(width() - preferred.width(), 0);
  ConvertPointToWidget(this, &location);
  return gfx::Rect(
      location.x(), location.y(),
      preferred.width(), preferred.height());
}

void AppNonClientFrameViewAura::Close() {
  control_widget_->Close();
  control_widget_ = NULL;
  mouse_watcher_.Stop();
  frame()->Close();
}

void AppNonClientFrameViewAura::Restore() {
  control_widget_->Close();
  control_widget_ = NULL;
  mouse_watcher_.Stop();
  frame()->Restore();
}
<commit_msg>Don't Close control_widget_ during teardown<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/frame/app_non_client_frame_view_aura.h"

#include "base/debug/stack_trace.h"
#include "chrome/browser/ui/views/frame/browser_frame.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "grit/ui_resources.h"
#include "ui/aura/window.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/base/hit_test.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/compositor/layer.h"
#include "ui/gfx/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/non_client_view.h"

namespace {
// The number of pixels to use as a hover zone at the top of the screen.
const int kTopMargin = 1;
// How long the hover animation takes if uninterrupted.
const int kHoverFadeDurationMs = 130;
// The number of pixels within the shadow to draw the buttons.
const int kShadowStart = 28;
}

class AppNonClientFrameViewAura::ControlView
    : public views::View, public views::ButtonListener {
 public:
  explicit ControlView(AppNonClientFrameViewAura* owner) :
      owner_(owner),
      close_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_CLOSE)),
      restore_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_RESTORE)) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    separator_ =
        *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SEPARATOR).ToSkBitmap();
    shadow_ = *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SHADOW).ToSkBitmap();
    AddChildView(close_button_);
    AddChildView(restore_button_);
  }

  virtual void Layout() OVERRIDE {
    restore_button_->SetPosition(gfx::Point(kShadowStart, 0));
    close_button_->SetPosition(
        gfx::Point(kShadowStart + close_button_->width() + separator_.width(),
                   0));
  }

  virtual gfx::Size GetPreferredSize() OVERRIDE {
    return gfx::Size(shadow_.width(), shadow_.height());
  }

  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
    views::View::OnPaint(canvas);
    canvas->DrawBitmapInt(
        separator_, restore_button_->x() + restore_button_->width(), 0);
    canvas->DrawBitmapInt(shadow_, 0, 0);
  }

  void ButtonPressed(
      views::Button* sender,
      const views::Event& event) OVERRIDE {
    if (sender == close_button_)
      owner_->Close();
    else if (sender == restore_button_)
      owner_->Restore();
  }

 private:
  // Gets an image representing 3 bitmaps laid out horizontally that will be
  // used as the normal, hot and pushed states for the created button.
  views::ImageButton* CreateImageButton(int resource_id) {
    views::ImageButton* button = new views::ImageButton(this);
    const SkBitmap* all_images =
        ResourceBundle::GetSharedInstance().GetImageNamed(
            resource_id).ToSkBitmap();
    int width = all_images->width() / 3;
    int height = all_images->height();

    SkBitmap normal, hot, pushed;
    all_images->extractSubset(
        &normal,
        SkIRect::MakeXYWH(0, 0, width, height));
    all_images->extractSubset(
        &hot,
        SkIRect::MakeXYWH(width, 0, width, height));
    all_images->extractSubset(
        &pushed,
        SkIRect::MakeXYWH(2 * width, 0, width, height));
    button->SetImage(views::CustomButton::BS_NORMAL, &normal);
    button->SetImage(views::CustomButton::BS_HOT, &hot);
    button->SetImage(views::CustomButton::BS_PUSHED, &pushed);

    button->SizeToPreferredSize();
    return button;
  }

  AppNonClientFrameViewAura* owner_;
  views::ImageButton* close_button_;
  views::ImageButton* restore_button_;
  SkBitmap separator_;
  SkBitmap shadow_;

  DISALLOW_COPY_AND_ASSIGN(ControlView);
};

class AppNonClientFrameViewAura::Host : public views::MouseWatcherHost {
 public:
  explicit Host(AppNonClientFrameViewAura* owner) : owner_(owner) {}
  virtual ~Host() {}

  virtual bool Contains(
      const gfx::Point& screen_point,
      views::MouseWatcherHost::MouseEventType type) {
    gfx::Rect top_margin = owner_->GetScreenBounds();
    top_margin.set_height(kTopMargin);
    gfx::Rect control_bounds = owner_->GetControlBounds();
    control_bounds.Inset(kShadowStart, 0, 0, kShadowStart);
    return top_margin.Contains(screen_point) ||
        control_bounds.Contains(screen_point);
  }

  AppNonClientFrameViewAura* owner_;

  DISALLOW_COPY_AND_ASSIGN(Host);
};

AppNonClientFrameViewAura::AppNonClientFrameViewAura(
    BrowserFrame* frame, BrowserView* browser_view)
    : BrowserNonClientFrameView(frame, browser_view),
      control_view_(new ControlView(this)),
      control_widget_(NULL),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          mouse_watcher_(new Host(this), this)) {
}

AppNonClientFrameViewAura::~AppNonClientFrameViewAura() {
}

gfx::Rect AppNonClientFrameViewAura::GetBoundsForClientView() const {
  gfx::Rect bounds = GetLocalBounds();
  bounds.Inset(0, kTopMargin, 0,  0);
  return bounds;
}

gfx::Rect AppNonClientFrameViewAura::GetWindowBoundsForClientBounds(
    const gfx::Rect& client_bounds) const {
  gfx::Rect bounds = client_bounds;
  bounds.Inset(0, -kTopMargin, 0, 0);
  return bounds;
}

int AppNonClientFrameViewAura::NonClientHitTest(
    const gfx::Point& point) {
  return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;
}

void AppNonClientFrameViewAura::GetWindowMask(const gfx::Size& size,
                                              gfx::Path* window_mask) {
}

void AppNonClientFrameViewAura::ResetWindowControls() {
}

void AppNonClientFrameViewAura::UpdateWindowIcon() {
}

gfx::Rect AppNonClientFrameViewAura::GetBoundsForTabStrip(
    views::View* tabstrip) const {
  return gfx::Rect();
}

int AppNonClientFrameViewAura::GetHorizontalTabStripVerticalOffset(
    bool restored) const {
  return 0;
}

void AppNonClientFrameViewAura::UpdateThrobber(bool running) {
}

void AppNonClientFrameViewAura::OnMouseEntered(
    const views::MouseEvent& event) {
  if (!control_widget_) {
    control_widget_ = new views::Widget;
    views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
    params.parent = browser_view()->GetNativeHandle();
    params.transparent = true;
    control_widget_->Init(params);
    control_widget_->SetContentsView(control_view_);
    aura::Window* window = control_widget_->GetNativeView();
    gfx::Rect control_bounds = GetControlBounds();
    control_bounds.set_y(control_bounds.y() - control_bounds.height());
    window->SetBounds(control_bounds);
    control_widget_->Show();
  }

  ui::Layer* layer = control_widget_->GetNativeView()->layer();
  ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());
  scoped_setter.SetTransitionDuration(
      base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));
  layer->SetBounds(GetControlBounds());
  layer->SetOpacity(1);

  mouse_watcher_.Start();
}

void AppNonClientFrameViewAura::MouseMovedOutOfHost() {
  ui::Layer* layer = control_widget_->GetNativeView()->layer();

  ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());
  scoped_setter.SetTransitionDuration(
      base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));
  gfx::Rect control_bounds = GetControlBounds();
  control_bounds.set_y(control_bounds.y() - control_bounds.height());
  layer->SetBounds(control_bounds);
  layer->SetOpacity(0);
}

gfx::Rect AppNonClientFrameViewAura::GetControlBounds() const {
  gfx::Size preferred = control_view_->GetPreferredSize();
  gfx::Point location(width() - preferred.width(), 0);
  ConvertPointToWidget(this, &location);
  return gfx::Rect(
      location.x(), location.y(),
      preferred.width(), preferred.height());
}

void AppNonClientFrameViewAura::Close() {
  if (control_widget_)
    control_widget_->Close();
  control_widget_ = NULL;
  mouse_watcher_.Stop();
  frame()->Close();
}

void AppNonClientFrameViewAura::Restore() {
  if (control_widget_)
    control_widget_->Close();
  control_widget_ = NULL;
  mouse_watcher_.Stop();
  frame()->Restore();
}
<|endoftext|>