<commit_before>#include "journal/player.hpp"

#include <list>
#include <string>
#include <vector>

#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"

namespace principia {
namespace journal {

class PlayerTest : public testing::Test {
 protected:
  PlayerTest()
      : test_name_(
            testing::UnitTest::GetInstance()->current_test_info()->name()),
        plugin_(ksp_plugin::principia__NewPlugin(1, 2)),
        recorder_(new Recorder(test_name_ + ".journal.hex")) {
    Recorder::Activate(recorder_);
  }

  ~PlayerTest() override {
    Recorder::Deactivate();
  }

  std::string const test_name_;
  std::unique_ptr<ksp_plugin::Plugin> plugin_;
  Recorder* recorder_;
};

TEST_F(PlayerTest, PlayTiny) {
  {
    Method<NewPlugin> m({1, 2});
    m.Return(plugin_.get());
  }
  {
    const ksp_plugin::Plugin* plugin = plugin_.get();
    Method<DeletePlugin> m({&plugin}, {&plugin});
    m.Return();
  }

  Player player(test_name_ + ".journal.hex");

  // Replay the journal.  Note that the journal doesn't grow as we replay
  // because we didn't call principia__ActivateRecorder so there is no active
  // journal in the ksp_plugin assembly.
  int count = 0;
  while (player.Play()) {
    ++count;
  }
  EXPECT_EQ(2, count);
}

#if 0
TEST_F(PlayerTest, PlayForReal) {
  Player player("P:\\Public Mockingbird\\Principia\\JOURNAL.20151203-220350");
  while (player.Play()) {}
}
#endif

}  // namespace journal
}  // namespace principia
<commit_msg>Run an actual replay.<commit_after>#include "journal/player.hpp"

#include <list>
#include <string>
#include <vector>

#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"

namespace principia {
namespace journal {

class PlayerTest : public testing::Test {
 protected:
  PlayerTest()
      : test_name_(
            testing::UnitTest::GetInstance()->current_test_info()->name()),
        plugin_(ksp_plugin::principia__NewPlugin(1, 2)),
        recorder_(new Recorder(test_name_ + ".journal.hex")) {
    Recorder::Activate(recorder_);
  }

  ~PlayerTest() override {
    Recorder::Deactivate();
  }

  std::string const test_name_;
  std::unique_ptr<ksp_plugin::Plugin> plugin_;
  Recorder* recorder_;
};

TEST_F(PlayerTest, PlayTiny) {
  {
    Method<NewPlugin> m({1, 2});
    m.Return(plugin_.get());
  }
  {
    const ksp_plugin::Plugin* plugin = plugin_.get();
    Method<DeletePlugin> m({&plugin}, {&plugin});
    m.Return();
  }

  Player player(test_name_ + ".journal.hex");

  // Replay the journal.  Note that the journal doesn't grow as we replay
  // because we didn't call principia__ActivateRecorder so there is no active
  // journal in the ksp_plugin assembly.
  int count = 0;
  while (player.Play()) {
    ++count;
  }
  EXPECT_EQ(2, count);
}

#if !defined(_DEBUG)
TEST_F(PlayerTest, PlayForReal) {
  Player player("P:\\Public Mockingbird\\Principia\\JOURNAL.20151206-170008");
  int count = 0;
  while (player.Play()) {
    ++count;
    LOG_IF(ERROR, (count % 10'000) == 0)
        << count << " journal entries replayed";
  }
}
#endif

}  // namespace journal
}  // namespace principia
<|endoftext|>


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

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

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

 =========================================================================*/

#include "otbDEMConvert.h"

#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"

// OSSIM include
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimStdOutProgress.h>
#include <ossim/base/ossimFilename.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/imaging/ossimJpegWriter.h>
#include <ossim/imaging/ossimImageHandler.h>
#include <ossim/imaging/ossimImageSource.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>
#include <ossim/imaging/ossimImageWriterFactoryRegistry.h>
#include <ossim/imaging/ossimImageWriterFactory.h>
#include <ossim/imaging/ossimImageFileWriter.h>
#include <ossim/imaging/ossimCacheTileSource.h>
#include <ossim/imaging/ossimBandSelector.h>
#include <ossim/imaging/ossimCibCadrgTileSource.h>

namespace otb
{

template<typename TPixelType>
int generic_convert_to_tif(otb::ApplicationOptionsResult* parseResult, ossimFilename tempFilename)
{
  typedef otb::VectorImage<TPixelType>              ImageType;
  typedef otb::ImageFileReader<ImageType>          ReaderType;
  typedef otb::StreamingImageFileWriter<ImageType> WriterType;

  typename ReaderType::Pointer reader = ReaderType::New();
  typename WriterType::Pointer writer = WriterType::New();

  reader->SetFileName(parseResult->GetInputImage().c_str());
  writer->SetFileName(tempFilename);

  writer->SetInput(reader->GetOutput());
  writer->Update();

  return EXIT_SUCCESS;
}

int DEMConvert::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("DEMConvertApplication");
  descriptor->SetDescription("Convert a DEM file into a general raster (.ras, .geom and .omd). To be used, those files have to be in a stand alone directory");
  descriptor->AddInputImage();
  descriptor->AddOption("OutputPath", "The filename (or path filename) of the output. It generates a Output.geom, Output.omd and Output.ras file.","out", 1, true,ApplicationDescriptor::String);
  descriptor->AddOption("KeepTif", "Keep the temporary generate tif file.","ktif", 0, false,ApplicationDescriptor::Boolean);

  return EXIT_SUCCESS;
}

/* The main is simple : read image using OTB and write it as a tif.
* Read this tif using OSSIM and convert it as a general raster file (.ras, .geom and . omd)
* first write the image as a tif (supported by OSSIM) allows to not only be abble to work
* with OSSIM supported format but any more.
*/

int DEMConvert::Execute(otb::ApplicationOptionsResult* parseResult)
{
  // Load input and output filename
  const char * input_file = parseResult->GetInputImage().c_str();

  ossimFilename tempFilename(parseResult->GetParameterString("OutputPath"));
  tempFilename += "_DEMConvert.tif";

  // Search for the input
  typedef otb::VectorImage<double, 2> InputImageType;
  typedef otb::ImageFileReader<InputImageType> ReaderType;
  ReaderType::Pointer reader=ReaderType::New();
  reader->SetFileName(input_file);
  reader->UpdateOutputInformation();

  // Generate the tif image using OTB
  // We keep the same pixel type
  std::string componentTypeInfo(reader->GetImageIO()->GetComponentTypeInfo().name());
  if( componentTypeInfo == typeid(unsigned char).name())
    {
      generic_convert_to_tif<unsigned char>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(char).name())
    {
      generic_convert_to_tif<char>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(unsigned short).name())
    {
      generic_convert_to_tif<unsigned short>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(short).name())
    {
      generic_convert_to_tif<short>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(unsigned int).name())
    {
      generic_convert_to_tif<unsigned int>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(int).name())
    {
      generic_convert_to_tif<int>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(unsigned long).name())
    {
      generic_convert_to_tif<unsigned long>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(long).name())
    {
      generic_convert_to_tif<long>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(float).name())
    {
      generic_convert_to_tif<float>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(double).name())
    {
      generic_convert_to_tif<double>(parseResult, tempFilename);
    }
  else
    {
      itkExceptionMacro("This appication doesn't support image pixel type " << componentTypeInfo);
      return EXIT_FAILURE;
    }

  // Keyword list to initialize image writers with.
   ossimKeywordlist kwl;
   const char* PREFIX = "imagewriter.";
   // Define the output file type
   const ossimString output_type("general_raster_bsq_envi");
   kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true);

   // Get an image handler for the input file.
   ossimRefPtr<ossimImageHandler> ih = ossimImageHandlerRegistry::instance()->open(tempFilename);

   // Initialize the
   if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)
   {
     itkExceptionMacro("Error reading image:  " << input_file << "Exiting application...");
     return EXIT_FAILURE;
   }

   ih->initialize();

   ossimRefPtr<ossimImageSource> source = ih.get();
   ossimRefPtr<ossimBandSelector> bs = 0;

   // Get the image rectangle for the rrLevel selected.
   ossimIrect output_rect;
   output_rect = source->getBoundingRect(0);

   ossimRefPtr<ossimImageFileWriter> writer =
     ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX);

   writer->connectMyInputTo(0, source.get());
   writer->open(ossimFilename(parseResult->GetParameterString("OutputPath"))+".ras");

   // Add a listener to get percent complete.
   ossimStdOutProgress prog(0, true);
   writer->addListener(&prog);

   if (writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK)
   {
      if( (ih->getOutputScalarType() != OSSIM_UCHAR) &&
          (PTR_CAST(ossimJpegWriter, writer.get()) ) )
      {
         writer->setScaleToEightBitFlag(true);
      }

      ossimRefPtr<ossimCacheTileSource> cache = new ossimCacheTileSource;
      ossimIpt tileWidthHeight(ih->getImageTileWidth(),
                               ih->getImageTileHeight());
      // only use the cache if its stripped
      if(static_cast<ossim_uint32>(tileWidthHeight.x) ==
         ih->getBoundingRect().width())
      {
         cache->connectMyInputTo(0, source.get());
         cache->setTileSize(tileWidthHeight);
         writer->connectMyInputTo(0, cache.get());
      }
      else
      {
         writer->connectMyInputTo(0, source.get());
      }
      writer->initialize();
      writer->setAreaOfInterest(output_rect); // Set the output rectangle.

      try
      {
         writer->execute();
      }
      catch(std::exception& err)
      {
      itkExceptionMacro("Error occurs writing the ouput image: " << err);
      return EXIT_FAILURE;
      }

   }
   else
     {
       itkExceptionMacro("Error detected in the image writer...");
       return EXIT_FAILURE;
     }

   if ( parseResult->IsOptionPresent("KeepTif") == false)
     {
       bool resRemove = tempFilename.remove();
       if( resRemove == false )
         {
           std::cout<<"Enable to erase the output temporary file "<<tempFilename<<"."<<std::endl;
         }
     }

   return EXIT_SUCCESS;
}

} // namespace otb
<commit_msg>WRG: fixed DEMConvert.cxx warning<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

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

 =========================================================================*/

#include "otbDEMConvert.h"

#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"

// OSSIM include
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimStdOutProgress.h>
#include <ossim/base/ossimFilename.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/imaging/ossimJpegWriter.h>
#include <ossim/imaging/ossimImageHandler.h>
#include <ossim/imaging/ossimImageSource.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>
#include <ossim/imaging/ossimImageWriterFactoryRegistry.h>
#include <ossim/imaging/ossimImageWriterFactory.h>
#include <ossim/imaging/ossimImageFileWriter.h>
#include <ossim/imaging/ossimCacheTileSource.h>
#include <ossim/imaging/ossimBandSelector.h>
#include <ossim/imaging/ossimCibCadrgTileSource.h>

namespace otb
{

template<typename TPixelType>
int generic_convert_to_tif(otb::ApplicationOptionsResult* parseResult, ossimFilename tempFilename)
{
  typedef otb::VectorImage<TPixelType>              ImageType;
  typedef otb::ImageFileReader<ImageType>          ReaderType;
  typedef otb::StreamingImageFileWriter<ImageType> WriterType;

  typename ReaderType::Pointer reader = ReaderType::New();
  typename WriterType::Pointer writer = WriterType::New();

  reader->SetFileName(parseResult->GetInputImage().c_str());
  writer->SetFileName(tempFilename);

  writer->SetInput(reader->GetOutput());
  writer->Update();

  return EXIT_SUCCESS;
}

int DEMConvert::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("DEMConvertApplication");
  descriptor->SetDescription("Convert a DEM file into a general raster (.ras, .geom and .omd). To be used, those files have to be in a stand alone directory");
  descriptor->AddInputImage();
  descriptor->AddOption("OutputPath", "The filename (or path filename) of the output. It generates a Output.geom, Output.omd and Output.ras file.","out", 1, true,ApplicationDescriptor::String);
  descriptor->AddOption("KeepTif", "Keep the temporary generate tif file.","ktif", 0, false,ApplicationDescriptor::Boolean);

  return EXIT_SUCCESS;
}

/* The main is simple : read image using OTB and write it as a tif.
* Read this tif using OSSIM and convert it as a general raster file (.ras, .geom and . omd)
* first write the image as a tif (supported by OSSIM) allows to not only be abble to work
* with OSSIM supported format but any more.
*/

int DEMConvert::Execute(otb::ApplicationOptionsResult* parseResult)
{
  // Load input and output filename
  const char * input_file = parseResult->GetInputImage().c_str();

  ossimFilename tempFilename(parseResult->GetParameterString("OutputPath"));
  tempFilename += "_DEMConvert.tif";

  // Search for the input
  typedef otb::VectorImage<double, 2> InputImageType;
  typedef otb::ImageFileReader<InputImageType> ReaderType;
  ReaderType::Pointer reader=ReaderType::New();
  reader->SetFileName(input_file);
  reader->UpdateOutputInformation();

  // Generate the tif image using OTB
  // We keep the same pixel type
  std::string componentTypeInfo(reader->GetImageIO()->GetComponentTypeInfo().name());
  if( componentTypeInfo == typeid(unsigned char).name())
    {
      generic_convert_to_tif<unsigned char>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(char).name())
    {
      generic_convert_to_tif<char>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(unsigned short).name())
    {
      generic_convert_to_tif<unsigned short>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(short).name())
    {
      generic_convert_to_tif<short>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(unsigned int).name())
    {
      generic_convert_to_tif<unsigned int>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(int).name())
    {
      generic_convert_to_tif<int>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(unsigned long).name())
    {
      generic_convert_to_tif<unsigned long>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(long).name())
    {
      generic_convert_to_tif<long>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(float).name())
    {
      generic_convert_to_tif<float>(parseResult, tempFilename);
    }
  else if( componentTypeInfo == typeid(double).name())
    {
      generic_convert_to_tif<double>(parseResult, tempFilename);
    }
  else
    {
      itkExceptionMacro("This appication doesn't support image pixel type " << componentTypeInfo);
      return EXIT_FAILURE;
    }

  // Keyword list to initialize image writers with.
   ossimKeywordlist kwl;
   const char* PREFIX = "imagewriter.";
   // Define the output file type
   const ossimString output_type("general_raster_bsq_envi");
   kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true);

   // Get an image handler for the input file.
   ossimRefPtr<ossimImageHandler> ih = ossimImageHandlerRegistry::instance()->open(tempFilename);

   // Initialize the
   if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)
   {
     itkExceptionMacro("Error reading image:  " << input_file << "Exiting application...");
     return EXIT_FAILURE;
   }

   ih->initialize();

   ossimRefPtr<ossimImageSource> source = ih.get();
   ossimRefPtr<ossimBandSelector> bs = 0;

   // Get the image rectangle for the rrLevel selected.
   ossimIrect output_rect;
   output_rect = source->getBoundingRect(0);

   ossimRefPtr<ossimImageFileWriter> writer =
     ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX);

   writer->connectMyInputTo(0, source.get());
   writer->open(ossimFilename(parseResult->GetParameterString("OutputPath"))+".ras");

   // Add a listener to get percent complete.
   ossimStdOutProgress prog(0, true);
   writer->addListener(&prog);

   if (writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK)
   {
      if( (ih->getOutputScalarType() != OSSIM_UCHAR) &&
          (PTR_CAST(ossimJpegWriter, writer.get()) ) )
      {
         writer->setScaleToEightBitFlag(true);
      }

      ossimRefPtr<ossimCacheTileSource> cache = new ossimCacheTileSource;
      ossimIpt tileWidthHeight(ih->getImageTileWidth(),
                               ih->getImageTileHeight());
      // only use the cache if its stripped
      if(static_cast<ossim_uint32>(tileWidthHeight.x) ==
         ih->getBoundingRect().width())
      {
         cache->connectMyInputTo(0, source.get());
         cache->setTileSize(tileWidthHeight);
         writer->connectMyInputTo(0, cache.get());
      }
      else
      {
         writer->connectMyInputTo(0, source.get());
      }
      writer->initialize();
      writer->setAreaOfInterest(output_rect); // Set the output rectangle.

      try
      {
         writer->execute();
      }
      catch(std::exception& e)
      {
      std::cerr << "std::exception  thrown:" << std::endl;
      std::cerr << e.what() <<  std::endl;
      itkExceptionMacro("Error occurs writing the ouput image...");
      return EXIT_FAILURE;
      }

   }
   else
     {
       itkExceptionMacro("Error detected in the image writer...");
       return EXIT_FAILURE;
     }

   if ( parseResult->IsOptionPresent("KeepTif") == false)
     {
       bool resRemove = tempFilename.remove();
       if( resRemove == false )
         {
           std::cout<<"Enable to erase the output temporary file "<<tempFilename<<"."<<std::endl;
         }
     }

   return EXIT_SUCCESS;
}

} // namespace otb
<|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 "ash/wm/shelf_layout_manager.h"

#include "ash/launcher/launcher.h"
#include "ash/screen_ash.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "base/auto_reset.h"
#include "ui/aura/event.h"
#include "ui/aura/event_filter.h"
#include "ui/aura/root_window.h"
#include "ui/gfx/compositor/layer.h"
#include "ui/gfx/compositor/layer_animation_observer.h"
#include "ui/gfx/compositor/layer_animator.h"
#include "ui/gfx/compositor/scoped_layer_animation_settings.h"
#include "ui/views/widget/widget.h"

namespace ash {
namespace internal {

namespace {

// Delay before showing/hiding the launcher after the mouse enters the launcher.
const int kAutoHideDelayMS = 300;

ui::Layer* GetLayer(views::Widget* widget) {
  return widget->GetNativeView()->layer();
}

}  // namespace

// static
const int ShelfLayoutManager::kWorkspaceAreaBottomInset = 2;

// static
const int ShelfLayoutManager::kAutoHideHeight = 2;

// Notifies ShelfLayoutManager any time the mouse moves.
class ShelfLayoutManager::AutoHideEventFilter : public aura::EventFilter {
 public:
  explicit AutoHideEventFilter(ShelfLayoutManager* shelf);
  virtual ~AutoHideEventFilter();

  // Overridden from aura::EventFilter:
  virtual bool PreHandleKeyEvent(aura::Window* target,
                                 aura::KeyEvent* event) OVERRIDE;
  virtual bool PreHandleMouseEvent(aura::Window* target,
                                   aura::MouseEvent* event) OVERRIDE;
  virtual ui::TouchStatus PreHandleTouchEvent(aura::Window* target,
                                              aura::TouchEvent* event) OVERRIDE;
  virtual ui::GestureStatus PreHandleGestureEvent(
      aura::Window* target,
      aura::GestureEvent* event) OVERRIDE;

 private:
  ShelfLayoutManager* shelf_;

  DISALLOW_COPY_AND_ASSIGN(AutoHideEventFilter);
};

ShelfLayoutManager::AutoHideEventFilter::AutoHideEventFilter(
    ShelfLayoutManager* shelf)
    : shelf_(shelf) {
  Shell::GetInstance()->AddRootWindowEventFilter(this);
}

ShelfLayoutManager::AutoHideEventFilter::~AutoHideEventFilter() {
  Shell::GetInstance()->RemoveRootWindowEventFilter(this);
}

bool ShelfLayoutManager::AutoHideEventFilter::PreHandleKeyEvent(
    aura::Window* target,
    aura::KeyEvent* event) {
  return false;  // Always let the event propagate.
}

bool ShelfLayoutManager::AutoHideEventFilter::PreHandleMouseEvent(
    aura::Window* target,
    aura::MouseEvent* event) {
  if (event->type() == ui::ET_MOUSE_MOVED)
    shelf_->UpdateAutoHideState();
  return false;  // Not handled.
}

ui::TouchStatus ShelfLayoutManager::AutoHideEventFilter::PreHandleTouchEvent(
    aura::Window* target,
    aura::TouchEvent* event) {
  return ui::TOUCH_STATUS_UNKNOWN;  // Not handled.
}

ui::GestureStatus
ShelfLayoutManager::AutoHideEventFilter::PreHandleGestureEvent(
    aura::Window* target,
    aura::GestureEvent* event) {
  return ui::GESTURE_STATUS_UNKNOWN;  // Not handled.
}

////////////////////////////////////////////////////////////////////////////////
// ShelfLayoutManager, public:

ShelfLayoutManager::ShelfLayoutManager(views::Widget* status)
    : in_layout_(false),
      shelf_height_(status->GetWindowScreenBounds().height()),
      launcher_(NULL),
      status_(status),
      window_overlaps_shelf_(false) {
}

ShelfLayoutManager::~ShelfLayoutManager() {
}

gfx::Rect ShelfLayoutManager::GetMaximizedWindowBounds(
    aura::Window* window) const {
  // TODO: needs to be multi-mon aware.
  gfx::Rect bounds(gfx::Screen::GetMonitorAreaNearestWindow(window));
  bounds.set_height(bounds.height() - kAutoHideHeight);
  return bounds;
}

gfx::Rect ShelfLayoutManager::GetUnmaximizedWorkAreaBounds(
    aura::Window* window) const {
  // TODO: needs to be multi-mon aware.
  gfx::Rect bounds(gfx::Screen::GetMonitorAreaNearestWindow(window));
  bounds.set_height(bounds.height() - shelf_height_ -
                    kWorkspaceAreaBottomInset);
  return bounds;
}

void ShelfLayoutManager::SetLauncher(Launcher* launcher) {
  if (launcher == launcher_)
    return;

  launcher_ = launcher;
  shelf_height_ =
      std::max(status_->GetWindowScreenBounds().height(),
               launcher_widget()->GetWindowScreenBounds().height());
  LayoutShelf();
}

void ShelfLayoutManager::LayoutShelf() {
  AutoReset<bool> auto_reset_in_layout(&in_layout_, true);
  StopAnimating();
  TargetBounds target_bounds;
  CalculateTargetBounds(state_, &target_bounds);
  if (launcher_widget()) {
    GetLayer(launcher_widget())->SetOpacity(target_bounds.opacity);
    launcher_widget()->SetBounds(target_bounds.launcher_bounds);
    launcher_->SetStatusWidth(
        target_bounds.status_bounds.width());
  }
  GetLayer(status_)->SetOpacity(target_bounds.opacity);
  status_->SetBounds(target_bounds.status_bounds);
  Shell::GetInstance()->SetMonitorWorkAreaInsets(
      Shell::GetRootWindow(),
      target_bounds.work_area_insets);
}

void ShelfLayoutManager::SetState(VisibilityState visibility_state) {
  State state;
  state.visibility_state = visibility_state;
  state.auto_hide_state = CalculateAutoHideState(visibility_state);

  if (state_.Equals(state))
    return;  // Nothing changed.

  if (state.visibility_state == AUTO_HIDE) {
    // When state is AUTO_HIDE we need to track when the mouse is over the
    // launcher to unhide the shelf. AutoHideEventFilter does that for us.
    if (!event_filter_.get())
      event_filter_.reset(new AutoHideEventFilter(this));
  } else {
    event_filter_.reset(NULL);
  }

  auto_hide_timer_.Stop();

  // Animating the background when transitioning from auto-hide & hidden to
  // visibile is janking. Update the background immediately in this case.
  internal::BackgroundAnimator::ChangeType change_type =
      (state_.visibility_state == AUTO_HIDE &&
       state_.auto_hide_state == AUTO_HIDE_HIDDEN &&
       state.visibility_state == VISIBLE) ?
      internal::BackgroundAnimator::CHANGE_IMMEDIATE :
      internal::BackgroundAnimator::CHANGE_ANIMATE;
  StopAnimating();
  state_ = state;
  TargetBounds target_bounds;
  CalculateTargetBounds(state_, &target_bounds);
  if (launcher_widget()) {
    ui::ScopedLayerAnimationSettings launcher_animation_setter(
        GetLayer(launcher_widget())->GetAnimator());
    launcher_animation_setter.SetTransitionDuration(
        base::TimeDelta::FromMilliseconds(130));
    launcher_animation_setter.SetTweenType(ui::Tween::EASE_OUT);
    GetLayer(launcher_widget())->SetBounds(target_bounds.launcher_bounds);
    GetLayer(launcher_widget())->SetOpacity(target_bounds.opacity);
  }
  ui::ScopedLayerAnimationSettings status_animation_setter(
      GetLayer(status_)->GetAnimator());
  status_animation_setter.SetTransitionDuration(
      base::TimeDelta::FromMilliseconds(130));
  status_animation_setter.SetTweenType(ui::Tween::EASE_OUT);
  GetLayer(status_)->SetBounds(target_bounds.status_bounds);
  GetLayer(status_)->SetOpacity(target_bounds.opacity);
  Shell::GetInstance()->SetMonitorWorkAreaInsets(
      Shell::GetRootWindow(),
      target_bounds.work_area_insets);
  UpdateShelfBackground(change_type);
}

void ShelfLayoutManager::UpdateAutoHideState() {
  if (CalculateAutoHideState(state_.visibility_state) !=
      state_.auto_hide_state) {
    // Don't change state immediately. Instead delay for a bit.
    if (!auto_hide_timer_.IsRunning()) {
      auto_hide_timer_.Start(
          FROM_HERE,
          base::TimeDelta::FromMilliseconds(kAutoHideDelayMS),
          this, &ShelfLayoutManager::UpdateAutoHideStateNow);
    }
  } else {
    auto_hide_timer_.Stop();
  }
}

void ShelfLayoutManager::SetWindowOverlapsShelf(bool value) {
  window_overlaps_shelf_ = value;
  UpdateShelfBackground(internal::BackgroundAnimator::CHANGE_ANIMATE);
}

////////////////////////////////////////////////////////////////////////////////
// ShelfLayoutManager, aura::LayoutManager implementation:

void ShelfLayoutManager::OnWindowResized() {
  LayoutShelf();
}

void ShelfLayoutManager::OnWindowAddedToLayout(aura::Window* child) {
}

void ShelfLayoutManager::OnWillRemoveWindowFromLayout(aura::Window* child) {
}

void ShelfLayoutManager::OnChildWindowVisibilityChanged(aura::Window* child,
                                                        bool visible) {
}

void ShelfLayoutManager::SetChildBounds(aura::Window* child,
                                        const gfx::Rect& requested_bounds) {
  SetChildBoundsDirect(child, requested_bounds);
  if (!in_layout_)
    LayoutShelf();
}

////////////////////////////////////////////////////////////////////////////////
// ShelfLayoutManager, private:

void ShelfLayoutManager::StopAnimating() {
  if (launcher_widget())
    GetLayer(launcher_widget())->GetAnimator()->StopAnimating();
  GetLayer(status_)->GetAnimator()->StopAnimating();
}

void ShelfLayoutManager::CalculateTargetBounds(
    const State& state,
    TargetBounds* target_bounds) const {
  const gfx::Rect& available_bounds(
      status_->GetNativeView()->GetRootWindow()->bounds());
  int y = available_bounds.bottom();
  int shelf_height = 0;
  int work_area_delta = 0;
  if (state.visibility_state == VISIBLE ||
      (state.visibility_state == AUTO_HIDE &&
       state.auto_hide_state == AUTO_HIDE_SHOWN)) {
    shelf_height = shelf_height_;
    work_area_delta = kWorkspaceAreaBottomInset;
  } else if (state.visibility_state == AUTO_HIDE &&
             state.auto_hide_state == AUTO_HIDE_HIDDEN) {
    shelf_height = kAutoHideHeight;
  }
  y -= shelf_height;
  gfx::Rect status_bounds(status_->GetWindowScreenBounds());
  // The status widget should extend to the bottom and right edges.
  target_bounds->status_bounds = gfx::Rect(
      available_bounds.right() - status_bounds.width(),
      y + shelf_height_ - status_bounds.height(),
      status_bounds.width(), status_bounds.height());
  if (launcher_widget()) {
    gfx::Rect launcher_bounds(launcher_widget()->GetWindowScreenBounds());
    target_bounds->launcher_bounds = gfx::Rect(
        available_bounds.x(),
        y + (shelf_height_ - launcher_bounds.height()) / 2,
        available_bounds.width(),
        launcher_bounds.height());
  }
  target_bounds->opacity =
      (state.visibility_state == VISIBLE ||
       state.visibility_state == AUTO_HIDE) ? 1.0f : 0.0f;
  target_bounds->work_area_insets =
      gfx::Insets(0, 0, shelf_height + work_area_delta, 0);
}

void ShelfLayoutManager::UpdateShelfBackground(
    BackgroundAnimator::ChangeType type) {
  bool launcher_paints = GetLauncherPaintsBackground();
  if (launcher_)
    launcher_->SetPaintsBackground(launcher_paints, type);
  // SystemTray normally draws a background, but we don't want it to draw a
  // background when the launcher does.
  Shell::GetInstance()->tray()->SetPaintsBackground(!launcher_paints, type);
}

bool ShelfLayoutManager::GetLauncherPaintsBackground() const {
  return window_overlaps_shelf_ || state_.visibility_state == AUTO_HIDE;
}

void ShelfLayoutManager::UpdateAutoHideStateNow() {
  SetState(state_.visibility_state);
}

ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState(
    VisibilityState visibility_state) const {
  if (visibility_state != AUTO_HIDE || !launcher_widget())
    return AUTO_HIDE_HIDDEN;

  Shell* shell = Shell::GetInstance();
  if (shell->tray()->showing_bubble())
    return AUTO_HIDE_SHOWN;  // Always show if a bubble is open from the shelf.

  aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow();
  bool mouse_over_launcher =
      launcher_widget()->GetWindowScreenBounds().Contains(
          root->last_mouse_location());
  return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN;
}

}  // namespace internal
}  // namespace ash
<commit_msg>ash: Fix crash when using --disable-ash-uber-tray.<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 "ash/wm/shelf_layout_manager.h"

#include "ash/launcher/launcher.h"
#include "ash/screen_ash.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "base/auto_reset.h"
#include "ui/aura/event.h"
#include "ui/aura/event_filter.h"
#include "ui/aura/root_window.h"
#include "ui/gfx/compositor/layer.h"
#include "ui/gfx/compositor/layer_animation_observer.h"
#include "ui/gfx/compositor/layer_animator.h"
#include "ui/gfx/compositor/scoped_layer_animation_settings.h"
#include "ui/views/widget/widget.h"

namespace ash {
namespace internal {

namespace {

// Delay before showing/hiding the launcher after the mouse enters the launcher.
const int kAutoHideDelayMS = 300;

ui::Layer* GetLayer(views::Widget* widget) {
  return widget->GetNativeView()->layer();
}

}  // namespace

// static
const int ShelfLayoutManager::kWorkspaceAreaBottomInset = 2;

// static
const int ShelfLayoutManager::kAutoHideHeight = 2;

// Notifies ShelfLayoutManager any time the mouse moves.
class ShelfLayoutManager::AutoHideEventFilter : public aura::EventFilter {
 public:
  explicit AutoHideEventFilter(ShelfLayoutManager* shelf);
  virtual ~AutoHideEventFilter();

  // Overridden from aura::EventFilter:
  virtual bool PreHandleKeyEvent(aura::Window* target,
                                 aura::KeyEvent* event) OVERRIDE;
  virtual bool PreHandleMouseEvent(aura::Window* target,
                                   aura::MouseEvent* event) OVERRIDE;
  virtual ui::TouchStatus PreHandleTouchEvent(aura::Window* target,
                                              aura::TouchEvent* event) OVERRIDE;
  virtual ui::GestureStatus PreHandleGestureEvent(
      aura::Window* target,
      aura::GestureEvent* event) OVERRIDE;

 private:
  ShelfLayoutManager* shelf_;

  DISALLOW_COPY_AND_ASSIGN(AutoHideEventFilter);
};

ShelfLayoutManager::AutoHideEventFilter::AutoHideEventFilter(
    ShelfLayoutManager* shelf)
    : shelf_(shelf) {
  Shell::GetInstance()->AddRootWindowEventFilter(this);
}

ShelfLayoutManager::AutoHideEventFilter::~AutoHideEventFilter() {
  Shell::GetInstance()->RemoveRootWindowEventFilter(this);
}

bool ShelfLayoutManager::AutoHideEventFilter::PreHandleKeyEvent(
    aura::Window* target,
    aura::KeyEvent* event) {
  return false;  // Always let the event propagate.
}

bool ShelfLayoutManager::AutoHideEventFilter::PreHandleMouseEvent(
    aura::Window* target,
    aura::MouseEvent* event) {
  if (event->type() == ui::ET_MOUSE_MOVED)
    shelf_->UpdateAutoHideState();
  return false;  // Not handled.
}

ui::TouchStatus ShelfLayoutManager::AutoHideEventFilter::PreHandleTouchEvent(
    aura::Window* target,
    aura::TouchEvent* event) {
  return ui::TOUCH_STATUS_UNKNOWN;  // Not handled.
}

ui::GestureStatus
ShelfLayoutManager::AutoHideEventFilter::PreHandleGestureEvent(
    aura::Window* target,
    aura::GestureEvent* event) {
  return ui::GESTURE_STATUS_UNKNOWN;  // Not handled.
}

////////////////////////////////////////////////////////////////////////////////
// ShelfLayoutManager, public:

ShelfLayoutManager::ShelfLayoutManager(views::Widget* status)
    : in_layout_(false),
      shelf_height_(status->GetWindowScreenBounds().height()),
      launcher_(NULL),
      status_(status),
      window_overlaps_shelf_(false) {
}

ShelfLayoutManager::~ShelfLayoutManager() {
}

gfx::Rect ShelfLayoutManager::GetMaximizedWindowBounds(
    aura::Window* window) const {
  // TODO: needs to be multi-mon aware.
  gfx::Rect bounds(gfx::Screen::GetMonitorAreaNearestWindow(window));
  bounds.set_height(bounds.height() - kAutoHideHeight);
  return bounds;
}

gfx::Rect ShelfLayoutManager::GetUnmaximizedWorkAreaBounds(
    aura::Window* window) const {
  // TODO: needs to be multi-mon aware.
  gfx::Rect bounds(gfx::Screen::GetMonitorAreaNearestWindow(window));
  bounds.set_height(bounds.height() - shelf_height_ -
                    kWorkspaceAreaBottomInset);
  return bounds;
}

void ShelfLayoutManager::SetLauncher(Launcher* launcher) {
  if (launcher == launcher_)
    return;

  launcher_ = launcher;
  shelf_height_ =
      std::max(status_->GetWindowScreenBounds().height(),
               launcher_widget()->GetWindowScreenBounds().height());
  LayoutShelf();
}

void ShelfLayoutManager::LayoutShelf() {
  AutoReset<bool> auto_reset_in_layout(&in_layout_, true);
  StopAnimating();
  TargetBounds target_bounds;
  CalculateTargetBounds(state_, &target_bounds);
  if (launcher_widget()) {
    GetLayer(launcher_widget())->SetOpacity(target_bounds.opacity);
    launcher_widget()->SetBounds(target_bounds.launcher_bounds);
    launcher_->SetStatusWidth(
        target_bounds.status_bounds.width());
  }
  GetLayer(status_)->SetOpacity(target_bounds.opacity);
  status_->SetBounds(target_bounds.status_bounds);
  Shell::GetInstance()->SetMonitorWorkAreaInsets(
      Shell::GetRootWindow(),
      target_bounds.work_area_insets);
}

void ShelfLayoutManager::SetState(VisibilityState visibility_state) {
  State state;
  state.visibility_state = visibility_state;
  state.auto_hide_state = CalculateAutoHideState(visibility_state);

  if (state_.Equals(state))
    return;  // Nothing changed.

  if (state.visibility_state == AUTO_HIDE) {
    // When state is AUTO_HIDE we need to track when the mouse is over the
    // launcher to unhide the shelf. AutoHideEventFilter does that for us.
    if (!event_filter_.get())
      event_filter_.reset(new AutoHideEventFilter(this));
  } else {
    event_filter_.reset(NULL);
  }

  auto_hide_timer_.Stop();

  // Animating the background when transitioning from auto-hide & hidden to
  // visibile is janking. Update the background immediately in this case.
  internal::BackgroundAnimator::ChangeType change_type =
      (state_.visibility_state == AUTO_HIDE &&
       state_.auto_hide_state == AUTO_HIDE_HIDDEN &&
       state.visibility_state == VISIBLE) ?
      internal::BackgroundAnimator::CHANGE_IMMEDIATE :
      internal::BackgroundAnimator::CHANGE_ANIMATE;
  StopAnimating();
  state_ = state;
  TargetBounds target_bounds;
  CalculateTargetBounds(state_, &target_bounds);
  if (launcher_widget()) {
    ui::ScopedLayerAnimationSettings launcher_animation_setter(
        GetLayer(launcher_widget())->GetAnimator());
    launcher_animation_setter.SetTransitionDuration(
        base::TimeDelta::FromMilliseconds(130));
    launcher_animation_setter.SetTweenType(ui::Tween::EASE_OUT);
    GetLayer(launcher_widget())->SetBounds(target_bounds.launcher_bounds);
    GetLayer(launcher_widget())->SetOpacity(target_bounds.opacity);
  }
  ui::ScopedLayerAnimationSettings status_animation_setter(
      GetLayer(status_)->GetAnimator());
  status_animation_setter.SetTransitionDuration(
      base::TimeDelta::FromMilliseconds(130));
  status_animation_setter.SetTweenType(ui::Tween::EASE_OUT);
  GetLayer(status_)->SetBounds(target_bounds.status_bounds);
  GetLayer(status_)->SetOpacity(target_bounds.opacity);
  Shell::GetInstance()->SetMonitorWorkAreaInsets(
      Shell::GetRootWindow(),
      target_bounds.work_area_insets);
  UpdateShelfBackground(change_type);
}

void ShelfLayoutManager::UpdateAutoHideState() {
  if (CalculateAutoHideState(state_.visibility_state) !=
      state_.auto_hide_state) {
    // Don't change state immediately. Instead delay for a bit.
    if (!auto_hide_timer_.IsRunning()) {
      auto_hide_timer_.Start(
          FROM_HERE,
          base::TimeDelta::FromMilliseconds(kAutoHideDelayMS),
          this, &ShelfLayoutManager::UpdateAutoHideStateNow);
    }
  } else {
    auto_hide_timer_.Stop();
  }
}

void ShelfLayoutManager::SetWindowOverlapsShelf(bool value) {
  window_overlaps_shelf_ = value;
  UpdateShelfBackground(internal::BackgroundAnimator::CHANGE_ANIMATE);
}

////////////////////////////////////////////////////////////////////////////////
// ShelfLayoutManager, aura::LayoutManager implementation:

void ShelfLayoutManager::OnWindowResized() {
  LayoutShelf();
}

void ShelfLayoutManager::OnWindowAddedToLayout(aura::Window* child) {
}

void ShelfLayoutManager::OnWillRemoveWindowFromLayout(aura::Window* child) {
}

void ShelfLayoutManager::OnChildWindowVisibilityChanged(aura::Window* child,
                                                        bool visible) {
}

void ShelfLayoutManager::SetChildBounds(aura::Window* child,
                                        const gfx::Rect& requested_bounds) {
  SetChildBoundsDirect(child, requested_bounds);
  if (!in_layout_)
    LayoutShelf();
}

////////////////////////////////////////////////////////////////////////////////
// ShelfLayoutManager, private:

void ShelfLayoutManager::StopAnimating() {
  if (launcher_widget())
    GetLayer(launcher_widget())->GetAnimator()->StopAnimating();
  GetLayer(status_)->GetAnimator()->StopAnimating();
}

void ShelfLayoutManager::CalculateTargetBounds(
    const State& state,
    TargetBounds* target_bounds) const {
  const gfx::Rect& available_bounds(
      status_->GetNativeView()->GetRootWindow()->bounds());
  int y = available_bounds.bottom();
  int shelf_height = 0;
  int work_area_delta = 0;
  if (state.visibility_state == VISIBLE ||
      (state.visibility_state == AUTO_HIDE &&
       state.auto_hide_state == AUTO_HIDE_SHOWN)) {
    shelf_height = shelf_height_;
    work_area_delta = kWorkspaceAreaBottomInset;
  } else if (state.visibility_state == AUTO_HIDE &&
             state.auto_hide_state == AUTO_HIDE_HIDDEN) {
    shelf_height = kAutoHideHeight;
  }
  y -= shelf_height;
  gfx::Rect status_bounds(status_->GetWindowScreenBounds());
  // The status widget should extend to the bottom and right edges.
  target_bounds->status_bounds = gfx::Rect(
      available_bounds.right() - status_bounds.width(),
      y + shelf_height_ - status_bounds.height(),
      status_bounds.width(), status_bounds.height());
  if (launcher_widget()) {
    gfx::Rect launcher_bounds(launcher_widget()->GetWindowScreenBounds());
    target_bounds->launcher_bounds = gfx::Rect(
        available_bounds.x(),
        y + (shelf_height_ - launcher_bounds.height()) / 2,
        available_bounds.width(),
        launcher_bounds.height());
  }
  target_bounds->opacity =
      (state.visibility_state == VISIBLE ||
       state.visibility_state == AUTO_HIDE) ? 1.0f : 0.0f;
  target_bounds->work_area_insets =
      gfx::Insets(0, 0, shelf_height + work_area_delta, 0);
}

void ShelfLayoutManager::UpdateShelfBackground(
    BackgroundAnimator::ChangeType type) {
  bool launcher_paints = GetLauncherPaintsBackground();
  if (launcher_)
    launcher_->SetPaintsBackground(launcher_paints, type);
  // SystemTray normally draws a background, but we don't want it to draw a
  // background when the launcher does.
  if (Shell::GetInstance()->tray())
    Shell::GetInstance()->tray()->SetPaintsBackground(!launcher_paints, type);
}

bool ShelfLayoutManager::GetLauncherPaintsBackground() const {
  return window_overlaps_shelf_ || state_.visibility_state == AUTO_HIDE;
}

void ShelfLayoutManager::UpdateAutoHideStateNow() {
  SetState(state_.visibility_state);
}

ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState(
    VisibilityState visibility_state) const {
  if (visibility_state != AUTO_HIDE || !launcher_widget())
    return AUTO_HIDE_HIDDEN;

  Shell* shell = Shell::GetInstance();
  if (shell->tray() && shell->tray()->showing_bubble())
    return AUTO_HIDE_SHOWN;  // Always show if a bubble is open from the shelf.

  aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow();
  bool mouse_over_launcher =
      launcher_widget()->GetWindowScreenBounds().Contains(
          root->last_mouse_location());
  return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN;
}

}  // namespace internal
}  // namespace ash
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
#ifndef _SD_IMPRESSREMOTE_RECEIVER_HXX
#define _SD_IMPRESSREMOTE_RECEIVER_HXX

#include <com/sun/star/presentation/XSlideShowListener.hpp>
#include <com/sun/star/presentation/XSlideShowController.hpp>
#include <com/sun/star/presentation/XPresentationSupplier.hpp>
#include <com/sun/star/presentation/XPresentation.hpp>
#include <com/sun/star/presentation/XPresentation2.hpp>
#include <osl/socket.hxx>
#include <stdlib.h>
#include <glib-object.h>
#include <json-glib/json-glib.h>

using namespace com::sun::star::presentation;
using namespace com::sun::star::uno;
namespace sd
{

class Receiver
{
public:
    Receiver();
    ~Receiver();
    void parseCommand( const char* aCommand, sal_Int32 size, osl::StreamSocket &aSocket );

private:
    void executeCommand( JsonObject *aObject, Reference<XSlideShowController> aController );

};

}

Sequence<sal_Int8> preparePreview(sal_uInt32 aSlideNumber, Reference<XSlideShowController> xSlideShowController, sal_uInt32 aWidth, sal_uInt32 aHeight, sal_uInt64 &aSize );

void sendPreview(sal_uInt32 aSlideNumber, Reference<XSlideShowController> xSlideShowController, osl::StreamSocket &mStreamSocket );

#endif // _SD_IMPRESSREMOTE_RECEIVER_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */<commit_msg>namespacing / compile fixing<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
#ifndef _SD_IMPRESSREMOTE_RECEIVER_HXX
#define _SD_IMPRESSREMOTE_RECEIVER_HXX

#include <com/sun/star/presentation/XSlideShowListener.hpp>
#include <com/sun/star/presentation/XSlideShowController.hpp>
#include <com/sun/star/presentation/XPresentationSupplier.hpp>
#include <com/sun/star/presentation/XPresentation.hpp>
#include <com/sun/star/presentation/XPresentation2.hpp>
#include <osl/socket.hxx>
#include <stdlib.h>
#include <glib-object.h>
#include <json-glib/json-glib.h>

namespace css = ::com::sun::star;

namespace sd
{

class Receiver
{
public:
    Receiver();
    ~Receiver();
    void parseCommand( const char* aCommand, sal_Int32 size, osl::StreamSocket &aSocket );

private:
    void executeCommand( JsonObject *aObject, css::uno::Reference<css::presentation::XSlideShowController> aController );

};

}

css::uno::Sequence<sal_Int8> preparePreview(sal_uInt32 aSlideNumber, css::uno::Reference<css::presentation::XSlideShowController> xSlideShowController, sal_uInt32 aWidth, sal_uInt32 aHeight, sal_uInt64 &aSize );

void sendPreview(sal_uInt32 aSlideNumber, css::uno::Reference<css::presentation::XSlideShowController> xSlideShowController, osl::StreamSocket &mStreamSocket );

#endif // _SD_IMPRESSREMOTE_RECEIVER_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "CameraFeed.h"
#include "Misc/Video.h"
#include "Vision/VisionAPI.h"

CameraFeed::CameraFeed()
	: image(frcCreateImage(IMAQ_IMAGE_RGB))
{
	// Use Requires() here to declare subsystem dependencies
	// eg. Requires(chassis);
	SetRunWhenDisabled(true);
}

// Called just before this Command runs the first time
void CameraFeed::Initialize()
{
	if (RobotVideo* video = RobotVideo::GetInstance()) {
		video->SetHeadingQueueSize(0);
		video->SetLocationQueueSize(0);
		video->Enable();
	}
}

// Called repeatedly when this Command is scheduled to run
void CameraFeed::Execute()
{
	if (RobotVideo* video = RobotVideo::GetInstance()) {
		if(!video->m_display) {
			frcReadImage(image,RobotVideo::IMG_FILE_NAME);
			CameraServer::GetInstance()->SetImage(image);
			//frcDispose(image);
			video->m_display = true;
		}

		float turnL = 0;
		float distL = 0;
		float turnR = 0;
		float distR = 0;
		size_t nTurns = 0;

		RobotVideo::GetInstance()->mutex_lock();
		nTurns = RobotVideo::GetInstance()->HaveHeading();
		if(nTurns > 0) {
			turnL = RobotVideo::GetInstance()->GetTurn(0);
			distL = RobotVideo::GetInstance()->GetDistance(0);
		}
		if(nTurns > 1) {
			turnR = RobotVideo::GetInstance()->GetTurn(1);
			distR = RobotVideo::GetInstance()->GetDistance(1);
		}
		RobotVideo::GetInstance()->mutex_unlock();

		if (nTurns > 0) {
			SmartDashboard::PutBoolean("FeedLeft", true);
			SmartDashboard::PutNumber("FeedDistL", distL);
			SmartDashboard::PutNumber("FeedTurnL", turnL);
			if (nTurns > 1) {
				SmartDashboard::PutBoolean("FeedRight", true);
				SmartDashboard::PutNumber("FeedDistR", distR);
				SmartDashboard::PutNumber("FeedTurnL", turnR);
			}
			else {
				SmartDashboard::PutBoolean("FeedRight", false);
				SmartDashboard::PutNumber("FeedDistR", 0);
				SmartDashboard::PutNumber("FeedTurnL", 0);
			}
		}
		else {
			SmartDashboard::PutBoolean("FeedLeft", false);
			SmartDashboard::PutNumber("FeedDistL", 0);
			SmartDashboard::PutNumber("FeedTurnL", 0);
		}

	}
}

// Make this return true when this Command no longer needs to run execute()
bool CameraFeed::IsFinished()
{
	return false;
}

// Called once after isFinished returns true
void CameraFeed::End()
{
	if (RobotVideo* video = RobotVideo::GetInstance()) {
		video->Disable();
	}
}

// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void CameraFeed::Interrupted()
{
	End();
}
<commit_msg>Poorman's camera feed - fix copy-paste artifacts<commit_after>#include "CameraFeed.h"
#include "Misc/Video.h"
#include "Vision/VisionAPI.h"

CameraFeed::CameraFeed()
	: image(frcCreateImage(IMAQ_IMAGE_RGB))
{
	// Use Requires() here to declare subsystem dependencies
	// eg. Requires(chassis);
	SetRunWhenDisabled(true);
}

// Called just before this Command runs the first time
void CameraFeed::Initialize()
{
	if (RobotVideo* video = RobotVideo::GetInstance()) {
		video->SetHeadingQueueSize(0);
		video->SetLocationQueueSize(0);
		video->Enable();
	}
}

// Called repeatedly when this Command is scheduled to run
void CameraFeed::Execute()
{
	if (RobotVideo* video = RobotVideo::GetInstance()) {
		if(!video->m_display) {
			frcReadImage(image,RobotVideo::IMG_FILE_NAME);
			CameraServer::GetInstance()->SetImage(image);
			//frcDispose(image);
			video->m_display = true;
		}

		float turnL = 0;
		float distL = 0;
		float turnR = 0;
		float distR = 0;
		size_t nTurns = 0;

		RobotVideo::GetInstance()->mutex_lock();
		nTurns = RobotVideo::GetInstance()->HaveHeading();
		if(nTurns > 0) {
			turnL = RobotVideo::GetInstance()->GetTurn(0);
			distL = RobotVideo::GetInstance()->GetDistance(0);
		}
		if(nTurns > 1) {
			turnR = RobotVideo::GetInstance()->GetTurn(1);
			distR = RobotVideo::GetInstance()->GetDistance(1);
		}
		RobotVideo::GetInstance()->mutex_unlock();

		if (nTurns > 0) {
			SmartDashboard::PutBoolean("FeedLeft", true);
			SmartDashboard::PutNumber("FeedDistL", distL);
			SmartDashboard::PutNumber("FeedTurnL", turnL);
			if (nTurns > 1) {
				SmartDashboard::PutBoolean("FeedRight", true);
				SmartDashboard::PutNumber("FeedDistR", distR);
				SmartDashboard::PutNumber("FeedTurnR", turnR);
			}
			else {
				SmartDashboard::PutBoolean("FeedRight", false);
				SmartDashboard::PutNumber("FeedDistR", 0);
				SmartDashboard::PutNumber("FeedTurnR", 0);
			}
		}
		else {
			SmartDashboard::PutBoolean("FeedLeft", false);
			SmartDashboard::PutNumber("FeedDistL", 0);
			SmartDashboard::PutNumber("FeedTurnL", 0);
		}

	}
}

// Make this return true when this Command no longer needs to run execute()
bool CameraFeed::IsFinished()
{
	return false;
}

// Called once after isFinished returns true
void CameraFeed::End()
{
	if (RobotVideo* video = RobotVideo::GetInstance()) {
		video->Disable();
	}
}

// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void CameraFeed::Interrupted()
{
	End();
}
<|endoftext|>


<commit_before>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.

#include <emscripten.h>
#include <emscripten/html5.h>
#include "NativeWindowEm.hpp"
#include "core/Engine.hpp"

static EM_BOOL emUICallback(int eventType, const EmscriptenUiEvent* uiEvent, void* userData)
{
    if (eventType == EMSCRIPTEN_EVENT_RESIZE)
    {
        reinterpret_cast<ouzel::NativeWindowEm*>(userData)->handleResize();
        return true;
    }

    return false;
}

namespace ouzel
{
    NativeWindowEm::NativeWindowEm(const Size2& newSize,
                                   bool newFullscreen,
                                   const std::string& newTitle):
        ouzel::NativeWindow(newSize,
                            true,
                            newFullscreen,
                            true,
                            newTitle,
                            true)
    {
        emscripten_set_resize_callback(nullptr, this, 1, emUICallback);

        if (size.width <= 0.0F || size.height <= 0.0F)
        {
            int width, height, fullscreen;
            emscripten_get_canvas_size(&width, &height, &fullscreen);

            if (size.width <= 0.0F) size.width = static_cast<float>(width);
            if (size.height <= 0.0F) size.height = static_cast<float>(height);
        }
        else
            emscripten_set_canvas_size(static_cast<int>(size.width),
                                       static_cast<int>(size.height));

        if (fullscreen)
        {
            EmscriptenFullscreenStrategy s;
            s.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT;
            s.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE;
            s.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
            s.canvasResizedCallback = nullptr;
            s.canvasResizedCallbackUserData = nullptr;

            emscripten_request_fullscreen_strategy("#canvas", EM_TRUE, &s);
        }

        resolution = size;
    }

    void NativeWindowEm::setSize(const Size2& newSize)
    {
        NativeWindow::setSize(newSize);

        emscripten_set_canvas_size(static_cast<int>(newSize.width),
                                   static_cast<int>(newSize.height));
    }

    void NativeWindowEm::setFullscreen(bool newFullscreen)
    {
        NativeWindow::setFullscreen(newFullscreen);

        if (fullscreen)
        {
            EmscriptenFullscreenStrategy s;
            s.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT;
            s.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE;
            s.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
            s.canvasResizedCallback = nullptr;
            s.canvasResizedCallbackUserData = nullptr;

            emscripten_request_fullscreen_strategy("#canvas", EM_TRUE, &s);
        }
        else
            emscripten_exit_fullscreen();
    }

    void NativeWindowEm::handleResize()
    {
        int width, height, fullscreen;
        emscripten_get_canvas_size(&width, &height, &fullscreen);

        Size2 newSize(static_cast<float>(width), static_cast<float>(height));

        size = newSize;
        resolution = size;

        if (listener)
        {
            listener->onSizeChange(size);
            listener->onResolutionChange(resolution);
        }
    }
}
<commit_msg>Don't pass canvas id to emscripten_request_fullscreen_strategy Add fullscreen callback<commit_after>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.

#include <emscripten.h>
#include <emscripten/html5.h>
#include "NativeWindowEm.hpp"
#include "core/Engine.hpp"

static EM_BOOL emResizeCallback(int eventType, const EmscriptenUiEvent* uiEvent, void* userData)
{
    if (eventType == EMSCRIPTEN_EVENT_RESIZE)
    {
        reinterpret_cast<ouzel::NativeWindowEm*>(userData)->handleResize();
        return true;
    }

    return false;
}

static EM_BOOL emFullscreenCallback(int eventType, const void*, void* userData)
{
    reinterpret_cast<ouzel::NativeWindowEm*>(userData)->handleResize();
    return true;
}

namespace ouzel
{
    NativeWindowEm::NativeWindowEm(const Size2& newSize,
                                   bool newFullscreen,
                                   const std::string& newTitle):
        ouzel::NativeWindow(newSize,
                            true,
                            newFullscreen,
                            true,
                            newTitle,
                            true)
    {
        emscripten_set_resize_callback(nullptr, this, 1, emResizeCallback);

        if (size.width <= 0.0F || size.height <= 0.0F)
        {
            int width, height, fullscreen;
            emscripten_get_canvas_size(&width, &height, &fullscreen);

            if (size.width <= 0.0F) size.width = static_cast<float>(width);
            if (size.height <= 0.0F) size.height = static_cast<float>(height);
        }
        else
            emscripten_set_canvas_size(static_cast<int>(size.width),
                                       static_cast<int>(size.height));

        if (fullscreen)
        {
            EmscriptenFullscreenStrategy s;
            s.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT;
            s.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE;
            s.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
            s.canvasResizedCallback = emFullscreenCallback;
            s.canvasResizedCallbackUserData = this;

            emscripten_request_fullscreen_strategy(nullptr, EM_TRUE, &s);
        }

        resolution = size;
    }

    void NativeWindowEm::setSize(const Size2& newSize)
    {
        NativeWindow::setSize(newSize);

        emscripten_set_canvas_size(static_cast<int>(newSize.width),
                                   static_cast<int>(newSize.height));
    }

    void NativeWindowEm::setFullscreen(bool newFullscreen)
    {
        NativeWindow::setFullscreen(newFullscreen);

        if (fullscreen)
        {
            EmscriptenFullscreenStrategy s;
            s.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT;
            s.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE;
            s.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
            s.canvasResizedCallback = emFullscreenCallback;
            s.canvasResizedCallbackUserData = this;

            emscripten_request_fullscreen_strategy(nullptr, EM_TRUE, &s);
        }
        else
            emscripten_exit_fullscreen();
    }

    void NativeWindowEm::handleResize()
    {
        int width, height, fullscreen;
        emscripten_get_canvas_size(&width, &height, &fullscreen);

        Size2 newSize(static_cast<float>(width), static_cast<float>(height));

        size = newSize;
        resolution = size;

        if (listener)
        {
            listener->onSizeChange(size);
            listener->onResolutionChange(resolution);
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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 "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

using base::TimeDelta;
using base::TimeTicks;

namespace {

class StartupTest : public UITest {
 public:
  StartupTest() {
    show_window_ = true;
    pages_ = "about:blank";
  }
  void SetUp() {}
  void TearDown() {}

  // Load a file on startup rather than about:blank.  This tests a longer
  // startup path, including resource loading and the loading of gears.dll.
  void SetUpWithFileURL() {
    FilePath file_url;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
    file_url = file_url.AppendASCII("simple.html");
    ASSERT_TRUE(file_util::PathExists(file_url));
    launch_arguments_.AppendLooseValue(file_url.ToWStringHack());

    pages_ = WideToUTF8(file_url.ToWStringHack());
  }

  // Use the given profile in the test data extensions/profiles dir.  This tests
  // startup with extensions installed.
  void SetUpWithExtensionsProfile(const char* profile) {
    FilePath data_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &data_dir);
    data_dir = data_dir.AppendASCII("extensions").AppendASCII("profiles").
        AppendASCII(profile);
    set_template_user_data(data_dir);

    // For now, these tests still depend on toolstrips.
    launch_arguments_.AppendSwitch(switches::kEnableExtensionToolstrips);
  }

  void RunStartupTest(const char* graph, const char* trace,
      bool test_cold, bool important, UITest::ProfileType profile_type) {
    profile_type_ = profile_type;

    // Sets the profile data for the run.  For now, this is only used for
    // the non-default themes test.
    if (profile_type != UITest::DEFAULT_THEME) {
      set_template_user_data(UITest::ComputeTypicalUserDataSource(
          profile_type));
    }

    const int kNumCyclesMax = 20;
    int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
    const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
    if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
      LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
                << "so setting numCycles to " << numCycles;

    TimeDelta timings[kNumCyclesMax];
    for (int i = 0; i < numCycles; ++i) {
      if (test_cold) {
        FilePath dir_app;
        ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));

        FilePath chrome_exe(dir_app.Append(
            FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
        // chrome.dll is windows specific.
        FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif

#if defined(OS_WIN)
        // TODO(port): Re-enable once gears is working on mac/linux.
        FilePath gears_dll;
        ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
        NOTIMPLEMENTED() << "gears not enabled yet";
#endif
      }
      UITest::SetUp();
      TimeTicks end_time = TimeTicks::Now();
      timings[i] = end_time - browser_launch_time_;
      // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
      // do, we crash.
      PlatformThread::Sleep(50);
      UITest::TearDown();

      if (i == 0) {
        // Re-use the profile data after first run so that the noise from
        // creating databases doesn't impact all the runs.
        clear_profile_ = false;
        // Clear template_user_data_ so we don't try to copy it over each time
        // through.
        set_template_user_data(FilePath());
      }
    }

    std::string times;
    for (int i = 0; i < numCycles; ++i)
      StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF());
    PrintResultList(graph, "", trace, times, "ms", important);
  }

 protected:
  std::string pages_;
};

class StartupReferenceTest : public StartupTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
  }
};

TEST_F(StartupTest, Perf) {
  RunStartupTest("warm", "t", false /* not cold */, true /* important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupReferenceTest, Perf) {
  RunStartupTest("warm", "t_ref", false /* not cold */,
                 true /* important */, UITest::DEFAULT_THEME);
}

// TODO(mpcomplete): Should we have reference timings for all these?

TEST_F(StartupTest, PerfCold) {
  RunStartupTest("cold", "t", true /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionEmpty) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("empty");
  RunStartupTest("warm", "t", false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionToolstrips1) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("toolstrips1");
  RunStartupTest("warm", "extension_toolstrip1",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionToolstrips50) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("toolstrips50");
  RunStartupTest("warm", "extension_toolstrip50",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionContentScript1) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("content_scripts1");
  RunStartupTest("warm", "extension_content_scripts1",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionContentScript50) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("content_scripts50");
  RunStartupTest("warm", "extension_content_scripts50",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupTest, PerfGears) {
  SetUpWithFileURL();
  RunStartupTest("warm", "gears", false /* not cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfColdGears) {
  SetUpWithFileURL();
  RunStartupTest("cold", "gears", true /* cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}
#endif

TEST_F(StartupTest, PerfColdComplexTheme) {
  RunStartupTest("warm", "t-theme", false /* warm */,
                 false /* not important */, UITest::COMPLEX_THEME);
}

#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
  RunStartupTest("warm", "gtk-theme", false /* warm */,
                 false /* not important */, UITest::NATIVE_THEME);
}

TEST_F(StartupTest, PrefColdNativeFrame) {
  RunStartupTest("warm", "custom-frame", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME);
}

TEST_F(StartupTest, PerfColdNativeFrameGtkTheme) {
  RunStartupTest("warm", "custom-frame-gtk-theme", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME_NATIVE_THEME);
}
#endif

}  // namespace
<commit_msg>Rename a conflicting trace.<commit_after>// Copyright (c) 2006-2008 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 "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

using base::TimeDelta;
using base::TimeTicks;

namespace {

class StartupTest : public UITest {
 public:
  StartupTest() {
    show_window_ = true;
    pages_ = "about:blank";
  }
  void SetUp() {}
  void TearDown() {}

  // Load a file on startup rather than about:blank.  This tests a longer
  // startup path, including resource loading and the loading of gears.dll.
  void SetUpWithFileURL() {
    FilePath file_url;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
    file_url = file_url.AppendASCII("simple.html");
    ASSERT_TRUE(file_util::PathExists(file_url));
    launch_arguments_.AppendLooseValue(file_url.ToWStringHack());

    pages_ = WideToUTF8(file_url.ToWStringHack());
  }

  // Use the given profile in the test data extensions/profiles dir.  This tests
  // startup with extensions installed.
  void SetUpWithExtensionsProfile(const char* profile) {
    FilePath data_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &data_dir);
    data_dir = data_dir.AppendASCII("extensions").AppendASCII("profiles").
        AppendASCII(profile);
    set_template_user_data(data_dir);

    // For now, these tests still depend on toolstrips.
    launch_arguments_.AppendSwitch(switches::kEnableExtensionToolstrips);
  }

  void RunStartupTest(const char* graph, const char* trace,
      bool test_cold, bool important, UITest::ProfileType profile_type) {
    profile_type_ = profile_type;

    // Sets the profile data for the run.  For now, this is only used for
    // the non-default themes test.
    if (profile_type != UITest::DEFAULT_THEME) {
      set_template_user_data(UITest::ComputeTypicalUserDataSource(
          profile_type));
    }

    const int kNumCyclesMax = 20;
    int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
    const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
    if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
      LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
                << "so setting numCycles to " << numCycles;

    TimeDelta timings[kNumCyclesMax];
    for (int i = 0; i < numCycles; ++i) {
      if (test_cold) {
        FilePath dir_app;
        ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));

        FilePath chrome_exe(dir_app.Append(
            FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
        // chrome.dll is windows specific.
        FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif

#if defined(OS_WIN)
        // TODO(port): Re-enable once gears is working on mac/linux.
        FilePath gears_dll;
        ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
        NOTIMPLEMENTED() << "gears not enabled yet";
#endif
      }
      UITest::SetUp();
      TimeTicks end_time = TimeTicks::Now();
      timings[i] = end_time - browser_launch_time_;
      // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
      // do, we crash.
      PlatformThread::Sleep(50);
      UITest::TearDown();

      if (i == 0) {
        // Re-use the profile data after first run so that the noise from
        // creating databases doesn't impact all the runs.
        clear_profile_ = false;
        // Clear template_user_data_ so we don't try to copy it over each time
        // through.
        set_template_user_data(FilePath());
      }
    }

    std::string times;
    for (int i = 0; i < numCycles; ++i)
      StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF());
    PrintResultList(graph, "", trace, times, "ms", important);
  }

 protected:
  std::string pages_;
};

class StartupReferenceTest : public StartupTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
  }
};

TEST_F(StartupTest, Perf) {
  RunStartupTest("warm", "t", false /* not cold */, true /* important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupReferenceTest, Perf) {
  RunStartupTest("warm", "t_ref", false /* not cold */,
                 true /* important */, UITest::DEFAULT_THEME);
}

// TODO(mpcomplete): Should we have reference timings for all these?

TEST_F(StartupTest, PerfCold) {
  RunStartupTest("cold", "t", true /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionEmpty) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("empty");
  RunStartupTest("warm", "extension_empty",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionToolstrips1) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("toolstrips1");
  RunStartupTest("warm", "extension_toolstrip1",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionToolstrips50) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("toolstrips50");
  RunStartupTest("warm", "extension_toolstrip50",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionContentScript1) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("content_scripts1");
  RunStartupTest("warm", "extension_content_scripts1",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionContentScript50) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("content_scripts50");
  RunStartupTest("warm", "extension_content_scripts50",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupTest, PerfGears) {
  SetUpWithFileURL();
  RunStartupTest("warm", "gears", false /* not cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfColdGears) {
  SetUpWithFileURL();
  RunStartupTest("cold", "gears", true /* cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}
#endif

TEST_F(StartupTest, PerfColdComplexTheme) {
  RunStartupTest("warm", "t-theme", false /* warm */,
                 false /* not important */, UITest::COMPLEX_THEME);
}

#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
  RunStartupTest("warm", "gtk-theme", false /* warm */,
                 false /* not important */, UITest::NATIVE_THEME);
}

TEST_F(StartupTest, PrefColdNativeFrame) {
  RunStartupTest("warm", "custom-frame", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME);
}

TEST_F(StartupTest, PerfColdNativeFrameGtkTheme) {
  RunStartupTest("warm", "custom-frame-gtk-theme", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME_NATIVE_THEME);
}
#endif

}  // namespace
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: disposelistener.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:05:59 $
 *
 *  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 __DISPOSELISTENER_HXX_
#define __DISPOSELISTENER_HXX_

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

class OStorage;
class OChildDispListener_Impl : public ::cppu::WeakImplHelper1 < ::com::sun::star::lang::XEventListener >
{
    ::osl::Mutex m_aMutex;
    OStorage* m_pStorage;

public:
    OChildDispListener_Impl( OStorage& aStorage );
    virtual ~OChildDispListener_Impl();

    void OwnerIsDisposed();

    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.3.98); FILE MERGED 2008/04/01 15:22:22 thb 1.3.98.3: #i85898# Stripping all external header guards 2008/04/01 12:32:12 thb 1.3.98.2: #i85898# Stripping all external header guards 2008/03/31 16:19:07 rt 1.3.98.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: disposelistener.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef __DISPOSELISTENER_HXX_
#define __DISPOSELISTENER_HXX_

#include <com/sun/star/lang/XEventListener.hpp>
#include <cppuhelper/implbase1.hxx>
#include <osl/mutex.hxx>

class OStorage;
class OChildDispListener_Impl : public ::cppu::WeakImplHelper1 < ::com::sun::star::lang::XEventListener >
{
    ::osl::Mutex m_aMutex;
    OStorage* m_pStorage;

public:
    OChildDispListener_Impl( OStorage& aStorage );
    virtual ~OChildDispListener_Impl();

    void OwnerIsDisposed();

    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);
};

#endif

<|endoftext|>


<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#ifndef DO_CORE_PIXEL_PIXEL_HPP
#define DO_CORE_PIXEL_PIXEL_HPP

#include <functional>
#include <stdexcept>

#include <DO/Core/EigenExtension.hpp>
#include <DO/Core/Meta.hpp>

// Pixel data structures.
namespace DO {

  //! \brief Simple pixel class implemented as a vector.
  template <typename _T, typename _ColorSpace>
  class Pixel : public Matrix<_T, _ColorSpace::size, 1>
  {
    typedef Matrix<_T, _ColorSpace::size, 1> base_type;

  public:
    //! Channel type.
    typedef _T channel_type;
    typedef _ColorSpace color_space_type;

    //! Default constructor.
    inline Pixel()
      : base_type()
    {
    }

    //! Custom constructor.
    inline Pixel(_T x, _T y, _T z)
      : base_type(x, y, z)
    {
    }

    //! Custom constructor.
    inline Pixel(_T x, _T y, _T z, _T t)
      : base_type(x, y, z, t)
    {
    }

    //! Copy constructor.
    inline Pixel(const base_type& x)
      : base_type(x)
    {
    }

    //! Assignment operator.
    template <typename _OtherDerived>
    inline Pixel& operator=(const Eigen::MatrixBase<_OtherDerived>& other)
    {
      this->base_type::operator=(other); return *this;
    }

    //! Constant channel access function.
    template <typename _ChannelTag>
    inline const channel_type& channel() const
    {
      return (*this)[Meta::IndexOf<_ColorSpace, _ChannelTag>::value];
    }

    //! Mutable channel access function.
    template <typename _ChannelTag>
    inline channel_type& channel()
    {
      return (*this)[Meta::IndexOf<_ColorSpace, _ChannelTag>::value];
    }

    //! Returns the number of channels.
    int num_channels() const
    {
      return _ColorSpace::size;
    }
  };

}

#endif /* DO_CORE_PIXEL_PIXEL_HPP */<commit_msg>Fix copy constructor of the `Pixel` class.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#ifndef DO_CORE_PIXEL_PIXEL_HPP
#define DO_CORE_PIXEL_PIXEL_HPP

#include <functional>
#include <stdexcept>

#include <DO/Core/EigenExtension.hpp>
#include <DO/Core/Meta.hpp>

// Pixel data structures.
namespace DO {

  //! \brief Simple pixel class implemented as a vector.
  template <typename _T, typename _ColorSpace>
  class Pixel : public Matrix<_T, _ColorSpace::size, 1>
  {
    typedef Matrix<_T, _ColorSpace::size, 1> base_type;

  public:
    //! Channel type.
    typedef _T channel_type;
    typedef _ColorSpace color_space_type;

    //! Default constructor.
    inline Pixel()
      : base_type()
    {
    }

    //! Custom constructor.
    inline Pixel(_T x, _T y, _T z)
      : base_type(x, y, z)
    {
    }

    //! Custom constructor.
    inline Pixel(_T x, _T y, _T z, _T t)
      : base_type(x, y, z, t)
    {
    }

    //! Copy constructor.
    template<typename OtherDerived>
    inline Pixel(const Eigen::MatrixBase<OtherDerived>& other)
      : base_type(other)
    {
    }

    //! Assignment operator.
    template <typename _OtherDerived>
    inline Pixel& operator=(const Eigen::MatrixBase<_OtherDerived>& other)
    {
      this->base_type::operator=(other); return *this;
    }

    //! Constant channel access function.
    template <typename _ChannelTag>
    inline const channel_type& channel() const
    {
      return (*this)[Meta::IndexOf<_ColorSpace, _ChannelTag>::value];
    }

    //! Mutable channel access function.
    template <typename _ChannelTag>
    inline channel_type& channel()
    {
      return (*this)[Meta::IndexOf<_ColorSpace, _ChannelTag>::value];
    }

    //! Returns the number of channels.
    int num_channels() const
    {
      return _ColorSpace::size;
    }
  };

}

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


<commit_before>#ifndef slic3r_ImGuiWrapper_hpp_
#define slic3r_ImGuiWrapper_hpp_

#include <string>
#include <map>

#include <imgui/imgui.h>

#include "libslic3r/Point.hpp"

class wxString;
class wxMouseEvent;
class wxKeyEvent;

namespace Slic3r {
namespace GUI {

class ImGuiWrapper
{
    typedef std::map<std::string, ImFont*> FontsMap;

    FontsMap m_fonts;
    const ImWchar *m_glyph_ranges;
    unsigned m_font_texture;
    float m_style_scaling;
    unsigned m_mouse_buttons;
    bool m_disabled;
    bool m_new_frame_open;
    std::string m_clipboard_text;

public:
    ImGuiWrapper();
    ~ImGuiWrapper();

    bool init();
    void read_glsl_version();

    void set_language(const std::string &language);
    void set_display_size(float w, float h);
    void set_style_scaling(float scaling);
    bool update_mouse_data(wxMouseEvent &evt);
    bool update_key_data(wxKeyEvent &evt);

    void new_frame();
    void render();

    void set_next_window_pos(float x, float y, int flag);
    void set_next_window_bg_alpha(float alpha);

    bool begin(const std::string &name, int flags = 0);
    bool begin(const wxString &name, int flags = 0);
    void end();

    bool button(const wxString &label);
    bool radio_button(const wxString &label, bool active);
    bool input_double(const std::string &label, const double &value, const std::string &format = "%.3f");
    bool input_vec3(const std::string &label, const Vec3d &value, float width, const std::string &format = "%.3f");
    bool checkbox(const wxString &label, bool &value);
    void text(const const char *label);
    void text(const std::string &label);
    void text(const wxString &label);
    bool combo(const wxString& label, const std::vector<std::string>& options, std::string& current_selection);
    bool combo(const wxString& label, const std::vector<wxString>& options, wxString& current_selection);

    void disabled_begin(bool disabled);
    void disabled_end();

    bool want_mouse() const;
    bool want_keyboard() const;
    bool want_text_input() const;
    bool want_any_input() const;

private:
    void init_default_font(float scaling);
    void create_device_objects();
    void create_fonts_texture();
    void init_input();
    void init_style();
    void render_draw_data(ImDrawData *draw_data);
    bool display_initialized() const;
    void destroy_device_objects();
    void destroy_fonts_texture();

    static const char* clipboard_get(void* user_data);
    static void clipboard_set(void* user_data, const char* text);
};

} // namespace GUI
} // namespace Slic3r

#endif // slic3r_ImGuiWrapper_hpp_

<commit_msg>Fixed a typo<commit_after>#ifndef slic3r_ImGuiWrapper_hpp_
#define slic3r_ImGuiWrapper_hpp_

#include <string>
#include <map>

#include <imgui/imgui.h>

#include "libslic3r/Point.hpp"

class wxString;
class wxMouseEvent;
class wxKeyEvent;

namespace Slic3r {
namespace GUI {

class ImGuiWrapper
{
    typedef std::map<std::string, ImFont*> FontsMap;

    FontsMap m_fonts;
    const ImWchar *m_glyph_ranges;
    unsigned m_font_texture;
    float m_style_scaling;
    unsigned m_mouse_buttons;
    bool m_disabled;
    bool m_new_frame_open;
    std::string m_clipboard_text;

public:
    ImGuiWrapper();
    ~ImGuiWrapper();

    bool init();
    void read_glsl_version();

    void set_language(const std::string &language);
    void set_display_size(float w, float h);
    void set_style_scaling(float scaling);
    bool update_mouse_data(wxMouseEvent &evt);
    bool update_key_data(wxKeyEvent &evt);

    void new_frame();
    void render();

    void set_next_window_pos(float x, float y, int flag);
    void set_next_window_bg_alpha(float alpha);

    bool begin(const std::string &name, int flags = 0);
    bool begin(const wxString &name, int flags = 0);
    void end();

    bool button(const wxString &label);
    bool radio_button(const wxString &label, bool active);
    bool input_double(const std::string &label, const double &value, const std::string &format = "%.3f");
    bool input_vec3(const std::string &label, const Vec3d &value, float width, const std::string &format = "%.3f");
    bool checkbox(const wxString &label, bool &value);
    void text(const char *label);
    void text(const std::string &label);
    void text(const wxString &label);
    bool combo(const wxString& label, const std::vector<std::string>& options, std::string& current_selection);
    bool combo(const wxString& label, const std::vector<wxString>& options, wxString& current_selection);

    void disabled_begin(bool disabled);
    void disabled_end();

    bool want_mouse() const;
    bool want_keyboard() const;
    bool want_text_input() const;
    bool want_any_input() const;

private:
    void init_default_font(float scaling);
    void create_device_objects();
    void create_fonts_texture();
    void init_input();
    void init_style();
    void render_draw_data(ImDrawData *draw_data);
    bool display_initialized() const;
    void destroy_device_objects();
    void destroy_fonts_texture();

    static const char* clipboard_get(void* user_data);
    static void clipboard_set(void* user_data, const char* text);
};

} // namespace GUI
} // namespace Slic3r

#endif // slic3r_ImGuiWrapper_hpp_

<|endoftext|>