<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// 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 "QOSPRayWindow.h"
#include "modules/opengl/util.h"

#ifdef __APPLE__
  #include <OpenGL/glu.h>
#else
  #include <GL/glu.h>
#endif

std::ostream &operator<<(std::ostream &o, const Viewport &viewport)
{
  o <<  "-vp " << viewport.from.x << " " << viewport.from.y << " " << viewport.from.z
    << " -vi " << viewport.at.x   << " " << viewport.at.y   << " " << viewport.at.z
    << " -vu " << viewport.up.x   << " " << viewport.up.y   << " " << viewport.up.z
    << std::endl;

  return o;
}

QOSPRayWindow::QOSPRayWindow(QMainWindow *parent,
                             OSPRenderer renderer,
                             bool showFrameRate,
                             std::string writeFramesFilename)
  : parent(parent),
    showFrameRate(showFrameRate),
    frameCount(0),
    renderingEnabled(false),
    rotationRate(0.f),
    benchmarkWarmUpFrames(0),
    benchmarkFrames(0),
    frameBuffer(NULL),
    renderer(NULL),
    camera(NULL),
    maxDepthTexture(NULL),
    writeFramesFilename(writeFramesFilename)
{
  // assign renderer
  if(!renderer)
    throw std::runtime_error("QOSPRayWindow: must be constructed with an existing renderer");

  this->renderer = renderer;

  // setup camera
  camera = ospNewCamera("perspective");

  if(!camera)
    throw std::runtime_error("QOSPRayWindow: could not create camera type 'perspective'");

  ospCommit(camera);

  ospSetObject(renderer, "camera", camera);

  // connect signals and slots
  connect(&renderTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
  connect(&renderRestartTimer, SIGNAL(timeout()), &renderTimer, SLOT(start()));
}

QOSPRayWindow::~QOSPRayWindow()
{
  // free the frame buffer and camera
  // we don't own the renderer!
  if(frameBuffer)
    ospFreeFrameBuffer(frameBuffer);

  if(camera)
    ospRelease(camera);
}

void QOSPRayWindow::setRenderingEnabled(bool renderingEnabled)
{
  this->renderingEnabled = renderingEnabled;

  // trigger render if true
  if(renderingEnabled == true)
    renderTimer.start();
  else
    renderTimer.stop();
}

void QOSPRayWindow::setRotationRate(float rotationRate)
{
  this->rotationRate = rotationRate;
}

void QOSPRayWindow::setBenchmarkParameters(int benchmarkWarmUpFrames, int benchmarkFrames)
{
  this->benchmarkWarmUpFrames = benchmarkWarmUpFrames;
  this->benchmarkFrames = benchmarkFrames;
}

void QOSPRayWindow::setWorldBounds(const ospcommon::box3f &worldBounds)
{
  this->worldBounds = worldBounds;

  // set viewport look at point to center of world bounds
  viewport.at = center(worldBounds);

  // set viewport from point relative to center of world bounds
  viewport.from = viewport.at - 1.5f * length(worldBounds.size()) * viewport.frame.l.vy;

  updateGL();
}

void QOSPRayWindow::paintGL()
{
  if(!renderingEnabled || !frameBuffer || !renderer)
    return;

  // if we're benchmarking and we've completed the required number of warm-up frames, start the timer
  if(benchmarkFrames > 0 && frameCount == benchmarkWarmUpFrames) {
    std::cout << "starting benchmark timer" << std::endl;
    benchmarkTimer.start();
  }

  // update OSPRay camera if viewport has been modified
  if(viewport.modified) {
    const ospcommon::vec3f dir =  viewport.at - viewport.from;
    ospSetVec3f(camera,"pos" ,(const osp::vec3f&)viewport.from);
    ospSetVec3f(camera,"dir" ,(const osp::vec3f&)dir);
    ospSetVec3f(camera,"up", (const osp::vec3f&)viewport.up);
    ospSetf(camera,"aspect", viewport.aspect);
    ospSetf(camera,"fovy", viewport.fovY);

    ospCommit(camera);

    viewport.modified = false;
  }

  renderFrameTimer.start();

  // we have OpenGL components if any slots are connected to the renderGLComponents() signal
  // if so, render these first and then composite the OSPRay-rendered content on top
  bool haveOpenGLComponents = receivers(SIGNAL(renderGLComponents())) > 0;

  if (haveOpenGLComponents) {

    // setup OpenGL view to match current view and render all OpenGL components
    renderGL();

    // generate max depth texture for early ray termination
    if (maxDepthTexture)
      ospRelease(maxDepthTexture);

    maxDepthTexture = ospray::opengl::getOSPDepthTextureFromOpenGLPerspective();
    ospSetObject(renderer, "maxDepthTexture", maxDepthTexture);

    // disable OSPRay background rendering since we're compositing
    ospSet1i(renderer, "backgroundEnabled", 0);

    ospCommit(renderer);

    // disable OpenGL depth testing and enable blending for compositing
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  }
  else {

    // unset any maximum depth texture and enable OSPRay background rendering
    ospSetObject(renderer, "maxDepthTexture", NULL);
    ospSet1i(renderer, "backgroundEnabled", 1);
    ospCommit(renderer);

    // disable OpenGL blending
    glDisable(GL_BLEND);
  }

  ospRenderFrame(frameBuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);
  double framesPerSecond = 1000.0 / renderFrameTimer.elapsed();
  char title[1024];  sprintf(title, "OSPRay Volume Viewer (%.4f fps)", framesPerSecond);
  if (showFrameRate == true) parent->setWindowTitle(title);

  uint32_t *mappedFrameBuffer = (unsigned int *) ospMapFrameBuffer(frameBuffer);

  glDrawPixels(windowSize.x, windowSize.y, GL_RGBA, GL_UNSIGNED_BYTE, mappedFrameBuffer);
  if (writeFramesFilename.length()) writeFrameBufferToFile(mappedFrameBuffer);

  ospUnmapFrameBuffer(mappedFrameBuffer, frameBuffer);

  // automatic rotation
  if(rotationRate != 0.f) {
    resetAccumulationBuffer();
    rotateCenter(rotationRate, 0.f);
  }

  // increment frame counter
  frameCount++;

  // quit if we're benchmarking and have exceeded the needed number of frames
  if(benchmarkFrames > 0 && frameCount >= benchmarkWarmUpFrames + benchmarkFrames) {

    float elapsedSeconds = float(benchmarkTimer.elapsed()) / 1000.f;

    std::cout << "benchmark: " << elapsedSeconds << " elapsed seconds ==> " << float(benchmarkFrames) / elapsedSeconds << " fps" << std::endl;

    QCoreApplication::quit();
  }
}

void QOSPRayWindow::resizeGL(int width, int height)
{
  windowSize = ospcommon::vec2i(width, height);

  // reallocate OSPRay framebuffer for new size
  if(frameBuffer)
    ospFreeFrameBuffer(frameBuffer);

  frameBuffer = ospNewFrameBuffer((const osp::vec2i&)windowSize, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_ACCUM);

  resetAccumulationBuffer();

  // update viewport aspect ratio
  viewport.aspect = float(width) / float(height);
  viewport.modified = true;

  // update OpenGL viewport and force redraw
  glViewport(0, 0, width, height);
  updateGL();
}

void QOSPRayWindow::mousePressEvent(QMouseEvent * event)
{
  lastMousePosition = event->pos();
}

void QOSPRayWindow::mouseReleaseEvent(QMouseEvent * event)
{
  lastMousePosition = event->pos();

  // restart continuous rendering immediately
  renderTimer.start();
}

void QOSPRayWindow::mouseMoveEvent(QMouseEvent * event)
{
  // pause continuous rendering during interaction and cancel any render restart timers.
  // this keeps interaction more responsive (especially with low frame rates).
  renderTimer.stop();
  renderRestartTimer.stop();

  resetAccumulationBuffer();

  int dx = event->x() - lastMousePosition.x();
  int dy = event->y() - lastMousePosition.y();

  if(event->buttons() & Qt::LeftButton) {

    // camera rotation about center point
    const float rotationSpeed = 0.003f;

    float du = dx * rotationSpeed;
    float dv = dy * rotationSpeed;

    rotateCenter(du, dv);
  }
  else if(event->buttons() & Qt::MidButton) {

    // camera strafe of from / at point
    const float strafeSpeed = 0.001f * length(worldBounds.size());

    float du = dx * strafeSpeed;
    float dv = dy * strafeSpeed;

    strafe(du, dv);
  }
  else if(event->buttons() & Qt::RightButton) {

    // camera distance from center point
    const float motionSpeed = 0.012f;

    float forward = dy * motionSpeed * length(worldBounds.size());
    float oldDistance = length(viewport.at - viewport.from);
    float newDistance = oldDistance - forward;

    if(newDistance < 1e-3f)
      return;

    viewport.from = viewport.at - newDistance * viewport.frame.l.vy;
    viewport.frame.p = viewport.from;

    viewport.modified = true;
  }

  lastMousePosition = event->pos();

  updateGL();

  // after a 0.5s delay, restart continuous rendering.
  renderRestartTimer.setSingleShot(true);
  renderRestartTimer.start(500);
}

void QOSPRayWindow::rotateCenter(float du, float dv)
{
  const ospcommon::vec3f pivot = viewport.at;

  ospcommon::affine3f xfm = ospcommon::affine3f::translate(pivot)
    * ospcommon::affine3f::rotate(viewport.frame.l.vx, -dv)
    * ospcommon::affine3f::rotate(viewport.frame.l.vz, -du)
    * ospcommon::affine3f::translate(-pivot);

  viewport.frame = xfm * viewport.frame;
  viewport.from  = xfmPoint(xfm, viewport.from);
  viewport.at    = xfmPoint(xfm, viewport.at);
  viewport.snapUp();

  viewport.modified = true;
}

void QOSPRayWindow::strafe(float du, float dv)
{
  ospcommon::affine3f xfm = ospcommon::affine3f::translate(dv * viewport.frame.l.vz)
    * ospcommon::affine3f::translate(-du * viewport.frame.l.vx);

  viewport.frame = xfm * viewport.frame;
  viewport.from = xfmPoint(xfm, viewport.from);
  viewport.at = xfmPoint(xfm, viewport.at);
  viewport.modified = true;

  viewport.modified = true;
}

void QOSPRayWindow::renderGL()
{
  // setup OpenGL state to match OSPRay view
  const ospcommon::vec3f bgColor = ospcommon::vec3f(1.f);
  glClearColor(bgColor.x, bgColor.y, bgColor.z, 1.f);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  float zNear = 0.1f;
  float zFar = 100000.f;
  gluPerspective(viewport.fovY, viewport.aspect, zNear, zFar);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  gluLookAt(viewport.from.x, viewport.from.y, viewport.from.z,
            viewport.at.x, viewport.at.y, viewport.at.z,
            viewport.up.x, viewport.up.y, viewport.up.z);

  // emit signal to render all OpenGL components; the slots will execute in the order they were registered
  emit(renderGLComponents());
}

void QOSPRayWindow::writeFrameBufferToFile(const uint32_t *pixelData)
{
  static uint32_t frameNumber = 0;
  char filename[1024];
  sprintf(filename, "%s_%05u.ppm", writeFramesFilename.c_str(), frameNumber++);
  FILE *file = fopen(filename, "wb");  if (!file) { std::cerr << "unable to write to file '" << filename << "'" << std::endl;  return; }

  fprintf(file, "P6\n%i %i\n255\n", windowSize.x, windowSize.y);
  unsigned char out[3 * windowSize.x];
  for (int y=0 ; y < windowSize.y ; y++) {
    const unsigned char *in = (const unsigned char *) &pixelData[(windowSize.y - 1 - y) * windowSize.x];
    for (int x=0 ; x < windowSize.x ; x++) {
      out[3 * x + 0] = in[4 * x + 0];
      out[3 * x + 1] = in[4 * x + 1];
      out[3 * x + 2] = in[4 * x + 2];
    }
    fwrite(&out, 3 * windowSize.x, sizeof(char), file);
  }
  fprintf(file, "\n");
  fclose(file);
}
<commit_msg>Fix screenshot view position info to match new argument syntax<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// 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 "QOSPRayWindow.h"
#include "modules/opengl/util.h"

#ifdef __APPLE__
  #include <OpenGL/glu.h>
#else
  #include <GL/glu.h>
#endif

std::ostream &operator<<(std::ostream &o, const Viewport &viewport)
{
  o <<  "--vp " << viewport.from.x << " " << viewport.from.y << " " << viewport.from.z
    << " --vi " << viewport.at.x   << " " << viewport.at.y   << " " << viewport.at.z
    << " --vu " << viewport.up.x   << " " << viewport.up.y   << " " << viewport.up.z
    << std::endl;

  return o;
}

QOSPRayWindow::QOSPRayWindow(QMainWindow *parent,
                             OSPRenderer renderer,
                             bool showFrameRate,
                             std::string writeFramesFilename)
  : parent(parent),
    showFrameRate(showFrameRate),
    frameCount(0),
    renderingEnabled(false),
    rotationRate(0.f),
    benchmarkWarmUpFrames(0),
    benchmarkFrames(0),
    frameBuffer(NULL),
    renderer(NULL),
    camera(NULL),
    maxDepthTexture(NULL),
    writeFramesFilename(writeFramesFilename)
{
  // assign renderer
  if(!renderer)
    throw std::runtime_error("QOSPRayWindow: must be constructed with an existing renderer");

  this->renderer = renderer;

  // setup camera
  camera = ospNewCamera("perspective");

  if(!camera)
    throw std::runtime_error("QOSPRayWindow: could not create camera type 'perspective'");

  ospCommit(camera);

  ospSetObject(renderer, "camera", camera);

  // connect signals and slots
  connect(&renderTimer, SIGNAL(timeout()), this, SLOT(updateGL()));
  connect(&renderRestartTimer, SIGNAL(timeout()), &renderTimer, SLOT(start()));
}

QOSPRayWindow::~QOSPRayWindow()
{
  // free the frame buffer and camera
  // we don't own the renderer!
  if(frameBuffer)
    ospFreeFrameBuffer(frameBuffer);

  if(camera)
    ospRelease(camera);
}

void QOSPRayWindow::setRenderingEnabled(bool renderingEnabled)
{
  this->renderingEnabled = renderingEnabled;

  // trigger render if true
  if(renderingEnabled == true)
    renderTimer.start();
  else
    renderTimer.stop();
}

void QOSPRayWindow::setRotationRate(float rotationRate)
{
  this->rotationRate = rotationRate;
}

void QOSPRayWindow::setBenchmarkParameters(int benchmarkWarmUpFrames, int benchmarkFrames)
{
  this->benchmarkWarmUpFrames = benchmarkWarmUpFrames;
  this->benchmarkFrames = benchmarkFrames;
}

void QOSPRayWindow::setWorldBounds(const ospcommon::box3f &worldBounds)
{
  this->worldBounds = worldBounds;

  // set viewport look at point to center of world bounds
  viewport.at = center(worldBounds);

  // set viewport from point relative to center of world bounds
  viewport.from = viewport.at - 1.5f * length(worldBounds.size()) * viewport.frame.l.vy;

  updateGL();
}

void QOSPRayWindow::paintGL()
{
  if(!renderingEnabled || !frameBuffer || !renderer)
    return;

  // if we're benchmarking and we've completed the required number of warm-up frames, start the timer
  if(benchmarkFrames > 0 && frameCount == benchmarkWarmUpFrames) {
    std::cout << "starting benchmark timer" << std::endl;
    benchmarkTimer.start();
  }

  // update OSPRay camera if viewport has been modified
  if(viewport.modified) {
    const ospcommon::vec3f dir =  viewport.at - viewport.from;
    ospSetVec3f(camera,"pos" ,(const osp::vec3f&)viewport.from);
    ospSetVec3f(camera,"dir" ,(const osp::vec3f&)dir);
    ospSetVec3f(camera,"up", (const osp::vec3f&)viewport.up);
    ospSetf(camera,"aspect", viewport.aspect);
    ospSetf(camera,"fovy", viewport.fovY);

    ospCommit(camera);

    viewport.modified = false;
  }

  renderFrameTimer.start();

  // we have OpenGL components if any slots are connected to the renderGLComponents() signal
  // if so, render these first and then composite the OSPRay-rendered content on top
  bool haveOpenGLComponents = receivers(SIGNAL(renderGLComponents())) > 0;

  if (haveOpenGLComponents) {

    // setup OpenGL view to match current view and render all OpenGL components
    renderGL();

    // generate max depth texture for early ray termination
    if (maxDepthTexture)
      ospRelease(maxDepthTexture);

    maxDepthTexture = ospray::opengl::getOSPDepthTextureFromOpenGLPerspective();
    ospSetObject(renderer, "maxDepthTexture", maxDepthTexture);

    // disable OSPRay background rendering since we're compositing
    ospSet1i(renderer, "backgroundEnabled", 0);

    ospCommit(renderer);

    // disable OpenGL depth testing and enable blending for compositing
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  }
  else {

    // unset any maximum depth texture and enable OSPRay background rendering
    ospSetObject(renderer, "maxDepthTexture", NULL);
    ospSet1i(renderer, "backgroundEnabled", 1);
    ospCommit(renderer);

    // disable OpenGL blending
    glDisable(GL_BLEND);
  }

  ospRenderFrame(frameBuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);
  double framesPerSecond = 1000.0 / renderFrameTimer.elapsed();
  char title[1024];  sprintf(title, "OSPRay Volume Viewer (%.4f fps)", framesPerSecond);
  if (showFrameRate == true) parent->setWindowTitle(title);

  uint32_t *mappedFrameBuffer = (unsigned int *) ospMapFrameBuffer(frameBuffer);

  glDrawPixels(windowSize.x, windowSize.y, GL_RGBA, GL_UNSIGNED_BYTE, mappedFrameBuffer);
  if (writeFramesFilename.length()) writeFrameBufferToFile(mappedFrameBuffer);

  ospUnmapFrameBuffer(mappedFrameBuffer, frameBuffer);

  // automatic rotation
  if(rotationRate != 0.f) {
    resetAccumulationBuffer();
    rotateCenter(rotationRate, 0.f);
  }

  // increment frame counter
  frameCount++;

  // quit if we're benchmarking and have exceeded the needed number of frames
  if(benchmarkFrames > 0 && frameCount >= benchmarkWarmUpFrames + benchmarkFrames) {

    float elapsedSeconds = float(benchmarkTimer.elapsed()) / 1000.f;

    std::cout << "benchmark: " << elapsedSeconds << " elapsed seconds ==> " << float(benchmarkFrames) / elapsedSeconds << " fps" << std::endl;

    QCoreApplication::quit();
  }
}

void QOSPRayWindow::resizeGL(int width, int height)
{
  windowSize = ospcommon::vec2i(width, height);

  // reallocate OSPRay framebuffer for new size
  if(frameBuffer)
    ospFreeFrameBuffer(frameBuffer);

  frameBuffer = ospNewFrameBuffer((const osp::vec2i&)windowSize, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_ACCUM);

  resetAccumulationBuffer();

  // update viewport aspect ratio
  viewport.aspect = float(width) / float(height);
  viewport.modified = true;

  // update OpenGL viewport and force redraw
  glViewport(0, 0, width, height);
  updateGL();
}

void QOSPRayWindow::mousePressEvent(QMouseEvent * event)
{
  lastMousePosition = event->pos();
}

void QOSPRayWindow::mouseReleaseEvent(QMouseEvent * event)
{
  lastMousePosition = event->pos();

  // restart continuous rendering immediately
  renderTimer.start();
}

void QOSPRayWindow::mouseMoveEvent(QMouseEvent * event)
{
  // pause continuous rendering during interaction and cancel any render restart timers.
  // this keeps interaction more responsive (especially with low frame rates).
  renderTimer.stop();
  renderRestartTimer.stop();

  resetAccumulationBuffer();

  int dx = event->x() - lastMousePosition.x();
  int dy = event->y() - lastMousePosition.y();

  if(event->buttons() & Qt::LeftButton) {

    // camera rotation about center point
    const float rotationSpeed = 0.003f;

    float du = dx * rotationSpeed;
    float dv = dy * rotationSpeed;

    rotateCenter(du, dv);
  }
  else if(event->buttons() & Qt::MidButton) {

    // camera strafe of from / at point
    const float strafeSpeed = 0.001f * length(worldBounds.size());

    float du = dx * strafeSpeed;
    float dv = dy * strafeSpeed;

    strafe(du, dv);
  }
  else if(event->buttons() & Qt::RightButton) {

    // camera distance from center point
    const float motionSpeed = 0.012f;

    float forward = dy * motionSpeed * length(worldBounds.size());
    float oldDistance = length(viewport.at - viewport.from);
    float newDistance = oldDistance - forward;

    if(newDistance < 1e-3f)
      return;

    viewport.from = viewport.at - newDistance * viewport.frame.l.vy;
    viewport.frame.p = viewport.from;

    viewport.modified = true;
  }

  lastMousePosition = event->pos();

  updateGL();

  // after a 0.5s delay, restart continuous rendering.
  renderRestartTimer.setSingleShot(true);
  renderRestartTimer.start(500);
}

void QOSPRayWindow::rotateCenter(float du, float dv)
{
  const ospcommon::vec3f pivot = viewport.at;

  ospcommon::affine3f xfm = ospcommon::affine3f::translate(pivot)
    * ospcommon::affine3f::rotate(viewport.frame.l.vx, -dv)
    * ospcommon::affine3f::rotate(viewport.frame.l.vz, -du)
    * ospcommon::affine3f::translate(-pivot);

  viewport.frame = xfm * viewport.frame;
  viewport.from  = xfmPoint(xfm, viewport.from);
  viewport.at    = xfmPoint(xfm, viewport.at);
  viewport.snapUp();

  viewport.modified = true;
}

void QOSPRayWindow::strafe(float du, float dv)
{
  ospcommon::affine3f xfm = ospcommon::affine3f::translate(dv * viewport.frame.l.vz)
    * ospcommon::affine3f::translate(-du * viewport.frame.l.vx);

  viewport.frame = xfm * viewport.frame;
  viewport.from = xfmPoint(xfm, viewport.from);
  viewport.at = xfmPoint(xfm, viewport.at);
  viewport.modified = true;

  viewport.modified = true;
}

void QOSPRayWindow::renderGL()
{
  // setup OpenGL state to match OSPRay view
  const ospcommon::vec3f bgColor = ospcommon::vec3f(1.f);
  glClearColor(bgColor.x, bgColor.y, bgColor.z, 1.f);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  float zNear = 0.1f;
  float zFar = 100000.f;
  gluPerspective(viewport.fovY, viewport.aspect, zNear, zFar);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  gluLookAt(viewport.from.x, viewport.from.y, viewport.from.z,
            viewport.at.x, viewport.at.y, viewport.at.z,
            viewport.up.x, viewport.up.y, viewport.up.z);

  // emit signal to render all OpenGL components; the slots will execute in the order they were registered
  emit(renderGLComponents());
}

void QOSPRayWindow::writeFrameBufferToFile(const uint32_t *pixelData)
{
  static uint32_t frameNumber = 0;
  char filename[1024];
  sprintf(filename, "%s_%05u.ppm", writeFramesFilename.c_str(), frameNumber++);
  FILE *file = fopen(filename, "wb");  if (!file) { std::cerr << "unable to write to file '" << filename << "'" << std::endl;  return; }

  fprintf(file, "P6\n%i %i\n255\n", windowSize.x, windowSize.y);
  unsigned char out[3 * windowSize.x];
  for (int y=0 ; y < windowSize.y ; y++) {
    const unsigned char *in = (const unsigned char *) &pixelData[(windowSize.y - 1 - y) * windowSize.x];
    for (int x=0 ; x < windowSize.x ; x++) {
      out[3 * x + 0] = in[4 * x + 0];
      out[3 * x + 1] = in[4 * x + 1];
      out[3 * x + 2] = in[4 * x + 2];
    }
    fwrite(&out, 3 * windowSize.x, sizeof(char), file);
  }
  fprintf(file, "\n");
  fclose(file);
}
<|endoftext|>


<commit_before>//
// file : backtrace.hpp
// in : file:///home/tim/projects/yaggler/yaggler/tools/backtrace.hpp
//
// created by : Timothée Feuillet on linux.site
// date: 13/02/2015 17:02:08
//
//
// Copyright (c) 2014-2016 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

#ifndef __N_1145625880472195080_2067372013__BACKTRACE_HPP__
# define __N_1145625880472195080_2067372013__BACKTRACE_HPP__

#ifdef __linux__
#include <execinfo.h>
#include <cxxabi.h>
#include <stdlib.h>
#include <string.h>
#endif

#include "logger/logger.hpp"

namespace neam
{
  namespace cr
  {
    /// \brief print the current callstack
    /// (and demangle functions name, and print a lovely addr2line command that you can use to get the line number)
    /// \param[in] backtrace_size the depth of the backtrace: the number of entries to print
    /// \param[in] skip the number of entries to skip from printing. (the N first entries to skip).
    /// \note currently only on LINUX
    static inline void print_callstack(size_t backtrace_size = 25, size_t skip = 1, bool has_logger_lock = false)
    {
#ifdef __linux__
      char **strings;
      void *bt[backtrace_size + skip];

      int num = backtrace(bt, backtrace_size + skip);
      strings = backtrace_symbols(bt, num);

      auto logger = neam::cr::out(has_logger_lock);
      logger.warn("#############[  B A C K T R A C E  ]#############");
      logger.debug("## most recent call first:");

      for (int j = skip; j < num; ++j)
      {
        // extract the symbol from the string
        int i = 0;
        int k = 0;
        for (; strings[j][i] && strings[j][i] != '('; ++i);
        if (strings[j][i]) ++i;
        for (; strings[j][i + k] && strings[j][i + k] != '+' && strings[j][i + k] != ')'; ++k);
        char *mangled = strndup(strings[j] + i, k);

        // demangle the symbol
        int status;
        char buffer[1024];
        size_t len = 1024;
        char *realname = abi::__cxa_demangle(mangled, buffer, &len, &status);
        if (status)
          realname = mangled;

        // print
        logger.warn("  [{}]: {}\t{}", num - j, realname, strings[j]);

        // and free
        free(mangled);
      }

      // print the indexes
      std::vector<char*> addr;
      addr.reserve(num);
      for (int j = skip; j < num; ++j)
      {
        // extract the address from the string
        int i = 0;
        int k = 0;
        for (; strings[j][i] && strings[j][i] != '['; ++i);
        if (strings[j][i]) ++i;
        for (; strings[j][i + k] && strings[j][i + k] != ']'; ++k);
        char *fnc_addr = strndup(strings[j] + i, k);

        addr.push_back(fnc_addr);
      }

      logger.debug("## addr2line -e {} -fipsC {}", program_invocation_name, fmt::join(addr, " "));

      for (auto it : addr)
      {
        free(it);
      }

      logger.warn("########[  B A C K T R A C E     E N D  ]########");

      free(strings);
#endif
    }
  }
} // namespace neam

#endif /*__N_1145625880472195080_2067372013__BACKTRACE_HPP__*/

// kate: indent-mode cstyle; indent-width 2; replace-tabs on;

<commit_msg>Make the addr2line info a warn not a debug<commit_after>//
// file : backtrace.hpp
// in : file:///home/tim/projects/yaggler/yaggler/tools/backtrace.hpp
//
// created by : Timothée Feuillet on linux.site
// date: 13/02/2015 17:02:08
//
//
// Copyright (c) 2014-2016 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

#ifndef __N_1145625880472195080_2067372013__BACKTRACE_HPP__
# define __N_1145625880472195080_2067372013__BACKTRACE_HPP__

#ifdef __linux__
#include <execinfo.h>
#include <cxxabi.h>
#include <stdlib.h>
#include <string.h>
#endif

#include "logger/logger.hpp"

namespace neam
{
  namespace cr
  {
    /// \brief print the current callstack
    /// (and demangle functions name, and print a lovely addr2line command that you can use to get the line number)
    /// \param[in] backtrace_size the depth of the backtrace: the number of entries to print
    /// \param[in] skip the number of entries to skip from printing. (the N first entries to skip).
    /// \note currently only on LINUX
    static inline void print_callstack(size_t backtrace_size = 25, size_t skip = 1, bool has_logger_lock = false)
    {
#ifdef __linux__
      char **strings;
      void *bt[backtrace_size + skip];

      int num = backtrace(bt, backtrace_size + skip);
      strings = backtrace_symbols(bt, num);

      auto logger = neam::cr::out(has_logger_lock);
      logger.warn("#############[  B A C K T R A C E  ]#############");
      logger.warn("## most recent call first:");

      for (int j = skip; j < num; ++j)
      {
        // extract the symbol from the string
        int i = 0;
        int k = 0;
        for (; strings[j][i] && strings[j][i] != '('; ++i);
        if (strings[j][i]) ++i;
        for (; strings[j][i + k] && strings[j][i + k] != '+' && strings[j][i + k] != ')'; ++k);
        char *mangled = strndup(strings[j] + i, k);

        // demangle the symbol
        int status;
        char buffer[1024];
        size_t len = 1024;
        char *realname = abi::__cxa_demangle(mangled, buffer, &len, &status);
        if (status)
          realname = mangled;

        // print
        logger.warn("  [{}]: {}\t{}", num - j, realname, strings[j]);

        // and free
        free(mangled);
      }

      // print the indexes
      std::vector<char*> addr;
      addr.reserve(num);
      for (int j = skip; j < num; ++j)
      {
        // extract the address from the string
        int i = 0;
        int k = 0;
        for (; strings[j][i] && strings[j][i] != '['; ++i);
        if (strings[j][i]) ++i;
        for (; strings[j][i + k] && strings[j][i + k] != ']'; ++k);
        char *fnc_addr = strndup(strings[j] + i, k);

        addr.push_back(fnc_addr);
      }

      logger.warn("## addr2line -e {} -fipsC {}", program_invocation_name, fmt::join(addr, " "));

      for (auto it : addr)
      {
        free(it);
      }

      logger.warn("########[  B A C K T R A C E     E N D  ]########");

      free(strings);
#endif
    }
  }
} // namespace neam

#endif /*__N_1145625880472195080_2067372013__BACKTRACE_HPP__*/

// kate: indent-mode cstyle; indent-width 2; replace-tabs on;

<|endoftext|>


<commit_before>/*
 * Add contact dialog
 *
 * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
 * Copyright (C) 2012 George Kiagiadakis <kiagiadakis.george@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "add-contact-dialog.h"
#include "ui_add-contact-dialog.h"

#include <KTp/Models/accounts-model.h>
#include <KTp/Models/accounts-model-item.h>

#include <QObject>
#include <QSortFilterProxyModel>
#include <QCloseEvent>

#include <KMessageBox>
#include <KPushButton>
#include <KDebug>

#include <TelepathyQt/Account>
#include <TelepathyQt/Connection>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingContacts>

namespace KTp {

/** A filter which only lists connections which accept adding contacts*/
class KTP_NO_EXPORT SubscribableAccountsModel : public QSortFilterProxyModel
{
public:
    SubscribableAccountsModel(QObject *parent);
    virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
};

SubscribableAccountsModel::SubscribableAccountsModel(QObject *parent)
 : QSortFilterProxyModel(parent)
{
}

bool SubscribableAccountsModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    AccountsModelItem* item = sourceModel()->index(source_row, 0, source_parent).data(AccountsModel::ItemRole).value<AccountsModelItem*>();

    if (item) {
        Tp::AccountPtr account = item->account();

        //if there's no connection we can't add contacts as we have no contactmanager
        if (! account->connection()) {
            return false;
        }

        //only show items which can add a contact (i.e hide accounts like IRC which are online but there's no point listing)
        if (! account->connection()->contactManager()->canRequestPresenceSubscription()){
            return false;
        }
    }
    return true;
}

struct KTP_NO_EXPORT AddContactDialog::Private
{
    Private() :
        ui(new Ui::AddContactDialog),
        acceptInProgress(false)
    {}

    Ui::AddContactDialog *ui;
    bool acceptInProgress;
};

AddContactDialog::AddContactDialog(AccountsModel *accountModel, QWidget *parent) :
    KDialog(parent),
    d(new Private)
{
    QWidget *widget = new QWidget(this);
    d->ui->setupUi(widget);
    setMainWidget(widget);

    SubscribableAccountsModel *filteredModel = new SubscribableAccountsModel(this);
    filteredModel->setSourceModel(accountModel);
    d->ui->accountCombo->setModel(filteredModel);

    d->ui->screenNameLineEdit->setFocus();
}

AddContactDialog::~AddContactDialog()
{
    delete d->ui;
    delete d;
}

void AddContactDialog::accept()
{
    Tp::AccountPtr account;
    QVariant itemData = d->ui->accountCombo->itemData(d->ui->accountCombo->currentIndex(), AccountsModel::ItemRole);
    AccountsModelItem* item = itemData.value<AccountsModelItem*>();
    if (item) {
        account = item->account();
    }

    if (account.isNull()) {
        KMessageBox::sorry(this, i18n("Seems like you forgot to select an account. "
                                      "Also, do not forget to connect it first."));
    } else if (account->connection().isNull()) {
        KMessageBox::sorry(this, i18n("The requested account has disconnected "
                                      "and so the contact could not be added."));
    } else if (d->ui->screenNameLineEdit->text().isEmpty()) {
        KMessageBox::sorry(this, i18n("You did not specify the name of the contact to add."));
    } else {
        QStringList identifiers = QStringList() << d->ui->screenNameLineEdit->text();
        kDebug() << "Requesting contacts for identifiers:" << identifiers;

        Tp::PendingContacts *pendingContacts = account->connection()->contactManager()->contactsForIdentifiers(identifiers);
        connect(pendingContacts, SIGNAL(finished(Tp::PendingOperation*)),
                this, SLOT(_k_onContactsForIdentifiersFinished(Tp::PendingOperation*)));

        setInProgress(true);
    }
}

void AddContactDialog::closeEvent(QCloseEvent *e)
{
    // ignore close event if we are in the middle of an operation
    if (!d->acceptInProgress) {
        KDialog::closeEvent(e);
    }
}

void AddContactDialog::_k_onContactsForIdentifiersFinished(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Failed to retrieve a contact for the given identifier"
                   << op->errorName() << op->errorMessage();
        KMessageBox::sorry(this, i18n("Failed to construct a contact with the given name."));
        setInProgress(false);
    } else {
        kDebug() << "Requesting presence subscription";

        Tp::PendingContacts *pc = qobject_cast<Tp::PendingContacts*>(op);
        connect(pc->manager()->requestPresenceSubscription(pc->contacts()),
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation*)));
    }
}

void AddContactDialog::_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Failed to request presence subscription"
                   << op->errorName() << op->errorMessage();
        KMessageBox::sorry(this, i18n("Failed to request presence subscription "
                                      "from the requested contact."));
        setInProgress(false);
    } else {
        QDialog::accept();
    }
}

void AddContactDialog::setInProgress(bool inProgress)
{
    d->acceptInProgress = inProgress;
    mainWidget()->setEnabled(!inProgress);
    button(KDialog::Ok)->setEnabled(!inProgress);
    button(KDialog::Cancel)->setEnabled(!inProgress);
}

} //namespace KTp

#include "add-contact-dialog.moc"
<commit_msg>AddContactDialog: Make some strings more user-friendly<commit_after>/*
 * Add contact dialog
 *
 * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
 * Copyright (C) 2012 George Kiagiadakis <kiagiadakis.george@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "add-contact-dialog.h"
#include "ui_add-contact-dialog.h"

#include <KTp/Models/accounts-model.h>
#include <KTp/Models/accounts-model-item.h>

#include <QObject>
#include <QSortFilterProxyModel>
#include <QCloseEvent>

#include <KMessageBox>
#include <KPushButton>
#include <KDebug>

#include <TelepathyQt/Account>
#include <TelepathyQt/Connection>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingContacts>

namespace KTp {

/** A filter which only lists connections which accept adding contacts*/
class KTP_NO_EXPORT SubscribableAccountsModel : public QSortFilterProxyModel
{
public:
    SubscribableAccountsModel(QObject *parent);
    virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
};

SubscribableAccountsModel::SubscribableAccountsModel(QObject *parent)
 : QSortFilterProxyModel(parent)
{
}

bool SubscribableAccountsModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    AccountsModelItem* item = sourceModel()->index(source_row, 0, source_parent).data(AccountsModel::ItemRole).value<AccountsModelItem*>();

    if (item) {
        Tp::AccountPtr account = item->account();

        //if there's no connection we can't add contacts as we have no contactmanager
        if (! account->connection()) {
            return false;
        }

        //only show items which can add a contact (i.e hide accounts like IRC which are online but there's no point listing)
        if (! account->connection()->contactManager()->canRequestPresenceSubscription()){
            return false;
        }
    }
    return true;
}

struct KTP_NO_EXPORT AddContactDialog::Private
{
    Private() :
        ui(new Ui::AddContactDialog),
        acceptInProgress(false)
    {}

    Ui::AddContactDialog *ui;
    bool acceptInProgress;
};

AddContactDialog::AddContactDialog(AccountsModel *accountModel, QWidget *parent) :
    KDialog(parent),
    d(new Private)
{
    QWidget *widget = new QWidget(this);
    d->ui->setupUi(widget);
    setMainWidget(widget);

    SubscribableAccountsModel *filteredModel = new SubscribableAccountsModel(this);
    filteredModel->setSourceModel(accountModel);
    d->ui->accountCombo->setModel(filteredModel);

    d->ui->screenNameLineEdit->setFocus();
}

AddContactDialog::~AddContactDialog()
{
    delete d->ui;
    delete d;
}

void AddContactDialog::accept()
{
    Tp::AccountPtr account;
    QVariant itemData = d->ui->accountCombo->itemData(d->ui->accountCombo->currentIndex(), AccountsModel::ItemRole);
    AccountsModelItem* item = itemData.value<AccountsModelItem*>();
    if (item) {
        account = item->account();
    }

    if (account.isNull()) {
        KMessageBox::sorry(this, i18n("No account selected."));
    } else if (account->connection().isNull()) {
        KMessageBox::sorry(this, i18n("The requested account has been disconnected "
                                      "and so the contact could not be added."));
    } else if (d->ui->screenNameLineEdit->text().isEmpty()) {
        KMessageBox::sorry(this, i18n("You did not specify the name of the contact to add."));
    } else {
        QStringList identifiers = QStringList() << d->ui->screenNameLineEdit->text();
        kDebug() << "Requesting contacts for identifiers:" << identifiers;

        Tp::PendingContacts *pendingContacts = account->connection()->contactManager()->contactsForIdentifiers(identifiers);
        connect(pendingContacts, SIGNAL(finished(Tp::PendingOperation*)),
                this, SLOT(_k_onContactsForIdentifiersFinished(Tp::PendingOperation*)));

        setInProgress(true);
    }
}

void AddContactDialog::closeEvent(QCloseEvent *e)
{
    // ignore close event if we are in the middle of an operation
    if (!d->acceptInProgress) {
        KDialog::closeEvent(e);
    }
}

void AddContactDialog::_k_onContactsForIdentifiersFinished(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Failed to retrieve a contact for the given identifier"
                   << op->errorName() << op->errorMessage();
        KMessageBox::sorry(this, i18n("Failed to create new contact."));
        setInProgress(false);
    } else {
        kDebug() << "Requesting presence subscription";

        Tp::PendingContacts *pc = qobject_cast<Tp::PendingContacts*>(op);
        connect(pc->manager()->requestPresenceSubscription(pc->contacts()),
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation*)));
    }
}

void AddContactDialog::_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Failed to request presence subscription"
                   << op->errorName() << op->errorMessage();
        KMessageBox::sorry(this, i18n("Failed to request presence subscription "
                                      "from the requested contact."));
        setInProgress(false);
    } else {
        QDialog::accept();
    }
}

void AddContactDialog::setInProgress(bool inProgress)
{
    d->acceptInProgress = inProgress;
    mainWidget()->setEnabled(!inProgress);
    button(KDialog::Ok)->setEnabled(!inProgress);
    button(KDialog::Cancel)->setEnabled(!inProgress);
}

} //namespace KTp

#include "add-contact-dialog.moc"
<|endoftext|>


<commit_before>/*******************************************************************************
*    ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration),
*    All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: acscomponentTestImpl.cpp,v 1.8 2006/09/01 02:20:54 cparedes Exp $"
*
* who       when        what
* --------  --------    ----------------------------------------------
* rcirami   2003-09-18  created

*/

#include <vltPort.h>

static char *rcsId="@(#) $Id: acscomponentTestImpl.cpp,v 1.8 2006/09/01 02:20:54 cparedes Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);

#include <acscomponentTestImpl.h>

extern CORBA::ORB_var orb;

//This must be used instead of "using ...." because of VxWorks
 using namespace acscomponent;

ACSComponentTestClassImpl::ACSComponentTestClassImpl(
						     const ACE_CString &name,
						     maci::ContainerServices *cs) :
  ACSComponentImpl(name,cs)
{

  ACS_SHORT_LOG((LM_INFO,"::ACSComponentTestClassImpl::ACSComponentTestClassImpl"));

}

ACSComponentTestClassImpl::~ACSComponentTestClassImpl()
{

  ACS_SHORT_LOG((LM_INFO,"::ACSComponentTestClassImpl::~ACSComponentTestClassImpl"));

}

void ACSComponentTestClassImpl::shutdown ()
    throw (CORBA::SystemException )
{
    ACS_SHORT_LOG((LM_INFO, "acscomponentTestImpl Shutdown"));
    orb->shutdown (true);
}

/* --------------- [ MACI DLL support functions ] -----------------*/

//MACI_DLL_SUPPORT_FUNCTIONS(ACSComponentTestClassImpl)

/* ----------------------------------------------------------------*/

<commit_msg>Removed the shutdown of the orb in the shutdown method of the component (the orb variable is extern and was shutted down twice: by the component and by the process instantiating the component)<commit_after>/*******************************************************************************
*    ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration),
*    All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: acscomponentTestImpl.cpp,v 1.9 2006/09/26 10:26:13 acaproni Exp $"
*
* who       when        what
* --------  --------    ----------------------------------------------
* rcirami   2003-09-18  created

*/

#include <vltPort.h>

static char *rcsId="@(#) $Id: acscomponentTestImpl.cpp,v 1.9 2006/09/26 10:26:13 acaproni Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);

#include <acscomponentTestImpl.h>

extern CORBA::ORB_var orb;

//This must be used instead of "using ...." because of VxWorks
 using namespace acscomponent;

ACSComponentTestClassImpl::ACSComponentTestClassImpl(
						     const ACE_CString &name,
						     maci::ContainerServices *cs) :
  ACSComponentImpl(name,cs)
{

  ACS_SHORT_LOG((LM_INFO,"::ACSComponentTestClassImpl::ACSComponentTestClassImpl"));

}

ACSComponentTestClassImpl::~ACSComponentTestClassImpl()
{

  ACS_SHORT_LOG((LM_INFO,"::ACSComponentTestClassImpl::~ACSComponentTestClassImpl"));

}

void ACSComponentTestClassImpl::shutdown ()
    throw (CORBA::SystemException )
{
    ACS_SHORT_LOG((LM_INFO, "acscomponentTestImpl Shutdown"));
 }

/* --------------- [ MACI DLL support functions ] -----------------*/

//MACI_DLL_SUPPORT_FUNCTIONS(ACSComponentTestClassImpl)

/* ----------------------------------------------------------------*/

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: rsctree.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 13:35:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _RSCTREE_HXX
#define _RSCTREE_HXX

#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif

#ifndef _RSCTOOLS_HXX
#include <rsctools.hxx>
#endif

/****************** C L A S S E S ****************************************/
class BiNode
{
protected:
    BiNode*     pLeft;    // left subtree
    BiNode*     pRight;   // right subtree

public:

                         // Wandelt eine doppelt verkettete Liste in
                         // einen binaeren Baum um
            BiNode *    ChangeDLListBTree( BiNode * pList );

                        BiNode();
    virtual             ~BiNode();

                        // Wandelt einen binaeren Baum in eine doppelt
                        // verkettete Liste um
                        BiNode* ChangeBTreeDLList();

            BiNode *    Left() const { return pLeft  ; };
            BiNode *    Right() const{ return pRight ; };
            void        EnumNodes( Link aLink ) const;
};

/*************************************************************************/
class NameNode : public BiNode
{
    void                SubOrderTree( NameNode * pOrderNode );

protected:
                        // pCmp ist Zeiger auf Namen
            NameNode*   Search( const void * pCmp ) const;

public:
            NameNode*   Left() const { return (NameNode *)pLeft  ; };
            NameNode*   Right() const{ return (NameNode *)pRight ; };
            NameNode*   Search( const NameNode * pName ) const;
                        // insert a new node in the b-tree
            BOOL        Insert( NameNode * pTN, sal_uInt32 * nDepth );
            BOOL        Insert( NameNode* pTN );
    virtual COMPARE     Compare( const NameNode * ) const;
    virtual COMPARE     Compare( const void * ) const;
            NameNode*   SearchParent( const NameNode * ) const;
                        // return ist neue Root
            NameNode*   Remove( NameNode * );
            void        OrderTree();
            BOOL        IsOrderTree() const;

};

/*************************************************************************/
class IdNode : public NameNode
{
    virtual COMPARE Compare( const NameNode * ) const;
    virtual COMPARE Compare( const void * ) const;

public:

    IdNode*         Search( sal_uInt32 nTypName ) const;
    virtual sal_uInt32  GetId() const;
};

/*************************************************************************/
class StringNode : public NameNode
{
    virtual COMPARE Compare( const NameNode * ) const;
    virtual COMPARE Compare( const void * ) const;

protected:
    ByteString      aName;

public:
                    StringNode(){};
                    StringNode( const ByteString & rStr ) { aName = rStr; }

    StringNode*     Search( const char * ) const;
    ByteString      GetName() const { return aName; }
};

#endif // _RSCTREE_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.4.8); FILE MERGED 2005/10/27 13:55:55 pl 1.4.8.1: #i55991# removed warnings for solaris platform<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: rsctree.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 05:45:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _RSCTREE_HXX
#define _RSCTREE_HXX

#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif

#ifndef _RSCTOOLS_HXX
#include <rsctools.hxx>
#endif

/****************** C L A S S E S ****************************************/
class BiNode
{
protected:
    BiNode*     pLeft;    // left subtree
    BiNode*     pRight;   // right subtree

public:

                         // Wandelt eine doppelt verkettete Liste in
                         // einen binaeren Baum um
            BiNode *    ChangeDLListBTree( BiNode * pList );

                        BiNode();
    virtual             ~BiNode();

                        // Wandelt einen binaeren Baum in eine doppelt
                        // verkettete Liste um
                        BiNode* ChangeBTreeDLList();

            BiNode *    Left() const { return pLeft  ; };
            BiNode *    Right() const{ return pRight ; };
            void        EnumNodes( Link aLink ) const;
};

/*************************************************************************/
class NameNode : public BiNode
{
    void                SubOrderTree( NameNode * pOrderNode );

protected:
                        // pCmp ist Zeiger auf Namen
            NameNode*   Search( const void * pCmp ) const;

public:
            NameNode*   Left() const { return (NameNode *)pLeft  ; };
            NameNode*   Right() const{ return (NameNode *)pRight ; };
            NameNode*   Search( const NameNode * pName ) const;
                        // insert a new node in the b-tree
            BOOL        Insert( NameNode * pTN, sal_uInt32 * nDepth );
            BOOL        Insert( NameNode* pTN );
    virtual COMPARE     Compare( const NameNode * ) const;
    virtual COMPARE     Compare( const void * ) const;
            NameNode*   SearchParent( const NameNode * ) const;
                        // return ist neue Root
            NameNode*   Remove( NameNode * );
            void        OrderTree();
            BOOL        IsOrderTree() const;

};

/*************************************************************************/
class IdNode : public NameNode
{
    virtual COMPARE Compare( const NameNode * ) const;
    virtual COMPARE Compare( const void * ) const;
protected:
    using NameNode::Search;

public:

    IdNode*         Search( sal_uInt32 nTypName ) const;
    virtual sal_uInt32  GetId() const;
};

/*************************************************************************/
class StringNode : public NameNode
{
    virtual COMPARE Compare( const NameNode * ) const;
    virtual COMPARE Compare( const void * ) const;

protected:
    using NameNode::Search;

    ByteString      aName;

public:
                    StringNode(){};
                    StringNode( const ByteString & rStr ) { aName = rStr; }

    StringNode*     Search( const char * ) const;
    ByteString      GetName() const { return aName; }
};

#endif // _RSCTREE_HXX
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      calc_relevant.inl
  \authors
  \authors     (rdo@rk9.bmstu.ru)
  \date      16.04.2011
  \brief     RDOCalc
  \indent    4T
*/

// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_runtime.h"
#include "simulator/runtime/rdo_activity.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOSetRelResParamCalc
// --------------------------------------------------------------------------------
template <EqualType equalType>
inline RDOSetRelResParamCalc<equalType>::RDOSetRelResParamCalc(ruint relResID, ruint paramID, CREF(LPRDOCalc) pCalc)
	: m_relResID(relResID)
	, m_paramID (paramID )
	, m_pCalc   (pCalc   )
{
	m_value = 1;
	if (m_pCalc)
	{
		setSrcInfo(m_pCalc->src_info());
	}
}

template <EqualType equalType>
inline RDOSetRelResParamCalc<equalType>::~RDOSetRelResParamCalc()
{}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_EQUAL>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	pRuntime->setResParamVal(resID, m_paramID, m_pCalc->calcValue(pRuntime));
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_PLUS>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	pRuntime->getResParamValRaw(resID, m_paramID) += m_pCalc->calcValue(pRuntime);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_MINUS>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	pRuntime->getResParamValRaw(resID, m_paramID) -= m_pCalc->calcValue(pRuntime);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_MULTIPLY>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	pRuntime->getResParamValRaw(resID, m_paramID) *= m_pCalc->calcValue(pRuntime);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_DIVIDE>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	pRuntime->getResParamValRaw(resID, m_paramID) /= m_pCalc->calcValue(pRuntime);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_INCR>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	pRuntime->getResParamValRaw(resID, m_paramID) += RDOValue(1);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_DECR>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	pRuntime->getResParamValRaw(resID, m_paramID) -= RDOValue(1);
	return m_value;
}

CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - калк возвращает значение параметра<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      calc_relevant.inl
  \authors
  \authors     (rdo@rk9.bmstu.ru)
  \date      16.04.2011
  \brief     RDOCalc
  \indent    4T
*/

// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_runtime.h"
#include "simulator/runtime/rdo_activity.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOSetRelResParamCalc
// --------------------------------------------------------------------------------
template <EqualType equalType>
inline RDOSetRelResParamCalc<equalType>::RDOSetRelResParamCalc(ruint relResID, ruint paramID, CREF(LPRDOCalc) pCalc)
	: m_relResID(relResID)
	, m_paramID (paramID )
	, m_pCalc   (pCalc   )
{
	m_value = 1;
	if (m_pCalc)
	{
		setSrcInfo(m_pCalc->src_info());
	}
}

template <EqualType equalType>
inline RDOSetRelResParamCalc<equalType>::~RDOSetRelResParamCalc()
{}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_EQUAL>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	m_value = m_pCalc->calcValue(pRuntime);
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	pRuntime->setResParamVal(resID, m_paramID, m_value);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_PLUS>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	m_value = pRuntime->getResParamValRaw(resID, m_paramID) += m_pCalc->calcValue(pRuntime);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_MINUS>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	m_value = pRuntime->getResParamValRaw(resID, m_paramID) -= m_pCalc->calcValue(pRuntime);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_MULTIPLY>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	m_value = pRuntime->getResParamValRaw(resID, m_paramID) *= m_pCalc->calcValue(pRuntime);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_DIVIDE>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	m_value = pRuntime->getResParamValRaw(resID, m_paramID) /= m_pCalc->calcValue(pRuntime);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_INCR>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	m_value = pRuntime->getResParamValRaw(resID, m_paramID) += RDOValue(1);
	return m_value;
}

template <>
inline REF(RDOValue) RDOSetRelResParamCalc<ET_DECR>::doCalc(CREF(LPRDORuntime) pRuntime)
{
	ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
	m_value = pRuntime->getResParamValRaw(resID, m_paramID) -= RDOValue(1);
	return m_value;
}

CLOSE_RDO_RUNTIME_NAMESPACE
<|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 "content/renderer/p2p/ipc_network_manager.h"

#include "base/bind.h"
#include "base/sys_byteorder.h"
#include "net/base/net_util.h"

namespace content {

IpcNetworkManager::IpcNetworkManager(P2PSocketDispatcher* socket_dispatcher)
    : socket_dispatcher_(socket_dispatcher),
      start_count_(0),
      network_list_received_(false),
      weak_factory_(this) {
  socket_dispatcher_->AddNetworkListObserver(this);
}

IpcNetworkManager::~IpcNetworkManager() {
  DCHECK(!start_count_);
  socket_dispatcher_->RemoveNetworkListObserver(this);
}

void IpcNetworkManager::StartUpdating() {
  if (network_list_received_) {
    // Post a task to avoid reentrancy.
    base::MessageLoop::current()->PostTask(
        FROM_HERE,
        base::Bind(&IpcNetworkManager::SendNetworksChangedSignal,
                   weak_factory_.GetWeakPtr()));
  }
  ++start_count_;
}

void IpcNetworkManager::StopUpdating() {
  DCHECK_GT(start_count_, 0);
  --start_count_;
}

void IpcNetworkManager::OnNetworkListChanged(
    const net::NetworkInterfaceList& list) {

  // Update flag if network list received for the first time.
  if (!network_list_received_)
    network_list_received_ = true;

  std::vector<talk_base::Network*> networks;
  for (net::NetworkInterfaceList::const_iterator it = list.begin();
       it != list.end(); it++) {
    uint32 address;
    if (it->address.size() != net::kIPv4AddressSize)
      continue;
    memcpy(&address, &it->address[0], sizeof(uint32));
    address = talk_base::NetworkToHost32(address);
    talk_base::Network* network = new talk_base::Network(
        it->name, it->name, talk_base::IPAddress(address), 32);
    network->AddIP(talk_base::IPAddress(address));
    networks.push_back(network);
  }

  bool changed = false;
  MergeNetworkList(networks, &changed);
  if (changed)
    SignalNetworksChanged();
}

void IpcNetworkManager::SendNetworksChangedSignal() {
  SignalNetworksChanged();
}

}  // namespace content
<commit_msg>Push IPv6 addresses to libjingle PortAllocator.<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 "content/renderer/p2p/ipc_network_manager.h"

#include "base/bind.h"
#include "base/sys_byteorder.h"
#include "net/base/net_util.h"

namespace content {

IpcNetworkManager::IpcNetworkManager(P2PSocketDispatcher* socket_dispatcher)
    : socket_dispatcher_(socket_dispatcher),
      start_count_(0),
      network_list_received_(false),
      weak_factory_(this) {
  socket_dispatcher_->AddNetworkListObserver(this);
}

IpcNetworkManager::~IpcNetworkManager() {
  DCHECK(!start_count_);
  socket_dispatcher_->RemoveNetworkListObserver(this);
}

void IpcNetworkManager::StartUpdating() {
  if (network_list_received_) {
    // Post a task to avoid reentrancy.
    base::MessageLoop::current()->PostTask(
        FROM_HERE,
        base::Bind(&IpcNetworkManager::SendNetworksChangedSignal,
                   weak_factory_.GetWeakPtr()));
  }
  ++start_count_;
}

void IpcNetworkManager::StopUpdating() {
  DCHECK_GT(start_count_, 0);
  --start_count_;
}

void IpcNetworkManager::OnNetworkListChanged(
    const net::NetworkInterfaceList& list) {

  // Update flag if network list received for the first time.
  if (!network_list_received_)
    network_list_received_ = true;

  // Note: 32 and 64 are the arbitrary(kind of) prefix length used to
  // differentiate IPv4 and IPv6 addresses.
  // talk_base::Network uses these prefix_length to compare network
  // interfaces discovered.
  std::vector<talk_base::Network*> networks;
  for (net::NetworkInterfaceList::const_iterator it = list.begin();
       it != list.end(); it++) {
    if (it->address.size() == net::kIPv4AddressSize) {
      uint32 address;
      memcpy(&address, &it->address[0], sizeof(uint32));
      address = talk_base::NetworkToHost32(address);
      talk_base::Network* network = new talk_base::Network(
          it->name, it->name, talk_base::IPAddress(address), 32);
      network->AddIP(talk_base::IPAddress(address));
      networks.push_back(network);
    } else if (it->address.size() == net::kIPv6AddressSize) {
      in6_addr address;
      memcpy(&address, &it->address[0], sizeof(in6_addr));
      talk_base::IPAddress ip6_addr(address);
      if (!talk_base::IPIsPrivate(ip6_addr)) {
        talk_base::Network* network = new talk_base::Network(
            it->name, it->name, ip6_addr, 64);
        network->AddIP(ip6_addr);
        networks.push_back(network);
      }
    }
  }

  bool changed = false;
  MergeNetworkList(networks, &changed);
  if (changed)
    SignalNetworksChanged();
}

void IpcNetworkManager::SendNetworksChangedSignal() {
  SignalNetworksChanged();
}

}  // namespace content
<|endoftext|>


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

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "xwalk/runtime/browser/image_util.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_registry.h"
#include "xwalk/runtime/common/xwalk_notification_types.h"
#include "xwalk/test/base/in_process_browser_test.h"
#include "xwalk/test/base/xwalk_test_utils.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "net/base/net_util.h"
#include "testing/gmock/include/gmock/gmock.h"

#if defined(TOOLKIT_GTK)
#include <gtk/gtk.h>  // NOLINT(build/include_order)
#endif

using xwalk::NativeAppWindow;
using xwalk::Runtime;
using xwalk::RuntimeRegistry;
using xwalk::RuntimeList;
using content::WebContents;
using testing::_;

// A mock observer to listen runtime registry changes.
class MockRuntimeRegistryObserver : public xwalk::RuntimeRegistryObserver {
 public:
  MockRuntimeRegistryObserver() {}
  virtual ~MockRuntimeRegistryObserver() {}

  MOCK_METHOD1(OnRuntimeAdded, void(Runtime* runtime));
  MOCK_METHOD1(OnRuntimeRemoved, void(Runtime* runtime));
  MOCK_METHOD1(OnRuntimeAppIconChanged, void(Runtime* runtime));

 private:
  DISALLOW_COPY_AND_ASSIGN(MockRuntimeRegistryObserver);
};

// An observer used to verify app icon change.
class FaviconChangedObserver : public xwalk::RuntimeRegistryObserver {
 public:
  explicit FaviconChangedObserver(const base::FilePath& icon_file)
      : icon_file_(icon_file) {
  }

  virtual ~FaviconChangedObserver() {}

  virtual void OnRuntimeAdded(Runtime* runtime) OVERRIDE {}

  virtual void OnRuntimeRemoved(Runtime* runtime) OVERRIDE {}

  virtual void OnRuntimeAppIconChanged(Runtime* runtime) OVERRIDE {
    const base::FilePath::StringType kPNGFormat(FILE_PATH_LITERAL(".png"));
    const base::FilePath::StringType kICOFormat(FILE_PATH_LITERAL(".ico"));

    gfx::Image image;
    image = xwalk_utils::LoadImageFromFilePath(icon_file_);

    EXPECT_FALSE(image.IsEmpty());
    gfx::Image icon = runtime->app_icon();
    EXPECT_FALSE(icon.IsEmpty());
    EXPECT_EQ(image.Size(), icon.Size());

    // Quit the message loop.
    MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
  }

 private:
  const base::FilePath& icon_file_;
};

// Observer for NOTIFICATION_FULLSCREEN_CHANGED notifications.
class FullscreenNotificationObserver
    : public content::WindowedNotificationObserver {
 public:
  FullscreenNotificationObserver() : WindowedNotificationObserver(
      xwalk::NOTIFICATION_FULLSCREEN_CHANGED,
      content::NotificationService::AllSources()) {}
 private:
  DISALLOW_COPY_AND_ASSIGN(FullscreenNotificationObserver);
};

class XWalkRuntimeTest : public InProcessBrowserTest {
 public:
  XWalkRuntimeTest() {}
  virtual ~XWalkRuntimeTest() {
    original_runtimes_.clear();
    notification_observer_.reset();
  }

  void Relaunch(const CommandLine& new_command_line) {
    base::LaunchProcess(new_command_line, base::LaunchOptions(), NULL);
  }

  // SetUpOnMainThread is called after BrowserMainRunner was initialized and
  // just before RunTestOnMainThread (aka. TestBody).
  virtual void SetUpOnMainThread() OVERRIDE {
    notification_observer_.reset(
        new content::WindowedNotificationObserver(
          xwalk::NOTIFICATION_RUNTIME_OPENED,
          content::NotificationService::AllSources()));
    const RuntimeList& runtimes = RuntimeRegistry::Get()->runtimes();
    for (RuntimeList::const_iterator it = runtimes.begin();
         it != runtimes.end(); ++it)
      original_runtimes_.push_back(*it);
  }

  // Block UI thread until a new Runtime instance is created.
  Runtime* WaitForSingleNewRuntime() {
    notification_observer_->Wait();
    const RuntimeList& runtimes = RuntimeRegistry::Get()->runtimes();
    for (RuntimeList::const_iterator it = runtimes.begin();
         it != runtimes.end(); ++it) {
      RuntimeList::iterator target =
          std::find(original_runtimes_.begin(), original_runtimes_.end(), *it);
      // Not found means a new one.
      if (target == original_runtimes_.end()) {
        original_runtimes_.push_back(*it);
        return *it;
      }
    }
    return NULL;
  }

 private:
  RuntimeList original_runtimes_;
  scoped_ptr<content::WindowedNotificationObserver> notification_observer_;
};

// FIXME(hmin): Since currently the browser process is not shared by multiple
// app launch, this test is disabled to avoid floody launches.
IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, DISABLED_SecondLaunch) {
  MockRuntimeRegistryObserver observer;
  RuntimeRegistry::Get()->AddObserver(&observer);
  Relaunch(GetCommandLineForRelaunch());

  Runtime* second_runtime = NULL;
  EXPECT_TRUE(second_runtime == WaitForSingleNewRuntime());
  EXPECT_CALL(observer, OnRuntimeAdded(second_runtime)).Times(1);
  ASSERT_EQ(2u, RuntimeRegistry::Get()->runtimes().size());

  RuntimeRegistry::Get()->RemoveObserver(&observer);
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, CreateAndCloseRuntime) {
  MockRuntimeRegistryObserver observer;
  RuntimeRegistry::Get()->AddObserver(&observer);
  // At least one Runtime instance is created at startup.
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  ASSERT_EQ(1, len);

  // Create a new Runtime instance.
  GURL url(test_server()->GetURL("test.html"));
  EXPECT_CALL(observer, OnRuntimeAdded(_)).Times(1);
  Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);
  EXPECT_TRUE(url == new_runtime->web_contents()->GetURL());
  EXPECT_EQ(new_runtime, WaitForSingleNewRuntime());
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());

  // Close the newly created Runtime instance.
  EXPECT_CALL(observer, OnRuntimeRemoved(new_runtime)).Times(1);
  new_runtime->Close();
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());

  RuntimeRegistry::Get()->RemoveObserver(&observer);
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, LoadURLAndClose) {
  GURL url(test_server()->GetURL("test.html"));
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  runtime()->LoadURL(url);
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());
  runtime()->Close();
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len - 1, RuntimeRegistry::Get()->runtimes().size());
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, CloseNativeWindow) {
  GURL url(test_server()->GetURL("test.html"));
  Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  new_runtime->window()->Close();
  content::RunAllPendingInMessageLoop();
  // Closing native window will lead to close Runtime instance.
  EXPECT_EQ(len - 1, RuntimeRegistry::Get()->runtimes().size());
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, LaunchWithFullscreenWindow) {
  MockRuntimeRegistryObserver observer;
  RuntimeRegistry::Get()->AddObserver(&observer);
  // At least one Runtime instance is created at startup.
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  ASSERT_EQ(1, len);
  // Original Runtime should has non fullscreen window.
  EXPECT_TRUE(false == runtime()->window()->IsFullscreen());

  // Add "--fullscreen" launch argument.
  CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  cmd_line->AppendSwitch("fullscreen");

  // Create a new Runtime instance.
  FullscreenNotificationObserver fullscreen_observer;
  GURL url(test_server()->GetURL("test.html"));
  EXPECT_CALL(observer, OnRuntimeAdded(_)).Times(1);
  Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());
  fullscreen_observer.Wait();
  EXPECT_TRUE(true == new_runtime->window()->IsFullscreen());

  // Close the newly created Runtime instance.
  EXPECT_CALL(observer, OnRuntimeRemoved(new_runtime)).Times(1);
  new_runtime->Close();
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());

  RuntimeRegistry::Get()->RemoveObserver(&observer);
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, HTML5FullscreenAPI) {
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(), base::FilePath().AppendASCII("fullscreen.html"));
  xwalk_test_utils::NavigateToURL(runtime(), url);
  EXPECT_TRUE(false == runtime()->window()->IsFullscreen());

  FullscreenNotificationObserver enter_observer;
  runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(
      string16(),
      ASCIIToUTF16("doFullscreenClick();"));
  content::RunAllPendingInMessageLoop();
  enter_observer.Wait();
  // Calling doFullscreenClick defined in fullscreen.html leads to enter into
  // fullscreen window state, so it's expected to be fullscreen.
  EXPECT_TRUE(true == runtime()->window()->IsFullscreen());

  FullscreenNotificationObserver exit_observer;
  runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(
      string16(),
      ASCIIToUTF16("doExitFullscreenClick();"));
  content::RunAllPendingInMessageLoop();
  exit_observer.Wait();
  // Calling doExitFullscreenClick defined in fullscreen.html leads to exit
  // fullscreen window state, so it's expected to be not fullscreen.
  EXPECT_TRUE(false == runtime()->window()->IsFullscreen());
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, GetWindowTitle) {
  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(), base::FilePath().AppendASCII("title.html"));
  string16 title = ASCIIToUTF16("Dummy Title");
  content::TitleWatcher title_watcher(runtime()->web_contents(), title);
  xwalk_test_utils::NavigateToURL(runtime(), url);
  EXPECT_EQ(title, title_watcher.WaitAndGetTitle());

  NativeAppWindow* window = runtime()->window();
#if defined(TOOLKIT_GTK)
  const char* window_title = gtk_window_get_title(window->GetNativeWindow());
  EXPECT_EQ(title, ASCIIToUTF16(window_title));
#elif defined(TOOLKIT_VIEWS)
  const int len = title.length() + 1;  // NULL-terminated string.
  string16 window_title;
  ::GetWindowText(window->GetNativeWindow(),
                  WriteInto(&window_title, len), len);
  EXPECT_EQ(title, window_title);
#endif  // defined(TOOLKIT_GTK)
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, OpenLinkInNewRuntime) {
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(), base::FilePath().AppendASCII("new_target.html"));
  xwalk_test_utils::NavigateToURL(runtime(), url);
  runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(
      string16(),
      ASCIIToUTF16("doClick();"));
  content::RunAllPendingInMessageLoop();
  // Calling doClick defined in new_target.html leads to open a href in a new
  // target window, and so it is expected to create a new Runtime instance.
  Runtime* second = WaitForSingleNewRuntime();
  EXPECT_TRUE(NULL != second);
  EXPECT_NE(runtime(), second);
  EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, FaviconTest_ICO) {
  base::FilePath icon_file(xwalk_test_utils::GetTestFilePath(
      base::FilePath(FILE_PATH_LITERAL("favicon")),
      base::FilePath(FILE_PATH_LITERAL("16x16.ico"))));

  FaviconChangedObserver observer(icon_file);
  RuntimeRegistry::Get()->AddObserver(&observer);

  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(FILE_PATH_LITERAL("favicon")),
      base::FilePath().AppendASCII("favicon_ico.html"));

  xwalk_test_utils::NavigateToURL(runtime(), url);
  content::RunMessageLoop();
  RuntimeRegistry::Get()->RemoveObserver(&observer);
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, FaviconTest_PNG) {
  base::FilePath icon_file(xwalk_test_utils::GetTestFilePath(
      base::FilePath(FILE_PATH_LITERAL("favicon")),
      base::FilePath(FILE_PATH_LITERAL("48x48.png"))));

  FaviconChangedObserver observer(icon_file);
  RuntimeRegistry::Get()->AddObserver(&observer);

  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(FILE_PATH_LITERAL("favicon")),
      base::FilePath().AppendASCII("favicon_png.html"));

  xwalk_test_utils::NavigateToURL(runtime(), url);
  content::RunMessageLoop();
  RuntimeRegistry::Get()->RemoveObserver(&observer);
}
<commit_msg>Aura: fix the runtime browser test.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "xwalk/runtime/browser/image_util.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_registry.h"
#include "xwalk/runtime/common/xwalk_notification_types.h"
#include "xwalk/test/base/in_process_browser_test.h"
#include "xwalk/test/base/xwalk_test_utils.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "net/base/net_util.h"
#include "testing/gmock/include/gmock/gmock.h"

#if defined(TOOLKIT_GTK)
#include <gtk/gtk.h>  // NOLINT(build/include_order)
#endif

#if defined(USE_AURA)
#include "ui/aura/window.h"
#endif

using xwalk::NativeAppWindow;
using xwalk::Runtime;
using xwalk::RuntimeRegistry;
using xwalk::RuntimeList;
using content::WebContents;
using testing::_;

// A mock observer to listen runtime registry changes.
class MockRuntimeRegistryObserver : public xwalk::RuntimeRegistryObserver {
 public:
  MockRuntimeRegistryObserver() {}
  virtual ~MockRuntimeRegistryObserver() {}

  MOCK_METHOD1(OnRuntimeAdded, void(Runtime* runtime));
  MOCK_METHOD1(OnRuntimeRemoved, void(Runtime* runtime));
  MOCK_METHOD1(OnRuntimeAppIconChanged, void(Runtime* runtime));

 private:
  DISALLOW_COPY_AND_ASSIGN(MockRuntimeRegistryObserver);
};

// An observer used to verify app icon change.
class FaviconChangedObserver : public xwalk::RuntimeRegistryObserver {
 public:
  explicit FaviconChangedObserver(const base::FilePath& icon_file)
      : icon_file_(icon_file) {
  }

  virtual ~FaviconChangedObserver() {}

  virtual void OnRuntimeAdded(Runtime* runtime) OVERRIDE {}

  virtual void OnRuntimeRemoved(Runtime* runtime) OVERRIDE {}

  virtual void OnRuntimeAppIconChanged(Runtime* runtime) OVERRIDE {
    const base::FilePath::StringType kPNGFormat(FILE_PATH_LITERAL(".png"));
    const base::FilePath::StringType kICOFormat(FILE_PATH_LITERAL(".ico"));

    gfx::Image image;
    image = xwalk_utils::LoadImageFromFilePath(icon_file_);

    EXPECT_FALSE(image.IsEmpty());
    gfx::Image icon = runtime->app_icon();
    EXPECT_FALSE(icon.IsEmpty());
    EXPECT_EQ(image.Size(), icon.Size());

    // Quit the message loop.
    MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
  }

 private:
  const base::FilePath& icon_file_;
};

// Observer for NOTIFICATION_FULLSCREEN_CHANGED notifications.
class FullscreenNotificationObserver
    : public content::WindowedNotificationObserver {
 public:
  FullscreenNotificationObserver() : WindowedNotificationObserver(
      xwalk::NOTIFICATION_FULLSCREEN_CHANGED,
      content::NotificationService::AllSources()) {}
 private:
  DISALLOW_COPY_AND_ASSIGN(FullscreenNotificationObserver);
};

class XWalkRuntimeTest : public InProcessBrowserTest {
 public:
  XWalkRuntimeTest() {}
  virtual ~XWalkRuntimeTest() {
    original_runtimes_.clear();
    notification_observer_.reset();
  }

  void Relaunch(const CommandLine& new_command_line) {
    base::LaunchProcess(new_command_line, base::LaunchOptions(), NULL);
  }

  // SetUpOnMainThread is called after BrowserMainRunner was initialized and
  // just before RunTestOnMainThread (aka. TestBody).
  virtual void SetUpOnMainThread() OVERRIDE {
    notification_observer_.reset(
        new content::WindowedNotificationObserver(
          xwalk::NOTIFICATION_RUNTIME_OPENED,
          content::NotificationService::AllSources()));
    const RuntimeList& runtimes = RuntimeRegistry::Get()->runtimes();
    for (RuntimeList::const_iterator it = runtimes.begin();
         it != runtimes.end(); ++it)
      original_runtimes_.push_back(*it);
  }

  // Block UI thread until a new Runtime instance is created.
  Runtime* WaitForSingleNewRuntime() {
    notification_observer_->Wait();
    const RuntimeList& runtimes = RuntimeRegistry::Get()->runtimes();
    for (RuntimeList::const_iterator it = runtimes.begin();
         it != runtimes.end(); ++it) {
      RuntimeList::iterator target =
          std::find(original_runtimes_.begin(), original_runtimes_.end(), *it);
      // Not found means a new one.
      if (target == original_runtimes_.end()) {
        original_runtimes_.push_back(*it);
        return *it;
      }
    }
    return NULL;
  }

 private:
  RuntimeList original_runtimes_;
  scoped_ptr<content::WindowedNotificationObserver> notification_observer_;
};

// FIXME(hmin): Since currently the browser process is not shared by multiple
// app launch, this test is disabled to avoid floody launches.
IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, DISABLED_SecondLaunch) {
  MockRuntimeRegistryObserver observer;
  RuntimeRegistry::Get()->AddObserver(&observer);
  Relaunch(GetCommandLineForRelaunch());

  Runtime* second_runtime = NULL;
  EXPECT_TRUE(second_runtime == WaitForSingleNewRuntime());
  EXPECT_CALL(observer, OnRuntimeAdded(second_runtime)).Times(1);
  ASSERT_EQ(2u, RuntimeRegistry::Get()->runtimes().size());

  RuntimeRegistry::Get()->RemoveObserver(&observer);
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, CreateAndCloseRuntime) {
  MockRuntimeRegistryObserver observer;
  RuntimeRegistry::Get()->AddObserver(&observer);
  // At least one Runtime instance is created at startup.
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  ASSERT_EQ(1, len);

  // Create a new Runtime instance.
  GURL url(test_server()->GetURL("test.html"));
  EXPECT_CALL(observer, OnRuntimeAdded(_)).Times(1);
  Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);
  EXPECT_TRUE(url == new_runtime->web_contents()->GetURL());
  EXPECT_EQ(new_runtime, WaitForSingleNewRuntime());
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());

  // Close the newly created Runtime instance.
  EXPECT_CALL(observer, OnRuntimeRemoved(new_runtime)).Times(1);
  new_runtime->Close();
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());

  RuntimeRegistry::Get()->RemoveObserver(&observer);
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, LoadURLAndClose) {
  GURL url(test_server()->GetURL("test.html"));
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  runtime()->LoadURL(url);
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());
  runtime()->Close();
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len - 1, RuntimeRegistry::Get()->runtimes().size());
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, CloseNativeWindow) {
  GURL url(test_server()->GetURL("test.html"));
  Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  new_runtime->window()->Close();
  content::RunAllPendingInMessageLoop();
  // Closing native window will lead to close Runtime instance.
  EXPECT_EQ(len - 1, RuntimeRegistry::Get()->runtimes().size());
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, LaunchWithFullscreenWindow) {
  MockRuntimeRegistryObserver observer;
  RuntimeRegistry::Get()->AddObserver(&observer);
  // At least one Runtime instance is created at startup.
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  ASSERT_EQ(1, len);
  // Original Runtime should has non fullscreen window.
  EXPECT_TRUE(false == runtime()->window()->IsFullscreen());

  // Add "--fullscreen" launch argument.
  CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  cmd_line->AppendSwitch("fullscreen");

  // Create a new Runtime instance.
  FullscreenNotificationObserver fullscreen_observer;
  GURL url(test_server()->GetURL("test.html"));
  EXPECT_CALL(observer, OnRuntimeAdded(_)).Times(1);
  Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());
  fullscreen_observer.Wait();
  EXPECT_TRUE(true == new_runtime->window()->IsFullscreen());

  // Close the newly created Runtime instance.
  EXPECT_CALL(observer, OnRuntimeRemoved(new_runtime)).Times(1);
  new_runtime->Close();
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());

  RuntimeRegistry::Get()->RemoveObserver(&observer);
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, HTML5FullscreenAPI) {
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(), base::FilePath().AppendASCII("fullscreen.html"));
  xwalk_test_utils::NavigateToURL(runtime(), url);
  EXPECT_TRUE(false == runtime()->window()->IsFullscreen());

  FullscreenNotificationObserver enter_observer;
  runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(
      string16(),
      ASCIIToUTF16("doFullscreenClick();"));
  content::RunAllPendingInMessageLoop();
  enter_observer.Wait();
  // Calling doFullscreenClick defined in fullscreen.html leads to enter into
  // fullscreen window state, so it's expected to be fullscreen.
  EXPECT_TRUE(true == runtime()->window()->IsFullscreen());

  FullscreenNotificationObserver exit_observer;
  runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(
      string16(),
      ASCIIToUTF16("doExitFullscreenClick();"));
  content::RunAllPendingInMessageLoop();
  exit_observer.Wait();
  // Calling doExitFullscreenClick defined in fullscreen.html leads to exit
  // fullscreen window state, so it's expected to be not fullscreen.
  EXPECT_TRUE(false == runtime()->window()->IsFullscreen());
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, GetWindowTitle) {
  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(), base::FilePath().AppendASCII("title.html"));
  string16 title = ASCIIToUTF16("Dummy Title");
  content::TitleWatcher title_watcher(runtime()->web_contents(), title);
  xwalk_test_utils::NavigateToURL(runtime(), url);
  EXPECT_EQ(title, title_watcher.WaitAndGetTitle());

  NativeAppWindow* window = runtime()->window();
#if defined(TOOLKIT_GTK)
  const char* window_title = gtk_window_get_title(window->GetNativeWindow());
  EXPECT_EQ(title, ASCIIToUTF16(window_title));
#elif defined(TOOLKIT_VIEWS) && defined(OS_WIN)
  const int len = title.length() + 1;  // NULL-terminated string.
  string16 window_title;
  ::GetWindowText(window->GetNativeWindow(),
                  WriteInto(&window_title, len), len);
  EXPECT_EQ(title, window_title);
#elif defined(USE_AURA)
  string16 window_title = window->GetNativeWindow()->title();
  EXPECT_EQ(title, window_title);
#endif  // defined(TOOLKIT_GTK)
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, OpenLinkInNewRuntime) {
  size_t len = RuntimeRegistry::Get()->runtimes().size();
  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(), base::FilePath().AppendASCII("new_target.html"));
  xwalk_test_utils::NavigateToURL(runtime(), url);
  runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(
      string16(),
      ASCIIToUTF16("doClick();"));
  content::RunAllPendingInMessageLoop();
  // Calling doClick defined in new_target.html leads to open a href in a new
  // target window, and so it is expected to create a new Runtime instance.
  Runtime* second = WaitForSingleNewRuntime();
  EXPECT_TRUE(NULL != second);
  EXPECT_NE(runtime(), second);
  EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, FaviconTest_ICO) {
  base::FilePath icon_file(xwalk_test_utils::GetTestFilePath(
      base::FilePath(FILE_PATH_LITERAL("favicon")),
      base::FilePath(FILE_PATH_LITERAL("16x16.ico"))));

  FaviconChangedObserver observer(icon_file);
  RuntimeRegistry::Get()->AddObserver(&observer);

  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(FILE_PATH_LITERAL("favicon")),
      base::FilePath().AppendASCII("favicon_ico.html"));

  xwalk_test_utils::NavigateToURL(runtime(), url);
  content::RunMessageLoop();
  RuntimeRegistry::Get()->RemoveObserver(&observer);
}

IN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, FaviconTest_PNG) {
  base::FilePath icon_file(xwalk_test_utils::GetTestFilePath(
      base::FilePath(FILE_PATH_LITERAL("favicon")),
      base::FilePath(FILE_PATH_LITERAL("48x48.png"))));

  FaviconChangedObserver observer(icon_file);
  RuntimeRegistry::Get()->AddObserver(&observer);

  GURL url = xwalk_test_utils::GetTestURL(
      base::FilePath(FILE_PATH_LITERAL("favicon")),
      base::FilePath().AppendASCII("favicon_png.html"));

  xwalk_test_utils::NavigateToURL(runtime(), url);
  content::RunMessageLoop();
  RuntimeRegistry::Get()->RemoveObserver(&observer);
}
<|endoftext|>