<commit_before>/*
 * Movie.hpp
 *
 *  Created on: Sep 25, 2009
 *      Author: travel
 */

#ifndef MOVIE_HPP_
#define MOVIE_HPP_

#include "Image.hpp"

namespace PV {

class Movie: public PV::Image {
public:
   Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames, float displayPeriod);
   virtual ~Movie();

   virtual pvdata_t * getImageBuffer();
   virtual PVLayerLoc getImageLoc();

   bool updateImage(float time, float dt);
   virtual int updateState(float time, float dt);

   int copyReducedImagePortion();
   const char * getNextFileName();

   float displayPeriod;     // length of time a frame is displayed
   float nextDisplayTime;   // time of next frame

   char inputfile[PV_PATH_MAX];  // current input file name

   FILE * fp;
};

}

#endif /* MOVIE_HPP_ */
<commit_msg>Added outputState, calcPosition, and offsetX and offsetY.<commit_after>/*
 * Movie.hpp
 *
 *  Created on: Sep 25, 2009
 *      Author: travel
 */

#ifndef MOVIE_HPP_
#define MOVIE_HPP_

#include "Image.hpp"

namespace PV {

class Movie: public PV::Image {
public:
   Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames, float displayPeriod);
   virtual ~Movie();

   virtual pvdata_t * getImageBuffer();
   virtual PVLayerLoc getImageLoc();

   virtual int outputState(float time, bool last=false);
   virtual int updateState(float time, float dt);
   bool        updateImage(float time, float dt);

   int calcPosition(int pos, int step, int sizeLength);

private:

   int copyReducedImagePortion();
   const char * getNextFileName();

   float displayPeriod;     // length of time a frame is displayed
   float nextDisplayTime;   // time of next frame

   int offsetX;             // offset of layer section within full movie frame
   int offsetY;

   char inputfile[PV_PATH_MAX];  // current input file name

   FILE * fp;
};

}

#endif /* MOVIE_HPP_ */
<|endoftext|>


<commit_before>#include "include/importdialog.h"
#include "ui_importdialog.h"
#include <QFileDialog>
#include <QMessageBox>

ImportDialog::ImportDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ImportDialog), seperateImages(false){
    ui->setupUi(this);
}

ImportDialog::~ImportDialog(){
    delete ui;
}

void ImportDialog::on_pushButtonLeftImageBrowse_clicked(){
    QString file = QFileDialog::getOpenFileName(this, tr("Open Left Eye Image"), ui->lineEditLeftImage->text());
    if(!file.isEmpty()){
        ui->lineEditLeftImage->setText(file);
    }
}

void ImportDialog::on_pushButtonRightImageBrowse_clicked(){
    QString file = QFileDialog::getOpenFileName(this, tr("Open Right Eye Image"), ui->lineEditRightImage->text());
    if(!file.isEmpty()){
        ui->lineEditRightImage->setText(file);
    }
}

void ImportDialog::accept(){
    if(ui->tabWidget->currentWidget() == ui->tabSeperateImages){
        seperateImages = true;
        filenameLeft = ui->lineEditLeftImage->text();
        filenameRight = ui->lineEditRightImage->text();

        if(filenameLeft.isEmpty() || filenameRight.isEmpty()){
            QMessageBox::warning(this, tr("Error importing!"), tr("Please choose the image files to open."));
            return;
        }
        if(!QFile::exists(filenameLeft) || !QFile::exists(filenameRight)){
            QMessageBox::warning(this, tr("Error importing!"), tr("One or both of the files do not exist."));
            return;
        }
    }
    QDialog::accept();
}
<commit_msg>added filter to import browse dialogs.<commit_after>#include "include/importdialog.h"
#include "ui_importdialog.h"
#include <QFileDialog>
#include <QMessageBox>

ImportDialog::ImportDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ImportDialog), seperateImages(false){
    ui->setupUi(this);
}

ImportDialog::~ImportDialog(){
    delete ui;
}

void ImportDialog::on_pushButtonLeftImageBrowse_clicked(){
    QString file = QFileDialog::getOpenFileName(this, tr("Open Left Eye Image"), ui->lineEditLeftImage->text(), "Image Files (*.bmp *.jpg *.jpeg *.png *.ppm *.tiff *.xbm *.xpm)");
    if(!file.isEmpty()){
        ui->lineEditLeftImage->setText(file);
    }
}

void ImportDialog::on_pushButtonRightImageBrowse_clicked(){
    QString file = QFileDialog::getOpenFileName(this, tr("Open Right Eye Image"), ui->lineEditRightImage->text(), "Image Files (*.bmp *.jpg *.jpeg *.png *.ppm *.tiff *.xbm *.xpm)");
    if(!file.isEmpty()){
        ui->lineEditRightImage->setText(file);
    }
}

void ImportDialog::accept(){
    if(ui->tabWidget->currentWidget() == ui->tabSeperateImages){
        seperateImages = true;
        filenameLeft = ui->lineEditLeftImage->text();
        filenameRight = ui->lineEditRightImage->text();

        if(filenameLeft.isEmpty() || filenameRight.isEmpty()){
            QMessageBox::warning(this, tr("Error importing!"), tr("Please choose the image files to open."));
            return;
        }
        if(!QFile::exists(filenameLeft) || !QFile::exists(filenameRight)){
            QMessageBox::warning(this, tr("Error importing!"), tr("One or both of the files do not exist."));
            return;
        }
    }
    QDialog::accept();
}
<|endoftext|>


<commit_before>#include "ingame_state.h"
#include "game.h"
#include "player_context.h"
#include "play_player_state.h"

using namespace space_invaders;

IngameState::IngameState(Game& game)
  : State(game),
    mFooterLine(game),
    mAvatar(game),
    mLeftOobDetector(game),
    mRightOobDetector(game),
    mTopOobDetector(game),
    mAvatarLaser(game),
    mLifesText(game),
    mLifeSprite1(game),
    mLifeSprite2(game),
    mAlienLeftDirector(game),
    mAlienRightDirector(game),
    mGameOverText(game)
{
  // initialoize the green static footer line at the bottom of the screen.
  mFooterLine.setImage(game.getSpriteSheet());
  mFooterLine.setX(0);
  mFooterLine.setY(717);
  mFooterLine.setClip({0, 117, 672, 3});

  // initialize the out-of-bounds detector for the left side of the scene.
  mLeftOobDetector.setX(-100);
  mLeftOobDetector.setY(0);
  mLeftOobDetector.setExtentX(50);
  mLeftOobDetector.setExtentY(768 / 2);

  // initialize the out-of-bounds detector for the right side of the scene.
  mRightOobDetector.setX(672);
  mRightOobDetector.setY(0);
  mRightOobDetector.setExtentX(50);
  mRightOobDetector.setExtentY(768 / 2);

  // initialize the out-of-bounds detector for the top side of the scene.
  mTopOobDetector.setX(0);
  mTopOobDetector.setY(0);
  mTopOobDetector.setExtentX(768 / 2);
  mTopOobDetector.setExtentY(70);

  // initialize the text indicating the amount of lifes.
  auto& ctx = mGame.getActivePlayerContext();
  mLifesText.setText(std::to_string(ctx.getLives()));
  mLifesText.setX(27);
  mLifesText.setY(743 - mLifesText.getHeight() + 5);

  // initialize a sprite describing whether the player has at least one life left.
  mLifeSprite1.setImage(mGame.getSpriteSheet());
  mLifeSprite1.setWidth(40);
  mLifeSprite1.setHeight(24);
  mLifeSprite1.setX(66);
  mLifeSprite1.setY(720);
  mLifeSprite1.setClip({ 85, 5, 40, 24 });
  mLifeSprite1.setVisible(ctx.getLives() > 1);

  // initialize a sprite describing whether the player has at least two lifes left.
  mLifeSprite2.setImage(mGame.getSpriteSheet());
  mLifeSprite2.setWidth(40);
  mLifeSprite2.setHeight(24);
  mLifeSprite2.setX(66 + 49);
  mLifeSprite2.setY(720);
  mLifeSprite2.setClip({ 85, 5, 40, 24 });
  mLifeSprite2.setVisible(ctx.getLives() > 2);

  // get aliens from the user context or create them if not yet created.
  mAliens = ctx.getAliens();
  if (mAliens.empty()) {
    for (auto i = 0; i < 55; i++) {
      mAliens.push_back(std::make_shared<Alien>(game, i));
    }
  }

  // initialize the left alien director for alien movement direction change.
  mAlienLeftDirector.setX(-45);
  mAlienLeftDirector.setY(0);
  mAlienLeftDirector.setExtentX(45);
  mAlienLeftDirector.setExtentY(768 / 2);

  // initialize the right alien director for alien movement direction change.
  mAlienRightDirector.setX(672 - 45);
  mAlienRightDirector.setY(0);
  mAlienRightDirector.setExtentX(45);
  mAlienRightDirector.setExtentY(768 / 2);

  // initialize the text that indicates that the game has ended.
  mGameOverText.setText("GAME OVER");
  mGameOverText.setColor({245, 3, 5, 255 });
  mGameOverText.setX(672 / 2 - mGameOverText.getExtentX());
  mGameOverText.setY(135);
  mGameOverText.setVisible(false);
}

void IngameState::update(unsigned long dt)
{
  // skip logical updates if the game has ended.
  if (mGameOverText.isVisible()) {
    return;
  }

  mFooterLine.update(dt);
  mAvatar.update(dt);
  mAvatarLaser.update(dt);

  // decrement the relaunch timer if it has been activated or handle destruction state.
  auto& ctx = mGame.getActivePlayerContext();
  auto relaunchTimer = ctx.getRelaunchTimer();
  if (relaunchTimer > 0) {
    relaunchTimer--;
    ctx.setRelaunchTimer(relaunchTimer);
    return;
  } else if (mAvatar.isEnabled() == false) {
    const auto playerCount = mGame.getPlayerCount();
    if (playerCount == 1) {
      // ::: SINGLE PLAYER :::
      // check whether it's time to end the game or just reset the avatar.
      if (ctx.getLives() <= 0) {
        // check and update the hi-score if necessary.
        const auto score = ctx.getScore();
        if (mGame.getHiScore() < score) {
          mGame.setHiScore(score);
        }
        mGameOverText.setVisible(true);
        return;
      } else {
        // refresh the amount of lifes indicators.
        const auto lives = ctx.getLives();
        mLifesText.setText(std::to_string(lives));
        if (lives == 2) {
          mLifeSprite2.setVisible(false);
          mLifeSprite1.setVisible(true);
        } else if (lives == 1) {
          mLifeSprite2.setVisible(false);
          mLifeSprite1.setVisible(false);
        }

        // reset the avatar state.
        mAvatar.reset();
      }
    } else {
      // ::: MULTI-PLAYER :::
      // store the current state of the player into the player context.
      ctx.setAliens(mAliens);
      // TODO store shields.

      // perform additional actions based on the currently active player.
      const auto activePlayer = mGame.getActivePlayer();
      if (activePlayer == Game::Player::PLAYER_1) {
        // player one was playing so we can now switch to next player.
        mGame.setActivePlayer(Game::Player::PLAYER_2);
        auto state = std::make_shared<PlayPlayerState>(mGame);
        auto scene = mGame.getScene();
        scene->setState(state);
      } else {
        // player two was playing so we should now check whether to end the game.
        auto& player1Ctx = mGame.getPlayerContext1();
        auto& player2Ctx = mGame.getPlayerContext2();
        if (player2Ctx.getLives() <= 0) {
          // check and update player1 the hi-score if necessary.
          const auto player1Score = player1Ctx.getScore();
          if (mGame.getHiScore() < player1Score) {
            mGame.setHiScore(player1Score);
          }

          // check and update player2 the hi-score if necessary.
          const auto player2Score = player2Ctx.getScore();
          if (mGame.getHiScore() < player2Score) {
            mGame.setHiScore(player2Score);
          }

          // show the game over text and also the score for the 1st player.
          mGameOverText.setVisible(true);
          // view the player 1 score.
          return;
        } else {
          // was not the last life, so we can just switch to next player.
          mGame.setActivePlayer(Game::Player::PLAYER_1);
          auto state = std::make_shared<PlayPlayerState>(mGame);
          auto scene = mGame.getScene();
          scene->setState(state);
        }
      }
    }
  }

  // check that the avatar cannot go out-of-bounds from the scene boundaries.
  const auto avatarDirection = mAvatar.getDirectionX();
  if (avatarDirection < 0.f) {
    if (mLeftOobDetector.collides(mAvatar)) {
      mAvatar.setDirectionX(0.f);
      mAvatar.setX(mLeftOobDetector.getX() + mLeftOobDetector.getWidth());
    }
  } else if (avatarDirection > 0.f) {
    if (mRightOobDetector.collides(mAvatar)) {
      mAvatar.setDirectionX(0.f);
      mAvatar.setX(mRightOobDetector.getX() - mAvatar.getWidth());
    }
  }

  // check whether any of the aliens hits the alien director bounds.
  auto alienMovementChangeRequired = false;
  auto aliensDirection = mAliens[0]->getDirectionX();
  for (auto& alien : mAliens) {
    if (aliensDirection > 0) {
      if (mAlienRightDirector.collides(*alien)) {
        alienMovementChangeRequired = true;
        break;
      }
    } else {
      if (mAlienLeftDirector.collides(*alien)) {
        alienMovementChangeRequired = true;
        break;
      }
    }
  }

  // iterate over aliens and perform alien specific update operations.
  auto activeAlienCount = 0;
  if (mAvatar.isEnabled()) {
    for (auto& alien : mAliens) {
      // drop alien downwards and change the movement if required.
      if (alienMovementChangeRequired) {
        alien->setDirectionX(-aliensDirection);
        alien->setY(alien->getY() + alien->getHeight());
      }

      // perform active calculation and update active aliens.
      if (alien->isVisible()) {
        activeAlienCount++;
        alien->update(dt);

        // check whether the target alien has just landed or hit the player.
        if (alien->collides(mFooterLine)) {
          mAvatar.explode();
        } else if (alien->collides(mAvatar)) {
          mAvatar.explode();
        }
      }
    }
  }

  // check whether all aliens are destroyed i.e. the level is cleared.
  if (activeAlienCount <= 0) {
    ctx.setLevel(ctx.getLevel() + 1);
    auto scene = mGame.getScene();
    scene->setState(std::make_shared<PlayPlayerState>(mGame));
    return;
  }

  // check whether the avatar laser beam hits something.
  if (mAvatarLaser.isEnabled()) {
    if (mAvatarLaser.collides(mTopOobDetector)) {
      mAvatarLaser.setCurrentAnimation("top-wall-hit");
      mAvatarLaser.explode();
    } else {
      for (auto& alien : mAliens) {
        if (mAvatarLaser.collides(*alien)) {
          // create an alien laser to explode at the alien position.
          mAvatarLaser.setCurrentAnimation("alien-hit");
          mAvatarLaser.explode();
          mAvatarLaser.setX(alien->getCenterX() - mAvatarLaser.getExtentX());
          mAvatarLaser.setY(alien->getCenterY() - mAvatarLaser.getExtentY());
          alien->disappear();

          // add the alien row specific amount of points to the player.
          auto& ctx = mGame.getActivePlayerContext();
          auto points = alien->getPoints();
          ctx.addScore(points);

          // speed up the movement of the aliens.
          auto newStepSize = alien->getStepSize() - Alien::STEP_DECREMENT_SIZE;
          for (auto& a : mAliens) {
            a->setStepSize(newStepSize);
            a->setAnimationStepSize(newStepSize);
          }
          break;
        }
      }
    }
  }
}

void IngameState::render(SDL_Renderer& renderer)
{
  mGameOverText.render(renderer);
  mFooterLine.render(renderer);
  mAvatar.render(renderer);
  mAvatarLaser.render(renderer);
  mLifesText.render(renderer);
  mLifeSprite1.render(renderer);
  mLifeSprite2.render(renderer);
  for (auto& alien : mAliens) {
    alien->render(renderer);
  }
}

void IngameState::onEnter()
{
  // ...
}

void IngameState::onExit()
{
  // ...
}

void IngameState::onKeyUp(SDL_KeyboardEvent& event)
{
  switch (event.keysym.sym) {
  case SDLK_LEFT:
    if (mAvatar.isEnabled() && mAvatar.getDirectionX() < 0.f) {
      mAvatar.setDirectionX(0.f);
    }
    break;
  case SDLK_RIGHT:
    if (mAvatar.isEnabled() && mAvatar.getDirectionX() > 0.f) {
      mAvatar.setDirectionX(0.f);
    }
    break;
  case SDLK_SPACE:
    if (mAvatar.isEnabled() && mAvatarLaser.isVisible() == false) {
      mAvatarLaser.setVisible(true);
      mAvatarLaser.setEnabled(true);
      mAvatarLaser.setDirectionY(-1.f);
      mAvatarLaser.setX(mAvatar.getCenterX() - mAvatarLaser.getExtentX());
      mAvatarLaser.setY(mAvatar.getY());
      mAvatarLaser.setCurrentAnimation("normal");
      mAvatarLaser.setAnimationFrame(0);

      // increment the shot count that is used in variety of places.
      auto& ctx = mGame.getActivePlayerContext();
      ctx.setShotCount(ctx.getShotCount() + 1);
    }
    break;
  }
}

void IngameState::onKeyDown(SDL_KeyboardEvent& event)
{
  switch (event.keysym.sym) {
  case SDLK_LEFT:
    if (mAvatar.isEnabled()) {
      mAvatar.setDirectionX(-1.f);
    }
    break;
  case SDLK_RIGHT:
    if (mAvatar.isEnabled()) {
      mAvatar.setDirectionX(1.f);
    }
    break;
  }
}<commit_msg>Fixed a bug where player change was not correctly handled.<commit_after>#include "ingame_state.h"
#include "game.h"
#include "player_context.h"
#include "play_player_state.h"

using namespace space_invaders;

IngameState::IngameState(Game& game)
  : State(game),
    mFooterLine(game),
    mAvatar(game),
    mLeftOobDetector(game),
    mRightOobDetector(game),
    mTopOobDetector(game),
    mAvatarLaser(game),
    mLifesText(game),
    mLifeSprite1(game),
    mLifeSprite2(game),
    mAlienLeftDirector(game),
    mAlienRightDirector(game),
    mGameOverText(game)
{
  // initialoize the green static footer line at the bottom of the screen.
  mFooterLine.setImage(game.getSpriteSheet());
  mFooterLine.setX(0);
  mFooterLine.setY(717);
  mFooterLine.setClip({0, 117, 672, 3});

  // initialize the out-of-bounds detector for the left side of the scene.
  mLeftOobDetector.setX(-100);
  mLeftOobDetector.setY(0);
  mLeftOobDetector.setExtentX(50);
  mLeftOobDetector.setExtentY(768 / 2);

  // initialize the out-of-bounds detector for the right side of the scene.
  mRightOobDetector.setX(672);
  mRightOobDetector.setY(0);
  mRightOobDetector.setExtentX(50);
  mRightOobDetector.setExtentY(768 / 2);

  // initialize the out-of-bounds detector for the top side of the scene.
  mTopOobDetector.setX(0);
  mTopOobDetector.setY(0);
  mTopOobDetector.setExtentX(768 / 2);
  mTopOobDetector.setExtentY(70);

  // initialize the text indicating the amount of lifes.
  auto& ctx = mGame.getActivePlayerContext();
  mLifesText.setText(std::to_string(ctx.getLives()));
  mLifesText.setX(27);
  mLifesText.setY(743 - mLifesText.getHeight() + 5);

  // initialize a sprite describing whether the player has at least one life left.
  mLifeSprite1.setImage(mGame.getSpriteSheet());
  mLifeSprite1.setWidth(40);
  mLifeSprite1.setHeight(24);
  mLifeSprite1.setX(66);
  mLifeSprite1.setY(720);
  mLifeSprite1.setClip({ 85, 5, 40, 24 });
  mLifeSprite1.setVisible(ctx.getLives() > 1);

  // initialize a sprite describing whether the player has at least two lifes left.
  mLifeSprite2.setImage(mGame.getSpriteSheet());
  mLifeSprite2.setWidth(40);
  mLifeSprite2.setHeight(24);
  mLifeSprite2.setX(66 + 49);
  mLifeSprite2.setY(720);
  mLifeSprite2.setClip({ 85, 5, 40, 24 });
  mLifeSprite2.setVisible(ctx.getLives() > 2);

  // get aliens from the user context or create them if not yet created.
  mAliens = ctx.getAliens();
  if (mAliens.empty()) {
    for (auto i = 0; i < 55; i++) {
      mAliens.push_back(std::make_shared<Alien>(game, i));
    }
  }

  // initialize the left alien director for alien movement direction change.
  mAlienLeftDirector.setX(-45);
  mAlienLeftDirector.setY(0);
  mAlienLeftDirector.setExtentX(45);
  mAlienLeftDirector.setExtentY(768 / 2);

  // initialize the right alien director for alien movement direction change.
  mAlienRightDirector.setX(672 - 45);
  mAlienRightDirector.setY(0);
  mAlienRightDirector.setExtentX(45);
  mAlienRightDirector.setExtentY(768 / 2);

  // initialize the text that indicates that the game has ended.
  mGameOverText.setText("GAME OVER");
  mGameOverText.setColor({245, 3, 5, 255 });
  mGameOverText.setX(672 / 2 - mGameOverText.getExtentX());
  mGameOverText.setY(135);
  mGameOverText.setVisible(false);
}

void IngameState::update(unsigned long dt)
{
  // skip logical updates if the game has ended.
  if (mGameOverText.isVisible()) {
    return;
  }

  mFooterLine.update(dt);
  mAvatar.update(dt);
  mAvatarLaser.update(dt);

  // decrement the relaunch timer if it has been activated or handle destruction state.
  auto& ctx = mGame.getActivePlayerContext();
  auto relaunchTimer = ctx.getRelaunchTimer();
  if (relaunchTimer > 0) {
    relaunchTimer--;
    ctx.setRelaunchTimer(relaunchTimer);
    return;
  } else if (mAvatar.isEnabled() == false) {
    const auto playerCount = mGame.getPlayerCount();
    if (playerCount == 1) {
      // ::: SINGLE PLAYER :::
      // check whether it's time to end the game or just reset the avatar.
      if (ctx.getLives() <= 0) {
        // check and update the hi-score if necessary.
        const auto score = ctx.getScore();
        if (mGame.getHiScore() < score) {
          mGame.setHiScore(score);
        }
        mGameOverText.setVisible(true);
        return;
      } else {
        // refresh the amount of lifes indicators.
        const auto lives = ctx.getLives();
        mLifesText.setText(std::to_string(lives));
        if (lives == 2) {
          mLifeSprite2.setVisible(false);
          mLifeSprite1.setVisible(true);
        } else if (lives == 1) {
          mLifeSprite2.setVisible(false);
          mLifeSprite1.setVisible(false);
        }

        // reset the avatar state.
        mAvatar.reset();
      }
    } else {
      // ::: MULTI-PLAYER :::
      // store the current state of the player into the player context.
      ctx.setAliens(mAliens);
      // TODO store shields.

      // perform additional actions based on the currently active player.
      const auto activePlayer = mGame.getActivePlayer();
      if (activePlayer == Game::Player::PLAYER_1) {
        // player one was playing so we can now switch to next player.
        mGame.setActivePlayer(Game::Player::PLAYER_2);
        return;
      } else {
        // player two was playing so we should now check whether to end the game.
        auto& player1Ctx = mGame.getPlayerContext1();
        auto& player2Ctx = mGame.getPlayerContext2();
        if (player2Ctx.getLives() <= 0) {
          // check and update player1 the hi-score if necessary.
          const auto player1Score = player1Ctx.getScore();
          if (mGame.getHiScore() < player1Score) {
            mGame.setHiScore(player1Score);
          }

          // check and update player2 the hi-score if necessary.
          const auto player2Score = player2Ctx.getScore();
          if (mGame.getHiScore() < player2Score) {
            mGame.setHiScore(player2Score);
          }

          // show the game over text and also the score for the 1st player.
          mGameOverText.setVisible(true);
          // view the player 1 score.
          return;
        } else {
          // was not the last life, so we can just switch to next player.
          mGame.setActivePlayer(Game::Player::PLAYER_1);
          return;
        }
      }
    }
  }

  // check that the avatar cannot go out-of-bounds from the scene boundaries.
  const auto avatarDirection = mAvatar.getDirectionX();
  if (avatarDirection < 0.f) {
    if (mLeftOobDetector.collides(mAvatar)) {
      mAvatar.setDirectionX(0.f);
      mAvatar.setX(mLeftOobDetector.getX() + mLeftOobDetector.getWidth());
    }
  } else if (avatarDirection > 0.f) {
    if (mRightOobDetector.collides(mAvatar)) {
      mAvatar.setDirectionX(0.f);
      mAvatar.setX(mRightOobDetector.getX() - mAvatar.getWidth());
    }
  }

  // check whether any of the aliens hits the alien director bounds.
  auto alienMovementChangeRequired = false;
  auto aliensDirection = mAliens[0]->getDirectionX();
  for (auto& alien : mAliens) {
    if (aliensDirection > 0) {
      if (mAlienRightDirector.collides(*alien)) {
        alienMovementChangeRequired = true;
        break;
      }
    } else {
      if (mAlienLeftDirector.collides(*alien)) {
        alienMovementChangeRequired = true;
        break;
      }
    }
  }

  // iterate over aliens and perform alien specific update operations.
  auto activeAlienCount = 0;
  if (mAvatar.isEnabled()) {
    for (auto& alien : mAliens) {
      // drop alien downwards and change the movement if required.
      if (alienMovementChangeRequired) {
        alien->setDirectionX(-aliensDirection);
        alien->setY(alien->getY() + alien->getHeight());
      }

      // perform active calculation and update active aliens.
      if (alien->isVisible()) {
        activeAlienCount++;
        alien->update(dt);

        // check whether the target alien has just landed or hit the player.
        if (alien->collides(mFooterLine)) {
          mAvatar.explode();
        } else if (alien->collides(mAvatar)) {
          mAvatar.explode();
        }
      }
    }
  }

  // check whether all aliens are destroyed i.e. the level is cleared.
  if (activeAlienCount <= 0) {
    ctx.setLevel(ctx.getLevel() + 1);
    auto scene = mGame.getScene();
    scene->setState(std::make_shared<PlayPlayerState>(mGame));
    return;
  }

  // check whether the avatar laser beam hits something.
  if (mAvatarLaser.isEnabled()) {
    if (mAvatarLaser.collides(mTopOobDetector)) {
      mAvatarLaser.setCurrentAnimation("top-wall-hit");
      mAvatarLaser.explode();
    } else {
      for (auto& alien : mAliens) {
        if (mAvatarLaser.collides(*alien)) {
          // create an alien laser to explode at the alien position.
          mAvatarLaser.setCurrentAnimation("alien-hit");
          mAvatarLaser.explode();
          mAvatarLaser.setX(alien->getCenterX() - mAvatarLaser.getExtentX());
          mAvatarLaser.setY(alien->getCenterY() - mAvatarLaser.getExtentY());
          alien->disappear();

          // add the alien row specific amount of points to the player.
          auto& ctx = mGame.getActivePlayerContext();
          auto points = alien->getPoints();
          ctx.addScore(points);

          // speed up the movement of the aliens.
          auto newStepSize = alien->getStepSize() - Alien::STEP_DECREMENT_SIZE;
          for (auto& a : mAliens) {
            a->setStepSize(newStepSize);
            a->setAnimationStepSize(newStepSize);
          }
          break;
        }
      }
    }
  }
}

void IngameState::render(SDL_Renderer& renderer)
{
  mGameOverText.render(renderer);
  mFooterLine.render(renderer);
  mAvatar.render(renderer);
  mAvatarLaser.render(renderer);
  mLifesText.render(renderer);
  mLifeSprite1.render(renderer);
  mLifeSprite2.render(renderer);
  for (auto& alien : mAliens) {
    alien->render(renderer);
  }
}

void IngameState::onEnter()
{
  // ...
}

void IngameState::onExit()
{
  // ...
}

void IngameState::onKeyUp(SDL_KeyboardEvent& event)
{
  switch (event.keysym.sym) {
  case SDLK_LEFT:
    if (mAvatar.isEnabled() && mAvatar.getDirectionX() < 0.f) {
      mAvatar.setDirectionX(0.f);
    }
    break;
  case SDLK_RIGHT:
    if (mAvatar.isEnabled() && mAvatar.getDirectionX() > 0.f) {
      mAvatar.setDirectionX(0.f);
    }
    break;
  case SDLK_SPACE:
    if (mAvatar.isEnabled() && mAvatarLaser.isVisible() == false) {
      mAvatarLaser.setVisible(true);
      mAvatarLaser.setEnabled(true);
      mAvatarLaser.setDirectionY(-1.f);
      mAvatarLaser.setX(mAvatar.getCenterX() - mAvatarLaser.getExtentX());
      mAvatarLaser.setY(mAvatar.getY());
      mAvatarLaser.setCurrentAnimation("normal");
      mAvatarLaser.setAnimationFrame(0);

      // increment the shot count that is used in variety of places.
      auto& ctx = mGame.getActivePlayerContext();
      ctx.setShotCount(ctx.getShotCount() + 1);
    }
    break;
  }
}

void IngameState::onKeyDown(SDL_KeyboardEvent& event)
{
  switch (event.keysym.sym) {
  case SDLK_LEFT:
    if (mAvatar.isEnabled()) {
      mAvatar.setDirectionX(-1.f);
    }
    break;
  case SDLK_RIGHT:
    if (mAvatar.isEnabled()) {
      mAvatar.setDirectionX(1.f);
    }
    break;
  }
}<|endoftext|>


<commit_before>#include "io_interface.h"
#include "bignum_types.h"
#include "random_bignum_generator.h"
#include "constants.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

void read_bignum_arrays_from_files(uint32_t* a, uint32_t* b, const char* file_name_1, const char* file_name_2)
{
    printf("reading bignums from files ... ");
    fflush(stdout);
    read_bignum_array_from_file(file_name_1, a, NUMBER_OF_BIGNUMS);
    read_bignum_array_from_file(file_name_2, b, NUMBER_OF_BIGNUMS);
    printf("done\n");
    fflush(stdout);
}

void generate_random_bignum_arrays_to_files(const char* file_name_1, const char* file_name_2)
{
    start_random_number_generator();

    generate_random_bignum_array_to_file(file_name_1);
    generate_random_bignum_array_to_file(file_name_2);

    stop_random_number_generator();
}

void generate_random_bignum_array_to_file(const char* file_name)
{
    uint32_t* bignum = (uint32_t*) calloc(BIGNUM_NUMBER_OF_WORDS, sizeof(uint32_t));
    FILE* file = fopen(file_name, "w");

    for (uint32_t i = 0; i < NUMBER_OF_BIGNUMS; i++)
    {
        generate_random_bignum(bignum);

        for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)
        {
            fprintf(file, "%u ", bignum[j]);
        }

        fprintf(file, "\n");
    }
}

void read_bignum_array_from_file(const char* file_name, uint32_t* bignum, uint32_t amount_to_read)
{
    FILE* file = fopen(file_name, "r");

    for (uint32_t i = 0; i < amount_to_read; i++)
    {
        for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)
        {
            fscanf(file, "%u", &bignum[IDX(i, j)]);
        }

        fprintf(file, "\n");
    }

    fclose(file);
}

void write_bignum_array_to_file(const char* file_name, uint32_t* bignum)
{
    FILE* file = fopen(file_name, "w");

    for (uint32_t i = 0; i < NUMBER_OF_BIGNUMS; i++)
    {
        for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)
        {
            fprintf(file, "%u ", bignum[IDX(i, j)]);
        }

        fprintf(file, "\n");
    }

    fclose(file);
}
<commit_msg>adding error checking code for io_interface.cpp<commit_after>#include "io_interface.h"
#include "bignum_types.h"
#include "random_bignum_generator.h"
#include "constants.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

void read_bignum_arrays_from_files(uint32_t* a, uint32_t* b, const char* file_name_1, const char* file_name_2)
{
    if (a != NULL && b != NULL && file_name_1 != NULL && file_name_2 != NULL)
    {
        printf("reading bignums from files ... ");
        fflush(stdout);
        read_bignum_array_from_file(file_name_1, a, NUMBER_OF_BIGNUMS);
        read_bignum_array_from_file(file_name_2, b, NUMBER_OF_BIGNUMS);
        printf("done\n");
        fflush(stdout);
    }
    else
    {
        if (a == NULL)
        {
            printf("Error: bignum array \"a\" is NULL\n");
        }

        if (b == NULL)
        {
            printf("Error: bignum array \"b\" is NULL\n");
        }

        if (file_name_1 == NULL)
        {
            printf("Error: \"file_name_1\" is NULL\n");
        }

        if (file_name_2 == NULL)
        {
            printf("Error: \"file_name_2\" is NULL\n");
        }

        exit(0);
    }
}

void generate_random_bignum_arrays_to_files(const char* file_name_1, const char* file_name_2)
{
    if (file_name_1 != NULL && file_name_2 != NULL)
    {
        start_random_number_generator();

        generate_random_bignum_array_to_file(file_name_1);
        generate_random_bignum_array_to_file(file_name_2);

        stop_random_number_generator();
    }
    else
    {
        if (file_name_1 == NULL)
        {
            printf("Error: \"file_name_1\" is NULL\n");
        }

        if (file_name_2 == NULL)
        {
            printf("Error: \"file_name_2\" is NULL\n");
        }

        exit(0);
    }
}

void generate_random_bignum_array_to_file(const char* file_name)
{
    if (file_name != NULL)
    {
        FILE* file = fopen(file_name, "w");

        if (file != NULL)
        {
            uint32_t* bignum = (uint32_t*) calloc(BIGNUM_NUMBER_OF_WORDS, sizeof(uint32_t));

            if (bignum != NULL)
            {
                for (uint32_t i = 0; i < NUMBER_OF_BIGNUMS; i++)
                {
                    generate_random_bignum(bignum);

                    for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)
                    {
                        fprintf(file, "%u ", bignum[j]);
                    }

                    fprintf(file, "\n");
                }
            }
            else
            {
                printf("Error: could not allocate memory for generated bignum\n");
                exit(0);
            }

            fclose(file);
        }
        else
        {
            printf("Error: could not open file \"%s\" for writing\n", file_name);
            exit(0);
        }
    }
    else
    {
        printf("Error: \"file_name\" is NULL\n");
        exit(0);
    }
}

void read_bignum_array_from_file(const char* file_name, uint32_t* bignum, uint32_t amount_to_read)
{
    // TODO
    if (file_name != NULL && bignum != NULL && amount_to_read > 0)
    {
        FILE* file = fopen(file_name, "r");

        if (file != NULL)
        {
            for (uint32_t i = 0; i < amount_to_read; i++)
            {
                for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)
                {
                    fscanf(file, "%u", &bignum[IDX(i, j)]);
                }

                fprintf(file, "\n");
            }

            fclose(file);
        }
        else
        {
            printf("Error: could not open file \"%s\" for reading\n", file_name);
            exit(0);
        }
    }
    else
    {
        if (file_name == NULL)
        {
            printf("Error: \"file_name\" is NULL\n");
        }

        if (bignum == NULL)
        {
            printf("Error: bignum array \"bignum\" is NULL\n");
        }

        exit(0);
    }
}

void write_bignum_array_to_file(const char* file_name, uint32_t* bignum)
{
    FILE* file = fopen(file_name, "w");

    if (file != NULL)
    {
        for (uint32_t i = 0; i < NUMBER_OF_BIGNUMS; i++)
        {
            for (uint32_t j = 0; j < BIGNUM_NUMBER_OF_WORDS; j++)
            {
                fprintf(file, "%u ", bignum[IDX(i, j)]);
            }

            fprintf(file, "\n");
        }

        fclose(file);
    }
    else
    {
        printf("Error: could not open file \"%s\" for writing\n", file_name);
        exit(0);
    }
}
<|endoftext|>


<commit_before>/*
 * istream implementation which reads nothing.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_null.hxx"
#include "istream_internal.hxx"
#include "util/Cast.hxx"
#include "pool.hxx"

#include <unistd.h>

struct NullIstream {
    struct istream stream;

    NullIstream(struct pool &p);
};

static inline NullIstream &
istream_to_null(struct istream *istream)
{
    return ContainerCast2(*istream, &NullIstream::stream);
}

static off_t
istream_null_available(struct istream *istream gcc_unused,
                       bool partial gcc_unused)
{
    return 0;
}

static off_t
istream_null_skip(struct istream *istream gcc_unused, off_t length gcc_unused)
{
    return 0;
}

static void
istream_null_read(struct istream *istream)
{
    NullIstream &null = istream_to_null(istream);

    istream_deinit_eof(&null.stream);
}

static int
istream_null_as_fd(struct istream *istream)
{
    NullIstream &null = istream_to_null(istream);

    /* fd0 is always linked with /dev/null */
    int fd = dup(0);
    if (fd < 0)
        return -1;

    istream_deinit(&null.stream);
    return fd;
}

static void
istream_null_close(struct istream *istream)
{
    NullIstream &null = istream_to_null(istream);

    istream_deinit(&null.stream);
}

static constexpr struct istream_class istream_null = {
    .available = istream_null_available,
    .skip = istream_null_skip,
    .read = istream_null_read,
    .as_fd = istream_null_as_fd,
    .close = istream_null_close,
};

inline NullIstream::NullIstream(struct pool &p)
{
    istream_init(&stream, &istream_null, &p);
}

struct istream *
istream_null_new(struct pool *pool)
{
    auto *n = NewFromPool<NullIstream>(*pool, *pool);
    return &n->stream;
}
<commit_msg>istream_null: rename "stream" to "output"<commit_after>/*
 * istream implementation which reads nothing.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_null.hxx"
#include "istream_internal.hxx"
#include "util/Cast.hxx"
#include "pool.hxx"

#include <unistd.h>

struct NullIstream {
    struct istream output;

    NullIstream(struct pool &p);
};

static inline NullIstream &
istream_to_null(struct istream *istream)
{
    return ContainerCast2(*istream, &NullIstream::output);
}

static off_t
istream_null_available(struct istream *istream gcc_unused,
                       bool partial gcc_unused)
{
    return 0;
}

static off_t
istream_null_skip(struct istream *istream gcc_unused, off_t length gcc_unused)
{
    return 0;
}

static void
istream_null_read(struct istream *istream)
{
    NullIstream &null = istream_to_null(istream);

    istream_deinit_eof(&null.output);
}

static int
istream_null_as_fd(struct istream *istream)
{
    NullIstream &null = istream_to_null(istream);

    /* fd0 is always linked with /dev/null */
    int fd = dup(0);
    if (fd < 0)
        return -1;

    istream_deinit(&null.output);
    return fd;
}

static void
istream_null_close(struct istream *istream)
{
    NullIstream &null = istream_to_null(istream);

    istream_deinit(&null.output);
}

static constexpr struct istream_class istream_null = {
    .available = istream_null_available,
    .skip = istream_null_skip,
    .read = istream_null_read,
    .as_fd = istream_null_as_fd,
    .close = istream_null_close,
};

inline NullIstream::NullIstream(struct pool &p)
{
    istream_init(&output, &istream_null, &p);
}

struct istream *
istream_null_new(struct pool *pool)
{
    auto *n = NewFromPool<NullIstream>(*pool, *pool);
    return &n->output;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <iostream>
#include <sstream>
namespace votca { namespace ctp {
;
}}

<commit_msg>added GSL OFF to CMake<commit_after><|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 "ui/views/controls/webview/webview.h"

#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "ipc/ipc_message.h"
#include "ui/accessibility/ax_enums.h"
#include "ui/accessibility/ax_view_state.h"
#include "ui/base/ui_base_switches_util.h"
#include "ui/events/event.h"
#include "ui/views/accessibility/native_view_accessibility.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/views_delegate.h"

namespace views {

// static
const char WebView::kViewClassName[] = "WebView";

////////////////////////////////////////////////////////////////////////////////
// WebView, public:

WebView::WebView(content::BrowserContext* browser_context)
    : holder_(new NativeViewHost()),
      embed_fullscreen_widget_mode_enabled_(false),
      is_embedding_fullscreen_widget_(false),
      browser_context_(browser_context),
      allow_accelerators_(false) {
  AddChildView(holder_);  // Takes ownership of |holder_|.
  NativeViewAccessibility::RegisterWebView(this);
}

WebView::~WebView() {
  SetWebContents(NULL);  // Make sure all necessary tear-down takes place.
  NativeViewAccessibility::UnregisterWebView(this);
}

content::WebContents* WebView::GetWebContents() {
  if (!web_contents()) {
    wc_owner_.reset(CreateWebContents(browser_context_));
    wc_owner_->SetDelegate(this);
    SetWebContents(wc_owner_.get());
  }
  return web_contents();
}

void WebView::SetWebContents(content::WebContents* replacement) {
  if (replacement == web_contents())
    return;
  DetachWebContents();
  WebContentsObserver::Observe(replacement);
  // web_contents() now returns |replacement| from here onwards.
  SetFocusable(!!web_contents());
  if (wc_owner_ != replacement)
    wc_owner_.reset();
  if (embed_fullscreen_widget_mode_enabled_) {
    is_embedding_fullscreen_widget_ =
        web_contents() && web_contents()->GetFullscreenRenderWidgetHostView();
  } else {
    DCHECK(!is_embedding_fullscreen_widget_);
  }
  AttachWebContents();
  NotifyMaybeTextInputClientChanged();
}

void WebView::SetEmbedFullscreenWidgetMode(bool enable) {
  DCHECK(!web_contents())
      << "Cannot change mode while a WebContents is attached.";
  embed_fullscreen_widget_mode_enabled_ = enable;
}

void WebView::LoadInitialURL(const GURL& url) {
  GetWebContents()->GetController().LoadURL(
      url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
      std::string());
}

void WebView::SetFastResize(bool fast_resize) {
  holder_->set_fast_resize(fast_resize);
}

void WebView::SetResizeBackgroundColor(SkColor resize_background_color) {
  holder_->set_resize_background_color(resize_background_color);
}

void WebView::OnWebContentsFocused(content::WebContents* web_contents) {
  FocusManager* focus_manager = GetFocusManager();
  if (focus_manager)
    focus_manager->SetFocusedView(this);
}

void WebView::SetPreferredSize(const gfx::Size& preferred_size) {
  preferred_size_ = preferred_size;
  PreferredSizeChanged();
}

////////////////////////////////////////////////////////////////////////////////
// WebView, View overrides:

const char* WebView::GetClassName() const {
  return kViewClassName;
}

ui::TextInputClient* WebView::GetTextInputClient() {
  // This function delegates the text input handling to the underlying
  // content::RenderWidgetHostView.  So when the underlying RWHV is destroyed or
  // replaced with another one, we have to notify the FocusManager through
  // FocusManager::OnTextInputClientChanged() that the focused TextInputClient
  // needs to be updated.
  if (switches::IsTextInputFocusManagerEnabled() &&
      web_contents() && !web_contents()->IsBeingDestroyed()) {
    content::RenderWidgetHostView* host_view =
        is_embedding_fullscreen_widget_ ?
        web_contents()->GetFullscreenRenderWidgetHostView() :
        web_contents()->GetRenderWidgetHostView();
    if (host_view)
      return host_view->GetTextInputClient();
  }
  return NULL;
}

scoped_ptr<content::WebContents> WebView::SwapWebContents(
    scoped_ptr<content::WebContents> new_web_contents) {
  if (wc_owner_)
    wc_owner_->SetDelegate(NULL);
  scoped_ptr<content::WebContents> old_web_contents(wc_owner_.Pass());
  wc_owner_ = new_web_contents.Pass();
  if (wc_owner_)
    wc_owner_->SetDelegate(this);
  SetWebContents(wc_owner_.get());
  return old_web_contents.Pass();
}

void WebView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
  // In most cases, the holder is simply sized to fill this WebView's bounds.
  // Only WebContentses that are in fullscreen mode and being screen-captured
  // will engage the special layout/sizing behavior.
  gfx::Rect holder_bounds(bounds().size());
  if (!embed_fullscreen_widget_mode_enabled_ ||
      !web_contents() ||
      web_contents()->GetCapturerCount() == 0 ||
      web_contents()->GetPreferredSize().IsEmpty() ||
      !(is_embedding_fullscreen_widget_ ||
        (web_contents()->GetDelegate() &&
         web_contents()->GetDelegate()->
             IsFullscreenForTabOrPending(web_contents())))) {
    holder_->SetBoundsRect(holder_bounds);
    return;
  }

  // Size the holder to the capture video resolution and center it.  If this
  // WebView is not large enough to contain the holder at the preferred size,
  // scale down to fit (preserving aspect ratio).
  const gfx::Size capture_size = web_contents()->GetPreferredSize();
  if (capture_size.width() <= holder_bounds.width() &&
      capture_size.height() <= holder_bounds.height()) {
    // No scaling, just centering.
    holder_bounds.ClampToCenteredSize(capture_size);
  } else {
    // Scale down, preserving aspect ratio, and center.
    // TODO(miu): This is basically media::ComputeLetterboxRegion(), and it
    // looks like others have written this code elsewhere.  Let's considate
    // into a shared function ui/gfx/geometry or around there.
    const int64 x = static_cast<int64>(capture_size.width()) *
        holder_bounds.height();
    const int64 y = static_cast<int64>(capture_size.height()) *
        holder_bounds.width();
    if (y < x) {
      holder_bounds.ClampToCenteredSize(gfx::Size(
          holder_bounds.width(), static_cast<int>(y / capture_size.width())));
    } else {
      holder_bounds.ClampToCenteredSize(gfx::Size(
          static_cast<int>(x / capture_size.height()), holder_bounds.height()));
    }
  }

  holder_->SetBoundsRect(holder_bounds);
}

void WebView::ViewHierarchyChanged(
    const ViewHierarchyChangedDetails& details) {
  if (details.is_add)
    AttachWebContents();
}

bool WebView::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
  if (allow_accelerators_)
    return FocusManager::IsTabTraversalKeyEvent(event);

  // Don't look-up accelerators or tab-traversal if we are showing a non-crashed
  // TabContents.
  // We'll first give the page a chance to process the key events.  If it does
  // not process them, they'll be returned to us and we'll treat them as
  // accelerators then.
  return web_contents() && !web_contents()->IsCrashed();
}

bool WebView::OnMousePressed(const ui::MouseEvent& event) {
  // A left-click within WebView is a request to focus.  The area within the
  // native view child is excluded since it will be handling mouse pressed
  // events itself (http://crbug.com/436192).
  if (event.IsOnlyLeftMouseButton() && HitTestPoint(event.location())) {
    gfx::Point location_in_holder = event.location();
    ConvertPointToTarget(this, holder_, &location_in_holder);
    if (!holder_->HitTestPoint(location_in_holder)) {
      RequestFocus();
      return true;
    }
  }
  return View::OnMousePressed(event);
}

void WebView::OnFocus() {
  if (web_contents())
    web_contents()->Focus();
}

void WebView::AboutToRequestFocusFromTabTraversal(bool reverse) {
  if (web_contents())
    web_contents()->FocusThroughTabTraversal(reverse);
}

void WebView::GetAccessibleState(ui::AXViewState* state) {
  state->role = ui::AX_ROLE_WEB_VIEW;
}

gfx::NativeViewAccessible WebView::GetNativeViewAccessible() {
  if (web_contents()) {
    content::RenderWidgetHostView* host_view =
        web_contents()->GetRenderWidgetHostView();
    if (host_view)
      return host_view->GetNativeViewAccessible();
  }
  return View::GetNativeViewAccessible();
}

gfx::Size WebView::GetPreferredSize() const {
  if (preferred_size_ == gfx::Size())
    return View::GetPreferredSize();
  else
    return preferred_size_;
}

////////////////////////////////////////////////////////////////////////////////
// WebView, content::WebContentsDelegate implementation:

void WebView::WebContentsFocused(content::WebContents* web_contents) {
  DCHECK(wc_owner_.get());
  // The WebView is only the delegate of WebContentses it creates itself.
  OnWebContentsFocused(wc_owner_.get());
}

bool WebView::EmbedsFullscreenWidget() const {
  DCHECK(wc_owner_.get());
  return embed_fullscreen_widget_mode_enabled_;
}

////////////////////////////////////////////////////////////////////////////////
// WebView, content::WebContentsObserver implementation:

void WebView::RenderViewDeleted(content::RenderViewHost* render_view_host) {
  NotifyMaybeTextInputClientChanged();
}

void WebView::RenderProcessGone(base::TerminationStatus status) {
  NotifyMaybeTextInputClientChanged();
}

void WebView::RenderViewHostChanged(content::RenderViewHost* old_host,
                                    content::RenderViewHost* new_host) {
  FocusManager* const focus_manager = GetFocusManager();
  if (focus_manager && focus_manager->GetFocusedView() == this)
    OnFocus();
  NotifyMaybeTextInputClientChanged();
}

void WebView::DidShowFullscreenWidget(int routing_id) {
  if (embed_fullscreen_widget_mode_enabled_)
    ReattachForFullscreenChange(true);
}

void WebView::DidDestroyFullscreenWidget(int routing_id) {
  if (embed_fullscreen_widget_mode_enabled_)
    ReattachForFullscreenChange(false);
}

void WebView::DidToggleFullscreenModeForTab(bool entered_fullscreen) {
  if (embed_fullscreen_widget_mode_enabled_)
    ReattachForFullscreenChange(entered_fullscreen);
}

void WebView::DidAttachInterstitialPage() {
  NotifyMaybeTextInputClientChanged();
}

void WebView::DidDetachInterstitialPage() {
  NotifyMaybeTextInputClientChanged();
}

////////////////////////////////////////////////////////////////////////////////
// WebView, private:

void WebView::AttachWebContents() {
  // Prevents attachment if the WebView isn't already in a Widget, or it's
  // already attached.
  if (!GetWidget() || !web_contents())
    return;

  const gfx::NativeView view_to_attach = is_embedding_fullscreen_widget_ ?
      web_contents()->GetFullscreenRenderWidgetHostView()->GetNativeView() :
      web_contents()->GetNativeView();
  OnBoundsChanged(bounds());
  if (holder_->native_view() == view_to_attach)
    return;

  holder_->Attach(view_to_attach);

  // The view will not be focused automatically when it is attached, so we need
  // to pass on focus to it if the FocusManager thinks the view is focused. Note
  // that not every Widget has a focus manager.
  FocusManager* const focus_manager = GetFocusManager();
  if (focus_manager && focus_manager->GetFocusedView() == this)
    OnFocus();

#if defined(OS_WIN)
  if (!is_embedding_fullscreen_widget_) {
    web_contents()->SetParentNativeViewAccessible(
        parent()->GetNativeViewAccessible());
  }
#endif
}

void WebView::DetachWebContents() {
  if (web_contents()) {
    holder_->Detach();
#if defined(OS_WIN)
    if (!is_embedding_fullscreen_widget_)
      web_contents()->SetParentNativeViewAccessible(NULL);
#endif
  }
}

void WebView::ReattachForFullscreenChange(bool enter_fullscreen) {
  DCHECK(embed_fullscreen_widget_mode_enabled_);
  const bool web_contents_has_separate_fs_widget =
      web_contents() && web_contents()->GetFullscreenRenderWidgetHostView();
  if (is_embedding_fullscreen_widget_ || web_contents_has_separate_fs_widget) {
    // Shutting down or starting up the embedding of the separate fullscreen
    // widget.  Need to detach and re-attach to a different native view.
    DetachWebContents();
    is_embedding_fullscreen_widget_ =
        enter_fullscreen && web_contents_has_separate_fs_widget;
    AttachWebContents();
  } else {
    // Entering or exiting "non-Flash" fullscreen mode, where the native view is
    // the same.  So, do not change attachment.
    OnBoundsChanged(bounds());
  }
  NotifyMaybeTextInputClientChanged();
}

void WebView::NotifyMaybeTextInputClientChanged() {
  // Update the TextInputClient as needed; see GetTextInputClient().
  FocusManager* const focus_manager = GetFocusManager();
  if (focus_manager)
    focus_manager->OnTextInputClientChanged(this);
}

content::WebContents* WebView::CreateWebContents(
      content::BrowserContext* browser_context) {
  content::WebContents* contents = NULL;
  if (ViewsDelegate::views_delegate) {
    contents = ViewsDelegate::views_delegate->CreateWebContents(
        browser_context, NULL);
  }

  if (!contents) {
    content::WebContents::CreateParams create_params(
        browser_context, NULL);
    return content::WebContents::Create(create_params);
  }

  return contents;
}

}  // namespace views
<commit_msg>disable webview handling of mouse click on gray area<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 "ui/views/controls/webview/webview.h"

#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "ipc/ipc_message.h"
#include "ui/accessibility/ax_enums.h"
#include "ui/accessibility/ax_view_state.h"
#include "ui/base/ui_base_switches_util.h"
#include "ui/events/event.h"
#include "ui/views/accessibility/native_view_accessibility.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/views_delegate.h"

namespace views {

// static
const char WebView::kViewClassName[] = "WebView";

////////////////////////////////////////////////////////////////////////////////
// WebView, public:

WebView::WebView(content::BrowserContext* browser_context)
    : holder_(new NativeViewHost()),
      embed_fullscreen_widget_mode_enabled_(false),
      is_embedding_fullscreen_widget_(false),
      browser_context_(browser_context),
      allow_accelerators_(false) {
  AddChildView(holder_);  // Takes ownership of |holder_|.
  NativeViewAccessibility::RegisterWebView(this);
}

WebView::~WebView() {
  SetWebContents(NULL);  // Make sure all necessary tear-down takes place.
  NativeViewAccessibility::UnregisterWebView(this);
}

content::WebContents* WebView::GetWebContents() {
  if (!web_contents()) {
    wc_owner_.reset(CreateWebContents(browser_context_));
    wc_owner_->SetDelegate(this);
    SetWebContents(wc_owner_.get());
  }
  return web_contents();
}

void WebView::SetWebContents(content::WebContents* replacement) {
  if (replacement == web_contents())
    return;
  DetachWebContents();
  WebContentsObserver::Observe(replacement);
  // web_contents() now returns |replacement| from here onwards.
  SetFocusable(!!web_contents());
  if (wc_owner_ != replacement)
    wc_owner_.reset();
  if (embed_fullscreen_widget_mode_enabled_) {
    is_embedding_fullscreen_widget_ =
        web_contents() && web_contents()->GetFullscreenRenderWidgetHostView();
  } else {
    DCHECK(!is_embedding_fullscreen_widget_);
  }
  AttachWebContents();
  NotifyMaybeTextInputClientChanged();
}

void WebView::SetEmbedFullscreenWidgetMode(bool enable) {
  DCHECK(!web_contents())
      << "Cannot change mode while a WebContents is attached.";
  embed_fullscreen_widget_mode_enabled_ = enable;
}

void WebView::LoadInitialURL(const GURL& url) {
  GetWebContents()->GetController().LoadURL(
      url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
      std::string());
}

void WebView::SetFastResize(bool fast_resize) {
  holder_->set_fast_resize(fast_resize);
}

void WebView::SetResizeBackgroundColor(SkColor resize_background_color) {
  holder_->set_resize_background_color(resize_background_color);
}

void WebView::OnWebContentsFocused(content::WebContents* web_contents) {
  FocusManager* focus_manager = GetFocusManager();
  if (focus_manager)
    focus_manager->SetFocusedView(this);
}

void WebView::SetPreferredSize(const gfx::Size& preferred_size) {
  preferred_size_ = preferred_size;
  PreferredSizeChanged();
}

////////////////////////////////////////////////////////////////////////////////
// WebView, View overrides:

const char* WebView::GetClassName() const {
  return kViewClassName;
}

ui::TextInputClient* WebView::GetTextInputClient() {
  // This function delegates the text input handling to the underlying
  // content::RenderWidgetHostView.  So when the underlying RWHV is destroyed or
  // replaced with another one, we have to notify the FocusManager through
  // FocusManager::OnTextInputClientChanged() that the focused TextInputClient
  // needs to be updated.
  if (switches::IsTextInputFocusManagerEnabled() &&
      web_contents() && !web_contents()->IsBeingDestroyed()) {
    content::RenderWidgetHostView* host_view =
        is_embedding_fullscreen_widget_ ?
        web_contents()->GetFullscreenRenderWidgetHostView() :
        web_contents()->GetRenderWidgetHostView();
    if (host_view)
      return host_view->GetTextInputClient();
  }
  return NULL;
}

scoped_ptr<content::WebContents> WebView::SwapWebContents(
    scoped_ptr<content::WebContents> new_web_contents) {
  if (wc_owner_)
    wc_owner_->SetDelegate(NULL);
  scoped_ptr<content::WebContents> old_web_contents(wc_owner_.Pass());
  wc_owner_ = new_web_contents.Pass();
  if (wc_owner_)
    wc_owner_->SetDelegate(this);
  SetWebContents(wc_owner_.get());
  return old_web_contents.Pass();
}

void WebView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
  // In most cases, the holder is simply sized to fill this WebView's bounds.
  // Only WebContentses that are in fullscreen mode and being screen-captured
  // will engage the special layout/sizing behavior.
  gfx::Rect holder_bounds(bounds().size());
  if (!embed_fullscreen_widget_mode_enabled_ ||
      !web_contents() ||
      web_contents()->GetCapturerCount() == 0 ||
      web_contents()->GetPreferredSize().IsEmpty() ||
      !(is_embedding_fullscreen_widget_ ||
        (web_contents()->GetDelegate() &&
         web_contents()->GetDelegate()->
             IsFullscreenForTabOrPending(web_contents())))) {
    holder_->SetBoundsRect(holder_bounds);
    return;
  }

  // Size the holder to the capture video resolution and center it.  If this
  // WebView is not large enough to contain the holder at the preferred size,
  // scale down to fit (preserving aspect ratio).
  const gfx::Size capture_size = web_contents()->GetPreferredSize();
  if (capture_size.width() <= holder_bounds.width() &&
      capture_size.height() <= holder_bounds.height()) {
    // No scaling, just centering.
    holder_bounds.ClampToCenteredSize(capture_size);
  } else {
    // Scale down, preserving aspect ratio, and center.
    // TODO(miu): This is basically media::ComputeLetterboxRegion(), and it
    // looks like others have written this code elsewhere.  Let's considate
    // into a shared function ui/gfx/geometry or around there.
    const int64 x = static_cast<int64>(capture_size.width()) *
        holder_bounds.height();
    const int64 y = static_cast<int64>(capture_size.height()) *
        holder_bounds.width();
    if (y < x) {
      holder_bounds.ClampToCenteredSize(gfx::Size(
          holder_bounds.width(), static_cast<int>(y / capture_size.width())));
    } else {
      holder_bounds.ClampToCenteredSize(gfx::Size(
          static_cast<int>(x / capture_size.height()), holder_bounds.height()));
    }
  }

  holder_->SetBoundsRect(holder_bounds);
}

void WebView::ViewHierarchyChanged(
    const ViewHierarchyChangedDetails& details) {
  if (details.is_add)
    AttachWebContents();
}

bool WebView::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
  if (allow_accelerators_)
    return FocusManager::IsTabTraversalKeyEvent(event);

  // Don't look-up accelerators or tab-traversal if we are showing a non-crashed
  // TabContents.
  // We'll first give the page a chance to process the key events.  If it does
  // not process them, they'll be returned to us and we'll treat them as
  // accelerators then.
  return web_contents() && !web_contents()->IsCrashed();
}

bool WebView::OnMousePressed(const ui::MouseEvent& event) {
#if 0
  if (event.IsOnlyLeftMouseButton() && HitTestPoint(event.location())) {
    gfx::Point location_in_holder = event.location();
    ConvertPointToTarget(this, holder_, &location_in_holder);
    if (!holder_->HitTestPoint(location_in_holder)) {
      RequestFocus();
      return true;
    }
  }
#endif
  return View::OnMousePressed(event);
}

void WebView::OnFocus() {
  if (web_contents())
    web_contents()->Focus();
}

void WebView::AboutToRequestFocusFromTabTraversal(bool reverse) {
  if (web_contents())
    web_contents()->FocusThroughTabTraversal(reverse);
}

void WebView::GetAccessibleState(ui::AXViewState* state) {
  state->role = ui::AX_ROLE_WEB_VIEW;
}

gfx::NativeViewAccessible WebView::GetNativeViewAccessible() {
  if (web_contents()) {
    content::RenderWidgetHostView* host_view =
        web_contents()->GetRenderWidgetHostView();
    if (host_view)
      return host_view->GetNativeViewAccessible();
  }
  return View::GetNativeViewAccessible();
}

gfx::Size WebView::GetPreferredSize() const {
  if (preferred_size_ == gfx::Size())
    return View::GetPreferredSize();
  else
    return preferred_size_;
}

////////////////////////////////////////////////////////////////////////////////
// WebView, content::WebContentsDelegate implementation:

void WebView::WebContentsFocused(content::WebContents* web_contents) {
  DCHECK(wc_owner_.get());
  // The WebView is only the delegate of WebContentses it creates itself.
  OnWebContentsFocused(wc_owner_.get());
}

bool WebView::EmbedsFullscreenWidget() const {
  DCHECK(wc_owner_.get());
  return embed_fullscreen_widget_mode_enabled_;
}

////////////////////////////////////////////////////////////////////////////////
// WebView, content::WebContentsObserver implementation:

void WebView::RenderViewDeleted(content::RenderViewHost* render_view_host) {
  NotifyMaybeTextInputClientChanged();
}

void WebView::RenderProcessGone(base::TerminationStatus status) {
  NotifyMaybeTextInputClientChanged();
}

void WebView::RenderViewHostChanged(content::RenderViewHost* old_host,
                                    content::RenderViewHost* new_host) {
  FocusManager* const focus_manager = GetFocusManager();
  if (focus_manager && focus_manager->GetFocusedView() == this)
    OnFocus();
  NotifyMaybeTextInputClientChanged();
}

void WebView::DidShowFullscreenWidget(int routing_id) {
  if (embed_fullscreen_widget_mode_enabled_)
    ReattachForFullscreenChange(true);
}

void WebView::DidDestroyFullscreenWidget(int routing_id) {
  if (embed_fullscreen_widget_mode_enabled_)
    ReattachForFullscreenChange(false);
}

void WebView::DidToggleFullscreenModeForTab(bool entered_fullscreen) {
  if (embed_fullscreen_widget_mode_enabled_)
    ReattachForFullscreenChange(entered_fullscreen);
}

void WebView::DidAttachInterstitialPage() {
  NotifyMaybeTextInputClientChanged();
}

void WebView::DidDetachInterstitialPage() {
  NotifyMaybeTextInputClientChanged();
}

////////////////////////////////////////////////////////////////////////////////
// WebView, private:

void WebView::AttachWebContents() {
  // Prevents attachment if the WebView isn't already in a Widget, or it's
  // already attached.
  if (!GetWidget() || !web_contents())
    return;

  const gfx::NativeView view_to_attach = is_embedding_fullscreen_widget_ ?
      web_contents()->GetFullscreenRenderWidgetHostView()->GetNativeView() :
      web_contents()->GetNativeView();
  OnBoundsChanged(bounds());
  if (holder_->native_view() == view_to_attach)
    return;

  holder_->Attach(view_to_attach);

  // The view will not be focused automatically when it is attached, so we need
  // to pass on focus to it if the FocusManager thinks the view is focused. Note
  // that not every Widget has a focus manager.
  FocusManager* const focus_manager = GetFocusManager();
  if (focus_manager && focus_manager->GetFocusedView() == this)
    OnFocus();

#if defined(OS_WIN)
  if (!is_embedding_fullscreen_widget_) {
    web_contents()->SetParentNativeViewAccessible(
        parent()->GetNativeViewAccessible());
  }
#endif
}

void WebView::DetachWebContents() {
  if (web_contents()) {
    holder_->Detach();
#if defined(OS_WIN)
    if (!is_embedding_fullscreen_widget_)
      web_contents()->SetParentNativeViewAccessible(NULL);
#endif
  }
}

void WebView::ReattachForFullscreenChange(bool enter_fullscreen) {
  DCHECK(embed_fullscreen_widget_mode_enabled_);
  const bool web_contents_has_separate_fs_widget =
      web_contents() && web_contents()->GetFullscreenRenderWidgetHostView();
  if (is_embedding_fullscreen_widget_ || web_contents_has_separate_fs_widget) {
    // Shutting down or starting up the embedding of the separate fullscreen
    // widget.  Need to detach and re-attach to a different native view.
    DetachWebContents();
    is_embedding_fullscreen_widget_ =
        enter_fullscreen && web_contents_has_separate_fs_widget;
    AttachWebContents();
  } else {
    // Entering or exiting "non-Flash" fullscreen mode, where the native view is
    // the same.  So, do not change attachment.
    OnBoundsChanged(bounds());
  }
  NotifyMaybeTextInputClientChanged();
}

void WebView::NotifyMaybeTextInputClientChanged() {
  // Update the TextInputClient as needed; see GetTextInputClient().
  FocusManager* const focus_manager = GetFocusManager();
  if (focus_manager)
    focus_manager->OnTextInputClientChanged(this);
}

content::WebContents* WebView::CreateWebContents(
      content::BrowserContext* browser_context) {
  content::WebContents* contents = NULL;
  if (ViewsDelegate::views_delegate) {
    contents = ViewsDelegate::views_delegate->CreateWebContents(
        browser_context, NULL);
  }

  if (!contents) {
    content::WebContents::CreateParams create_params(
        browser_context, NULL);
    return content::WebContents::Create(create_params);
  }

  return contents;
}

}  // namespace views
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/
#include "MultiDContactConstraint.h"

#include "SystemBase.h"
#include "PenetrationLocator.h"

// libMesh includes
#include "string_to_enum.h"

template<>
InputParameters validParams<MultiDContactConstraint>()
{
  InputParameters params = validParams<NodeFaceConstraint>();
  params.set<bool>("use_displaced_mesh") = true;
  params.addParam<bool>("jacobian_update", false, "Whether or not to update the 'in contact' list every jacobian evaluation (by default it will happen once per timestep");

  params.addRequiredParam<unsigned int>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");
  params.addCoupledVar("disp_x", "The x displacement");
  params.addCoupledVar("disp_y", "The y displacement");
  params.addCoupledVar("disp_z", "The z displacement");
  params.addParam<std::string>("model", "frictionless", "The contact model to use");
  params.addParam<Real>("penalty", 1e8, "The penalty to apply.  This can vary depending on the stiffness of your materials");

  // TODO: Reenable this
//  params.addParam<std::string>("order", "FIRST", "The finite element order");

  return params;
}

MultiDContactConstraint::MultiDContactConstraint(const std::string & name, InputParameters parameters) :
    NodeFaceConstraint(name, parameters),
    _residual_copy(_sys.residualGhosted()),
    _jacobian_update(getParam<bool>("jacobian_update")),
    _component(getParam<unsigned int>("component")),
    _model(contactModel(getParam<std::string>("model"))),
    _penalty(getParam<Real>("penalty")),
    _x_var(isCoupled("disp_x") ? coupled("disp_x") : 99999),
    _y_var(isCoupled("disp_y") ? coupled("disp_y") : 99999),
    _z_var(isCoupled("disp_z") ? coupled("disp_z") : 99999),
    _vars(_x_var, _y_var, _z_var)
{
  _overwrite_slave_residual = false;
}

void
MultiDContactConstraint::timestepSetup()
{
  updateContactSet();
}

void
MultiDContactConstraint::jacobianSetup()
{
  updateContactSet();
}

void
MultiDContactConstraint::updateContactSet()
{
  std::map<unsigned int, bool> & has_penetrated = _penetration_locator._has_penetrated;

  std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator it = _penetration_locator._penetration_info.begin();
  std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator end = _penetration_locator._penetration_info.end();

  for (; it!=end; ++it)
  {
    PenetrationLocator::PenetrationInfo * pinfo = it->second;

    if (!pinfo)
    {
      continue;
    }

    if (pinfo->_distance > 0)
    {
      unsigned int slave_node_num = it->first;
      has_penetrated[slave_node_num] = true;
    }
  }
}

bool
MultiDContactConstraint::shouldApply()
{
  return _penetration_locator._has_penetrated[_current_node->id()];
}

Real
MultiDContactConstraint::computeQpSlaveValue()
{
  PenetrationLocator::PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
  std::cerr<<std::endl
           <<"Popping out node: "<<_current_node->id()<<std::endl
           <<"Closest Point "<<_component<<": "<<pinfo->_closest_point(_component)<<std::endl
           <<"Current Node "<<_component<<": "<<(*_current_node)(_component)<<std::endl
           <<"Current Value: "<<_u_slave[_qp]<<std::endl
           <<"New Value: "<<pinfo->_closest_point(_component) - ((*_current_node)(_component) - _u_slave[_qp])<<std::endl
           <<"Change: "<<_u_slave[_qp] - (pinfo->_closest_point(_component) - ((*_current_node)(_component) - _u_slave[_qp]))<<std::endl<<std::endl;

  return pinfo->_closest_point(_component) - ((*_current_node)(_component) - _u_slave[_qp]);
}

Real
MultiDContactConstraint::computeQpResidual(Moose::ConstraintType type)
{
  PenetrationLocator::PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
  const Node * node = pinfo->_node;

  RealVectorValue res_vec;
  // Build up residual vector
  for(unsigned int i=0; i<_dim; ++i)
  {
    int dof_number = node->dof_number(0, _vars(i), 0);
    res_vec(i) = _residual_copy(dof_number);
  }

  const RealVectorValue distance_vec(_mesh.node(node->id()) - pinfo->_closest_point);
  const RealVectorValue pen_force(_penalty * distance_vec);
  Real resid = 0;

  switch(type)
  {
  case Moose::Slave:
    switch(_model)
    {
    case CM_FRICTIONLESS:

      resid = pinfo->_normal(_component) * (pinfo->_normal * ( pen_force - res_vec ));
      break;

    case CM_GLUED:
    case CM_TIED:

      resid = pen_force(_component)
        - res_vec(_component)
        ;

      break;

    default:
      mooseError("Invalid or unavailable contact model");
    }
    return _test_slave[_i][_qp] * resid;
  case Moose::Master:
    switch(_model)
    {
    case CM_FRICTIONLESS:

      resid = pinfo->_normal(_component) * (pinfo->_normal * res_vec);
      break;

    case CM_GLUED:
    case CM_TIED:
      resid = res_vec(_component);
      break;

    default:
      mooseError("Invalid or unavailable contact model");
    }
    return _test_master[_i][_qp] * resid;
  }
  return 0;
}

Real
MultiDContactConstraint::computeQpJacobian(Moose::ConstraintJacobianType type)
{
  PenetrationLocator::PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
  //const Node * node = pinfo->_node;

  if(_name != "contact_x")
    return 0;

  double slave_jac = 0;
  switch(type)
  {
  case Moose::SlaveSlave:
    switch(_model)
    {
    case CM_FRICTIONLESS:

      slave_jac = pinfo->_normal(_component) * pinfo->_normal(_component) * ( _penalty*_phi_slave[_j][_qp] - (*_jacobian)(_current_node->dof_number(0, _var.number(), 0), _connected_dof_indices[_j]) );
      break;

    case CM_GLUED:
    case CM_TIED:
/*
      resid = pen_force(_component)
        - res_vec(_component)
        ;
*/
      break;

    default:
      mooseError("Invalid or unavailable contact model");
    }
    return _test_slave[_i][_qp] * slave_jac;
  case Moose::SlaveMaster:
    switch(_model)
    {
    case CM_FRICTIONLESS:

      slave_jac = pinfo->_normal(_component) * pinfo->_normal(_component) * ( -_penalty*_phi_master[_j][_qp] );
      break;

    case CM_GLUED:
    case CM_TIED:
/*
      resid = pen_force(_component)
        - res_vec(_component)
        ;
*/
      break;

    default:
      mooseError("Invalid or unavailable contact model");
    }
    return _test_slave[_i][_qp] * slave_jac;

//    return -_phi_master[_j][_qp]*_test_slave[_i][_qp];
  case Moose::MasterSlave:
    slave_jac = (*_jacobian)(_current_node->dof_number(0, _var.number(), 0), _connected_dof_indices[_j]);
    return slave_jac*_test_master[_i][_qp];
  case Moose::MasterMaster:
    return 0;
  }
  return 0;
}
<commit_msg>more work toward the new contact system #716<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/
#include "MultiDContactConstraint.h"

#include "SystemBase.h"
#include "PenetrationLocator.h"

// libMesh includes
#include "string_to_enum.h"

template<>
InputParameters validParams<MultiDContactConstraint>()
{
  InputParameters params = validParams<NodeFaceConstraint>();
  params.set<bool>("use_displaced_mesh") = true;
  params.addParam<bool>("jacobian_update", false, "Whether or not to update the 'in contact' list every jacobian evaluation (by default it will happen once per timestep");

  params.addRequiredParam<unsigned int>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");
  params.addCoupledVar("disp_x", "The x displacement");
  params.addCoupledVar("disp_y", "The y displacement");
  params.addCoupledVar("disp_z", "The z displacement");
  params.addParam<std::string>("model", "frictionless", "The contact model to use");
  params.addParam<Real>("penalty", 1e8, "The penalty to apply.  This can vary depending on the stiffness of your materials");

  // TODO: Reenable this
//  params.addParam<std::string>("order", "FIRST", "The finite element order");

  return params;
}

MultiDContactConstraint::MultiDContactConstraint(const std::string & name, InputParameters parameters) :
    NodeFaceConstraint(name, parameters),
    _residual_copy(_sys.residualGhosted()),
    _jacobian_update(getParam<bool>("jacobian_update")),
    _component(getParam<unsigned int>("component")),
    _model(contactModel(getParam<std::string>("model"))),
    _penalty(getParam<Real>("penalty")),
    _x_var(isCoupled("disp_x") ? coupled("disp_x") : 99999),
    _y_var(isCoupled("disp_y") ? coupled("disp_y") : 99999),
    _z_var(isCoupled("disp_z") ? coupled("disp_z") : 99999),
    _vars(_x_var, _y_var, _z_var)
{
  _overwrite_slave_residual = false;
}

void
MultiDContactConstraint::timestepSetup()
{
  if(_component == 0)
  {
    _penetration_locator._unlocked_this_step.clear();
    _penetration_locator._locked_this_step.clear();
    updateContactSet();
  }
}

void
MultiDContactConstraint::jacobianSetup()
{
  if(_component == 0)
    updateContactSet();
}

void
MultiDContactConstraint::updateContactSet()
{
  std::map<unsigned int, bool> & has_penetrated = _penetration_locator._has_penetrated;
  std::map<unsigned int, bool> & unlocked_this_step = _penetration_locator._unlocked_this_step;
  std::map<unsigned int, bool> & locked_this_step = _penetration_locator._unlocked_this_step;

  std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator it = _penetration_locator._penetration_info.begin();
  std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator end = _penetration_locator._penetration_info.end();

  for (; it!=end; ++it)
  {
    PenetrationLocator::PenetrationInfo * pinfo = it->second;
    const Node * node = pinfo->_node;

    if (!pinfo)
    {
      continue;
    }

    unsigned int slave_node_num = it->first;

    RealVectorValue res_vec;
    // Build up residual vector
    for(unsigned int i=0; i<_dim; ++i)
    {
      int dof_number = node->dof_number(0, _vars(i), 0);
      res_vec(i) = _residual_copy(dof_number);
    }

    Real resid = 0;
    switch(_model)
    {
    case CM_FRICTIONLESS:

      resid = pinfo->_normal * res_vec;
      break;

    case CM_GLUED:
    case CM_TIED:

      resid = pinfo->_normal * res_vec;
      break;

    default:
      mooseError("Invalid or unavailable contact model");
    }

//    if(has_penetrated[slave_node_num] && resid < 0)
//      std::cerr<<resid<<std::endl;
/*
    if(has_penetrated[slave_node_num] == true && resid < -.15)
    {
      std::cerr<<std::endl<<"Unlocking node "<<node->id()<<" because resid: "<<resid<<std::endl<<std::endl;

      has_penetrated[slave_node_num] = false;
      unlocked_this_step[slave_node_num] = true;
    }
    else*/
    if (pinfo->_distance > 0 && !has_penetrated[slave_node_num])// && !unlocked_this_step[slave_node_num])
    {
//      std::cerr<<std::endl<<"Locking node "<<node->id()<<" because distance: "<<pinfo->_distance<<std::endl<<std::endl;
//      libMesh::print_trace();

      has_penetrated[slave_node_num] = true;
      locked_this_step[slave_node_num] = true;
    }
  }
}

bool
MultiDContactConstraint::shouldApply()
{
  return _penetration_locator._has_penetrated[_current_node->id()];
}

Real
MultiDContactConstraint::computeQpSlaveValue()
{
//  if(_name != "contact_x")
//    return _u_slave[_qp];

  PenetrationLocator::PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
/*
  std::cerr<<std::endl
           <<"Popping out node: "<<_current_node->id()<<std::endl
           <<"Closest Point "<<_component<<": "<<pinfo->_closest_point(_component)<<std::endl
           <<"Current Node "<<_component<<": "<<(*_current_node)(_component)<<std::endl
           <<"Current Value: "<<_u_slave[_qp]<<std::endl
           <<"New Value: "<<pinfo->_closest_point(_component) - ((*_current_node)(_component) - _u_slave[_qp])<<std::endl
           <<"Change: "<<_u_slave[_qp] - (pinfo->_closest_point(_component) - ((*_current_node)(_component) - _u_slave[_qp]))<<std::endl<<std::endl;
*/
  return  pinfo->_closest_point(_component) - ((*_current_node)(_component) - _u_slave[_qp]);
}

Real
MultiDContactConstraint::computeQpResidual(Moose::ConstraintType type)
{
  PenetrationLocator::PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
  const Node * node = pinfo->_node;

  RealVectorValue res_vec;
  // Build up residual vector
  for(unsigned int i=0; i<_dim; ++i)
  {
    int dof_number = node->dof_number(0, _vars(i), 0);
    res_vec(i) = _residual_copy(dof_number);
  }

  const RealVectorValue distance_vec(_mesh.node(node->id()) - pinfo->_closest_point);
  const RealVectorValue pen_force(_penalty * distance_vec);
  Real resid = 0;

  switch(type)
  {
  case Moose::Slave:
    switch(_model)
    {
    case CM_FRICTIONLESS:

      resid = pinfo->_normal(_component) * (pinfo->_normal * ( pen_force - res_vec ));
      break;

    case CM_GLUED:
    case CM_TIED:

      resid = pen_force(_component)
        - res_vec(_component)
        ;

      break;

    default:
      mooseError("Invalid or unavailable contact model");
    }
    return _test_slave[_i][_qp] * resid;
  case Moose::Master:
    switch(_model)
    {
    case CM_FRICTIONLESS:

      resid = pinfo->_normal(_component) * (pinfo->_normal * res_vec);
      break;

    case CM_GLUED:
    case CM_TIED:
      resid = res_vec(_component);
      break;

    default:
      mooseError("Invalid or unavailable contact model");
    }
    return _test_master[_i][_qp] * resid;
  }
  return 0;
}

Real
MultiDContactConstraint::computeQpJacobian(Moose::ConstraintJacobianType type)
{
  PenetrationLocator::PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
  //const Node * node = pinfo->_node;

//  if(_name != "contact_x")
//    return 0;

  double slave_jac = 0;
  switch(type)
  {
  case Moose::SlaveSlave:
    switch(_model)
    {
    case CM_FRICTIONLESS:

      slave_jac = pinfo->_normal(_component) * pinfo->_normal(_component) * ( _penalty*_phi_slave[_j][_qp] - (*_jacobian)(_current_node->dof_number(0, _var.number(), 0), _connected_dof_indices[_j]) );
      break;

    case CM_GLUED:
    case CM_TIED:
/*
      resid = pen_force(_component)
        - res_vec(_component)
        ;
*/
      break;

    default:
      mooseError("Invalid or unavailable contact model");
    }
    return _test_slave[_i][_qp] * slave_jac;
  case Moose::SlaveMaster:
    switch(_model)
    {
    case CM_FRICTIONLESS:

      slave_jac = pinfo->_normal(_component) * pinfo->_normal(_component) * ( -_penalty*_phi_master[_j][_qp] );
      break;

    case CM_GLUED:
    case CM_TIED:
/*
      resid = pen_force(_component)
        - res_vec(_component)
        ;
*/
      break;

    default:
      mooseError("Invalid or unavailable contact model");
    }
    return _test_slave[_i][_qp] * slave_jac;

//    return -_phi_master[_j][_qp]*_test_slave[_i][_qp];
  case Moose::MasterSlave:
    slave_jac = (*_jacobian)(_current_node->dof_number(0, _var.number(), 0), _connected_dof_indices[_j]);
    return slave_jac*_test_master[_i][_qp];
  case Moose::MasterMaster:
    return 0;
  }
  return 0;
}
<|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 "ui/views/examples/examples_main.h"

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/process_util.h"
#include "base/stl_util.h"
#include "base/utf_string_conversions.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/models/combobox_model.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/examples/bubble_example.h"
#include "ui/views/examples/button_example.h"
#include "ui/views/examples/combobox_example.h"
#include "ui/views/examples/double_split_view_example.h"
#include "ui/views/examples/link_example.h"
#include "ui/views/examples/message_box_example.h"
#include "ui/views/examples/native_theme_button_example.h"
#include "ui/views/examples/native_theme_checkbox_example.h"
#include "ui/views/examples/progress_bar_example.h"
#include "ui/views/examples/radio_button_example.h"
#include "ui/views/examples/scroll_view_example.h"
#include "ui/views/examples/single_split_view_example.h"
#include "ui/views/examples/tabbed_pane_example.h"
#include "ui/views/examples/table_example.h"
#include "ui/views/examples/text_example.h"
#include "ui/views/examples/textfield_example.h"
#include "ui/views/examples/throbber_example.h"
#include "ui/views/examples/tree_view_example.h"
#include "ui/views/examples/widget_example.h"
#include "ui/views/focus/accelerator_handler.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/widget/widget.h"

#if !defined(USE_AURA)
#include "ui/views/examples/menu_example.h"
#endif

namespace views {
namespace examples {

class ExampleBase;

// Model for the examples that are being added via AddExample()
class ComboboxModelExampleList : public ui::ComboboxModel {
 public:
  ComboboxModelExampleList() {}
  virtual ~ComboboxModelExampleList() {}

  // Overridden from ui::ComboboxModel:
  virtual int GetItemCount() OVERRIDE { return example_list.size(); }
  virtual string16 GetItemAt(int index) OVERRIDE {
    return UTF8ToUTF16(example_list[index]->example_title());
  }

  views::View* GetItemViewAt(int index) {
    return example_list[index]->example_view();
  }

  void AddExample(ExampleBase* example) {
    example_list.push_back(example);
  }

 private:
  std::vector<ExampleBase*> example_list;

  DISALLOW_COPY_AND_ASSIGN(ComboboxModelExampleList);
};

class ExamplesWindowContents : public views::WidgetDelegateView,
                               public views::ComboboxListener {
 public:
  explicit ExamplesWindowContents(bool quit_on_close)
      : combobox_model_(new ComboboxModelExampleList),
        combobox_(new views::Combobox(combobox_model_)),
        example_shown_(new views::View),
        status_label_(new views::Label),
        quit_on_close_(quit_on_close) {
    instance_ = this;
    combobox_->set_listener(this);
  }
  virtual ~ExamplesWindowContents() {
    delete combobox_model_;
  }

  // Prints a message in the status area, at the bottom of the window.
  void SetStatus(const std::string& status) {
    status_label_->SetText(UTF8ToUTF16(status));
  }

  static ExamplesWindowContents* instance() { return instance_; }

 private:
  // Overridden from WidgetDelegateView:
  virtual bool CanResize() const OVERRIDE { return true; }
  virtual bool CanMaximize() const OVERRIDE { return true; }
  virtual string16 GetWindowTitle() const OVERRIDE {
    return ASCIIToUTF16("Views Examples");
  }
  virtual views::View* GetContentsView() OVERRIDE { return this; }
  virtual void WindowClosing() OVERRIDE {
    instance_ = NULL;
    if (quit_on_close_)
      MessageLoopForUI::current()->Quit();
  }

  // Overridden from View:
  virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child) {
    if (is_add && child == this)
      InitExamplesWindow();
  }

  // Overridden from ComboboxListener:
  virtual void ItemChanged(Combobox* combo_box,
                           int prev_index,
                           int new_index) OVERRIDE {
    DCHECK(combo_box && combo_box == combobox_);
    DCHECK(new_index < combobox_model_->GetItemCount());
    example_shown_->RemoveAllChildViews(false);
    example_shown_->AddChildView(combobox_model_->GetItemViewAt(new_index));
    example_shown_->RequestFocus();
    Layout();
  }

  // Creates the layout within the examples window.
  void InitExamplesWindow() {
    AddExamples();

    set_background(views::Background::CreateStandardPanelBackground());
    views::GridLayout* layout = new views::GridLayout(this);
    SetLayoutManager(layout);
    views::ColumnSet* column_set = layout->AddColumnSet(0);
    column_set->AddPaddingColumn(0, 5);
    column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
                          views::GridLayout::USE_PREF, 0, 0);
    column_set->AddPaddingColumn(0, 5);
    layout->AddPaddingRow(0, 5);
    layout->StartRow(0 /* no expand */, 0);
    layout->AddView(combobox_);

    if (combobox_model_->GetItemCount() > 0) {
      layout->StartRow(1, 0);
      example_shown_->SetLayoutManager(new views::FillLayout());
      example_shown_->AddChildView(combobox_model_->GetItemViewAt(0));
      layout->AddView(example_shown_);
    }

    layout->StartRow(0 /* no expand */, 0);
    layout->AddView(status_label_);
    layout->AddPaddingRow(0, 5);
  }

  // Adds all the individual examples to the combobox model.
  void AddExamples() {
    combobox_model_->AddExample(new TreeViewExample);
    combobox_model_->AddExample(new TableExample);
    combobox_model_->AddExample(new BubbleExample);
    combobox_model_->AddExample(new ButtonExample);
    combobox_model_->AddExample(new ComboboxExample);
    combobox_model_->AddExample(new DoubleSplitViewExample);
    combobox_model_->AddExample(new LinkExample);
#if !defined(USE_AURA)
    combobox_model_->AddExample(new MenuExample);
#endif
    combobox_model_->AddExample(new MessageBoxExample);
    combobox_model_->AddExample(new NativeThemeButtonExample);
    combobox_model_->AddExample(new NativeThemeCheckboxExample);
    combobox_model_->AddExample(new ProgressBarExample);
    combobox_model_->AddExample(new RadioButtonExample);
    combobox_model_->AddExample(new ScrollViewExample);
    combobox_model_->AddExample(new SingleSplitViewExample);
    combobox_model_->AddExample(new TabbedPaneExample);
    combobox_model_->AddExample(new TextExample);
    combobox_model_->AddExample(new TextfieldExample);
    combobox_model_->AddExample(new ThrobberExample);
    combobox_model_->AddExample(new WidgetExample);
  }

  static ExamplesWindowContents* instance_;
  ComboboxModelExampleList* combobox_model_;
  views::Combobox* combobox_;
  views::View* example_shown_;
  views::Label* status_label_;
  bool quit_on_close_;

  DISALLOW_COPY_AND_ASSIGN(ExamplesWindowContents);
};

// static
ExamplesWindowContents* ExamplesWindowContents::instance_ = NULL;

void ShowExamplesWindow(bool quit_on_close) {
  if (ExamplesWindowContents::instance()) {
    ExamplesWindowContents::instance()->GetWidget()->Activate();
  } else {
    Widget::CreateWindowWithBounds(new ExamplesWindowContents(quit_on_close),
                                   gfx::Rect(0, 0, 850, 300))->Show();
  }
}

void LogStatus(const std::string& string) {
  ExamplesWindowContents::instance()->SetStatus(string);
}

}  // namespace examples
}  // namespace views
<commit_msg>views: Include examples_window.h in its source file instead of examples_main.h.<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 "ui/views/examples/examples_window.h"

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/process_util.h"
#include "base/stl_util.h"
#include "base/utf_string_conversions.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/models/combobox_model.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/examples/bubble_example.h"
#include "ui/views/examples/button_example.h"
#include "ui/views/examples/combobox_example.h"
#include "ui/views/examples/double_split_view_example.h"
#include "ui/views/examples/link_example.h"
#include "ui/views/examples/message_box_example.h"
#include "ui/views/examples/native_theme_button_example.h"
#include "ui/views/examples/native_theme_checkbox_example.h"
#include "ui/views/examples/progress_bar_example.h"
#include "ui/views/examples/radio_button_example.h"
#include "ui/views/examples/scroll_view_example.h"
#include "ui/views/examples/single_split_view_example.h"
#include "ui/views/examples/tabbed_pane_example.h"
#include "ui/views/examples/table_example.h"
#include "ui/views/examples/text_example.h"
#include "ui/views/examples/textfield_example.h"
#include "ui/views/examples/throbber_example.h"
#include "ui/views/examples/tree_view_example.h"
#include "ui/views/examples/widget_example.h"
#include "ui/views/focus/accelerator_handler.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"

#if !defined(USE_AURA)
#include "ui/views/examples/menu_example.h"
#endif

namespace views {
namespace examples {

class ExampleBase;

// Model for the examples that are being added via AddExample()
class ComboboxModelExampleList : public ui::ComboboxModel {
 public:
  ComboboxModelExampleList() {}
  virtual ~ComboboxModelExampleList() {}

  // Overridden from ui::ComboboxModel:
  virtual int GetItemCount() OVERRIDE { return example_list.size(); }
  virtual string16 GetItemAt(int index) OVERRIDE {
    return UTF8ToUTF16(example_list[index]->example_title());
  }

  views::View* GetItemViewAt(int index) {
    return example_list[index]->example_view();
  }

  void AddExample(ExampleBase* example) {
    example_list.push_back(example);
  }

 private:
  std::vector<ExampleBase*> example_list;

  DISALLOW_COPY_AND_ASSIGN(ComboboxModelExampleList);
};

class ExamplesWindowContents : public views::WidgetDelegateView,
                               public views::ComboboxListener {
 public:
  explicit ExamplesWindowContents(bool quit_on_close)
      : combobox_model_(new ComboboxModelExampleList),
        combobox_(new views::Combobox(combobox_model_)),
        example_shown_(new views::View),
        status_label_(new views::Label),
        quit_on_close_(quit_on_close) {
    instance_ = this;
    combobox_->set_listener(this);
  }
  virtual ~ExamplesWindowContents() {
    delete combobox_model_;
  }

  // Prints a message in the status area, at the bottom of the window.
  void SetStatus(const std::string& status) {
    status_label_->SetText(UTF8ToUTF16(status));
  }

  static ExamplesWindowContents* instance() { return instance_; }

 private:
  // Overridden from WidgetDelegateView:
  virtual bool CanResize() const OVERRIDE { return true; }
  virtual bool CanMaximize() const OVERRIDE { return true; }
  virtual string16 GetWindowTitle() const OVERRIDE {
    return ASCIIToUTF16("Views Examples");
  }
  virtual views::View* GetContentsView() OVERRIDE { return this; }
  virtual void WindowClosing() OVERRIDE {
    instance_ = NULL;
    if (quit_on_close_)
      MessageLoopForUI::current()->Quit();
  }

  // Overridden from View:
  virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child) {
    if (is_add && child == this)
      InitExamplesWindow();
  }

  // Overridden from ComboboxListener:
  virtual void ItemChanged(Combobox* combo_box,
                           int prev_index,
                           int new_index) OVERRIDE {
    DCHECK(combo_box && combo_box == combobox_);
    DCHECK(new_index < combobox_model_->GetItemCount());
    example_shown_->RemoveAllChildViews(false);
    example_shown_->AddChildView(combobox_model_->GetItemViewAt(new_index));
    example_shown_->RequestFocus();
    Layout();
  }

  // Creates the layout within the examples window.
  void InitExamplesWindow() {
    AddExamples();

    set_background(views::Background::CreateStandardPanelBackground());
    views::GridLayout* layout = new views::GridLayout(this);
    SetLayoutManager(layout);
    views::ColumnSet* column_set = layout->AddColumnSet(0);
    column_set->AddPaddingColumn(0, 5);
    column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
                          views::GridLayout::USE_PREF, 0, 0);
    column_set->AddPaddingColumn(0, 5);
    layout->AddPaddingRow(0, 5);
    layout->StartRow(0 /* no expand */, 0);
    layout->AddView(combobox_);

    if (combobox_model_->GetItemCount() > 0) {
      layout->StartRow(1, 0);
      example_shown_->SetLayoutManager(new views::FillLayout());
      example_shown_->AddChildView(combobox_model_->GetItemViewAt(0));
      layout->AddView(example_shown_);
    }

    layout->StartRow(0 /* no expand */, 0);
    layout->AddView(status_label_);
    layout->AddPaddingRow(0, 5);
  }

  // Adds all the individual examples to the combobox model.
  void AddExamples() {
    combobox_model_->AddExample(new TreeViewExample);
    combobox_model_->AddExample(new TableExample);
    combobox_model_->AddExample(new BubbleExample);
    combobox_model_->AddExample(new ButtonExample);
    combobox_model_->AddExample(new ComboboxExample);
    combobox_model_->AddExample(new DoubleSplitViewExample);
    combobox_model_->AddExample(new LinkExample);
#if !defined(USE_AURA)
    combobox_model_->AddExample(new MenuExample);
#endif
    combobox_model_->AddExample(new MessageBoxExample);
    combobox_model_->AddExample(new NativeThemeButtonExample);
    combobox_model_->AddExample(new NativeThemeCheckboxExample);
    combobox_model_->AddExample(new ProgressBarExample);
    combobox_model_->AddExample(new RadioButtonExample);
    combobox_model_->AddExample(new ScrollViewExample);
    combobox_model_->AddExample(new SingleSplitViewExample);
    combobox_model_->AddExample(new TabbedPaneExample);
    combobox_model_->AddExample(new TextExample);
    combobox_model_->AddExample(new TextfieldExample);
    combobox_model_->AddExample(new ThrobberExample);
    combobox_model_->AddExample(new WidgetExample);
  }

  static ExamplesWindowContents* instance_;
  ComboboxModelExampleList* combobox_model_;
  views::Combobox* combobox_;
  views::View* example_shown_;
  views::Label* status_label_;
  bool quit_on_close_;

  DISALLOW_COPY_AND_ASSIGN(ExamplesWindowContents);
};

// static
ExamplesWindowContents* ExamplesWindowContents::instance_ = NULL;

void ShowExamplesWindow(bool quit_on_close) {
  if (ExamplesWindowContents::instance()) {
    ExamplesWindowContents::instance()->GetWidget()->Activate();
  } else {
    Widget::CreateWindowWithBounds(new ExamplesWindowContents(quit_on_close),
                                   gfx::Rect(0, 0, 850, 300))->Show();
  }
}

void LogStatus(const std::string& string) {
  ExamplesWindowContents::instance()->SetStatus(string);
}

}  // namespace examples
}  // namespace views
<|endoftext|>