<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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbStereorectificationDeformationFieldSource.h"

namespace otb
{
namespace Wrapper
{

class StereoRectificationGridGenerator : public Application
{
public:
  /** Standard class typedefs. */
  typedef StereoRectificationGridGenerator    Self;
  typedef Application                         Superclass;
  typedef itk::SmartPointer<Self>             Pointer;
  typedef itk::SmartPointer<const Self>       ConstPointer;

  typedef otb::StereorectificationDeformationFieldSource
  <FloatVectorImageType,FloatVectorImageType> DeformationFieldSourceType;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(StereoRectificationGridGenerator, otb::Application);

private:

  StereoRectificationGridGenerator()
  {
    // Instanciate deformation field source
    m_DeformationFieldSource = DeformationFieldSourceType::New();
  }

 void DoInit()
  {
    SetName("StereoRectificationGridGenerator");
    SetDescription("Generates two deformation fields to stereo-rectify (i.e. resample in epipolar geometry) a pair of stereo images up to the sensor model precision");

    SetDocName("Stereo-rectification deformation grid generator");
    SetDocLongDescription("This application generates a pair of deformation grid to stereo-rectify a pair of stereo images according to sensor modelling and a mean elevation hypothesis. The deformation grids can be passed to the StereoRectificationGridGenerator application for actual resampling in epipolar geometry.");
    SetDocLimitations("Generation of the deformation grid is not streamable, pay attention to this fact when setting the grid step.");
    SetDocAuthors("OTB-Team");

    AddDocTag(Tags::Geometry);

    SetDocSeeAlso("otbGridBasedImageResampling");

    AddParameter(ParameterType_Group,"io","Input and output data");
    SetParameterDescription("io","This group of parameters allows to set the input and output images.");
    AddParameter(ParameterType_InputImage,"io.inleft","Left input image");
    SetParameterDescription("io.inleft","The left input image to resample");

    AddParameter(ParameterType_InputImage,"io.inright","Right input image");
    SetParameterDescription("io.inright","The right input image to resample");

    AddParameter(ParameterType_OutputImage, "io.outleft", "Left output deformation grid");
    SetParameterDescription("io.outleft","The output deformation grid to be used to resample the left input image");

    AddParameter(ParameterType_OutputImage, "io.outright", "Right output deformation grid");
    SetParameterDescription("io.outright","The output deformation grid to be used to resample the right input image");

    AddParameter(ParameterType_Group,"epi","Epipolar  geometry and grid parameters");
    SetParameterDescription("epi","Parameters of the epipolar geometry and output grids");

    AddParameter(ParameterType_Float,"epi.elevation","Mean elevation (in meters)");
    SetParameterDescription("epi.elevation","In the output rectified images, corresponding pixels whose elevation is equal to the mean elevation will have a null disparity");
    SetDefaultParameterFloat("epi.elevation",0.);

    AddParameter(ParameterType_Float,"epi.scale","Scale of epipolar images");
    SetParameterDescription("epi.scale","The scale parameter allows to generated zoomed-in (scale < 1) or zoomed-out (scale > 1) epipolar images.");
    SetDefaultParameterFloat("epi.scale",1.);

    AddParameter(ParameterType_Int,"epi.step","Step of the deformation grid (in nb. of pixels)");
    SetParameterDescription("epi.step","Stereo-rectification deformation grid only varies slowly. Therefore, it is recommanded to use a coarser grid (higher step value) in case of large images");
    SetDefaultParameterInt("epi.step",1);

    AddParameter(ParameterType_Int,"epi.rectsizex","Rectified image size X");
    SetParameterDescription("epi.rectsizex","The application computes the optimal rectified image size so that the whole left input image fits into the rectified area. However, due to the scale and step parameter, this size may not match the size of the deformation field output. In this case, one can use these output values.");
    SetParameterRole("epi.rectsizex", Role_Output);

    AddParameter(ParameterType_Int,"epi.rectsizey","Rectified image size Y");
    SetParameterDescription("epi.rectsizey","The application computes the optimal rectified image size so that the whole left input image fits into the rectified area. However, due to the scale and step parameter, this size may not match the size of the deformation field output. In this case, one can use these output values.");
    SetParameterRole("epi.rectsizey", Role_Output);

    AddParameter(ParameterType_Float,"epi.baseline","Mean baseline ratio");
    SetParameterDescription("epi.baseline","This parameter is the mean value, in meters, of the baseline to sensor altitude ratio. It can be used to convert disparities to physical elevation, since a disparity of one pixel will corresspond to an elevation offset of this value with respect to the mean elevation.");
    SetParameterRole("epi.baseline", Role_Output);

    // Doc example
    SetDocExampleParameterValue("io.inleft","wv2_xs_left.tif");
    SetDocExampleParameterValue("io.inright","wv2_xs_left.tif");
    SetDocExampleParameterValue("io.outleft","wv2_xs_left_epi_field.tif");
    SetDocExampleParameterValue("io.outright","wv2_xs_right_epi_field.tif");
    SetDocExampleParameterValue("epi.elevation","400");
  }

 void DoUpdateParameters()
  {
    // Nothing to do here
  }

void DoExecute()
    {
      m_DeformationFieldSource->SetLeftImage(GetParameterImage("io.inleft"));
      m_DeformationFieldSource->SetRightImage(GetParameterImage("io.inright"));
      m_DeformationFieldSource->SetGridStep(GetParameterInt("epi.step"));
      m_DeformationFieldSource->SetScale(GetParameterFloat("epi.scale"));
      m_DeformationFieldSource->SetAverageElevation(GetParameterFloat("epi.elevation"));

      AddProcess(m_DeformationFieldSource, "Computing epipolar grids ...");

      m_DeformationFieldSource->Update();

      SetParameterInt("epi.rectsizex",m_DeformationFieldSource->GetRectifiedImageSize()[0]);
      SetParameterInt("epi.rectsizey",m_DeformationFieldSource->GetRectifiedImageSize()[1]);
      SetParameterFloat("epi.baseline",m_DeformationFieldSource->GetMeanBaselineRatio());

      SetParameterOutputImage("io.outleft",m_DeformationFieldSource->GetLeftDeformationFieldOutput());

      SetParameterOutputImage("io.outright",m_DeformationFieldSource->GetRightDeformationFieldOutput());
    }

  DeformationFieldSourceType::Pointer m_DeformationFieldSource;
};
} // End namespace Wrapper
} // End namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::StereoRectificationGridGenerator)
<commit_msg>ENH: enable DEM use for stereo-rectification in application<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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbStereorectificationDeformationFieldSource.h"

// Elevation handler
#include "otbWrapperElevationParametersHandler.h"

namespace otb
{
namespace Wrapper
{

class StereoRectificationGridGenerator : public Application
{
public:
  /** Standard class typedefs. */
  typedef StereoRectificationGridGenerator    Self;
  typedef Application                         Superclass;
  typedef itk::SmartPointer<Self>             Pointer;
  typedef itk::SmartPointer<const Self>       ConstPointer;

  typedef otb::StereorectificationDeformationFieldSource
  <FloatVectorImageType,FloatVectorImageType> DeformationFieldSourceType;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(StereoRectificationGridGenerator, otb::Application);

private:

  StereoRectificationGridGenerator()
  {
    // Instanciate deformation field source
    m_DeformationFieldSource = DeformationFieldSourceType::New();
  }

 void DoInit()
  {
    SetName("StereoRectificationGridGenerator");
    SetDescription("Generates two deformation fields to stereo-rectify (i.e. resample in epipolar geometry) a pair of stereo images up to the sensor model precision");

    SetDocName("Stereo-rectification deformation grid generator");
    SetDocLongDescription("This application generates a pair of deformation grid to stereo-rectify a pair of stereo images according to sensor modelling and a mean elevation hypothesis. The deformation grids can be passed to the StereoRectificationGridGenerator application for actual resampling in epipolar geometry.");
    SetDocLimitations("Generation of the deformation grid is not streamable, pay attention to this fact when setting the grid step.");
    SetDocAuthors("OTB-Team");

    AddDocTag(Tags::Geometry);

    SetDocSeeAlso("otbGridBasedImageResampling");

    AddParameter(ParameterType_Group,"io","Input and output data");
    SetParameterDescription("io","This group of parameters allows to set the input and output images.");
    AddParameter(ParameterType_InputImage,"io.inleft","Left input image");
    SetParameterDescription("io.inleft","The left input image to resample");

    AddParameter(ParameterType_InputImage,"io.inright","Right input image");
    SetParameterDescription("io.inright","The right input image to resample");

    AddParameter(ParameterType_OutputImage, "io.outleft", "Left output deformation grid");
    SetParameterDescription("io.outleft","The output deformation grid to be used to resample the left input image");

    AddParameter(ParameterType_OutputImage, "io.outright", "Right output deformation grid");
    SetParameterDescription("io.outright","The output deformation grid to be used to resample the right input image");

    AddParameter(ParameterType_Group,"epi","Epipolar  geometry and grid parameters");
    SetParameterDescription("epi","Parameters of the epipolar geometry and output grids");

    ElevationParametersHandler::AddElevationParameters(this, "epi.elevation");
    SetParameterDescription("epi.elevation","In the output rectified images, corresponding pixels whose elevation is equal to the mean elevation will have a null disparity");
    MandatoryOn("epi.elevation");

    AddParameter(ParameterType_Float,"epi.scale","Scale of epipolar images");
    SetParameterDescription("epi.scale","The scale parameter allows to generated zoomed-in (scale < 1) or zoomed-out (scale > 1) epipolar images.");
    SetDefaultParameterFloat("epi.scale",1.);

    AddParameter(ParameterType_Int,"epi.step","Step of the deformation grid (in nb. of pixels)");
    SetParameterDescription("epi.step","Stereo-rectification deformation grid only varies slowly. Therefore, it is recommanded to use a coarser grid (higher step value) in case of large images");
    SetDefaultParameterInt("epi.step",1);

    AddParameter(ParameterType_Int,"epi.rectsizex","Rectified image size X");
    SetParameterDescription("epi.rectsizex","The application computes the optimal rectified image size so that the whole left input image fits into the rectified area. However, due to the scale and step parameter, this size may not match the size of the deformation field output. In this case, one can use these output values.");
    SetParameterRole("epi.rectsizex", Role_Output);

    AddParameter(ParameterType_Int,"epi.rectsizey","Rectified image size Y");
    SetParameterDescription("epi.rectsizey","The application computes the optimal rectified image size so that the whole left input image fits into the rectified area. However, due to the scale and step parameter, this size may not match the size of the deformation field output. In this case, one can use these output values.");
    SetParameterRole("epi.rectsizey", Role_Output);

    AddParameter(ParameterType_Float,"epi.baseline","Mean baseline ratio");
    SetParameterDescription("epi.baseline","This parameter is the mean value, in meters, of the baseline to sensor altitude ratio. It can be used to convert disparities to physical elevation, since a disparity of one pixel will corresspond to an elevation offset of this value with respect to the mean elevation.");
    SetParameterRole("epi.baseline", Role_Output);

    // Doc example
    SetDocExampleParameterValue("io.inleft","wv2_xs_left.tif");
    SetDocExampleParameterValue("io.inright","wv2_xs_left.tif");
    SetDocExampleParameterValue("io.outleft","wv2_xs_left_epi_field.tif");
    SetDocExampleParameterValue("io.outright","wv2_xs_right_epi_field.tif");
    SetDocExampleParameterValue("epi.elevation.average","400");
  }

 void DoUpdateParameters()
  {
    // Nothing to do here
  }

void DoExecute()
    {
      m_DeformationFieldSource->SetLeftImage(GetParameterImage("io.inleft"));
      m_DeformationFieldSource->SetRightImage(GetParameterImage("io.inright"));
      m_DeformationFieldSource->SetGridStep(GetParameterInt("epi.step"));
      m_DeformationFieldSource->SetScale(GetParameterFloat("epi.scale"));

      switch(ElevationParametersHandler::GetElevationType(this, "epi.elevation"))
        {
        case Elevation_DEM:
        {
        m_DeformationFieldSource->SetDEMDirectory(ElevationParametersHandler::GetDEMDirectory(this, "epi.elevation"));
        m_DeformationFieldSource->SetGeoidFile(ElevationParametersHandler::GetGeoidFile(this, "epi.elevation"));
        }
        break;
        case Elevation_Average:
        {
        m_DeformationFieldSource->SetAverageElevation(ElevationParametersHandler::GetAverageElevation(this, "epi.elevation"));
        }
        }

      AddProcess(m_DeformationFieldSource, "Computing epipolar grids ...");

      m_DeformationFieldSource->Update();

      SetParameterInt("epi.rectsizex",m_DeformationFieldSource->GetRectifiedImageSize()[0]);
      SetParameterInt("epi.rectsizey",m_DeformationFieldSource->GetRectifiedImageSize()[1]);
      SetParameterFloat("epi.baseline",m_DeformationFieldSource->GetMeanBaselineRatio());

      SetParameterOutputImage("io.outleft",m_DeformationFieldSource->GetLeftDeformationFieldOutput());

      SetParameterOutputImage("io.outright",m_DeformationFieldSource->GetRightDeformationFieldOutput());
    }

  DeformationFieldSourceType::Pointer m_DeformationFieldSource;
};
} // End namespace Wrapper
} // End namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::StereoRectificationGridGenerator)
<|endoftext|>


<commit_before>// Copyright (c) 2009 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 <stdlib.h>  // required by _set_abort_behavior
#include <gtk/gtk.h>

#include "base/command_line.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
  gtk_init(argc, argv);
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  // Pick a theme that uses Cairo for drawing, since we:
  // 1) currently don't support GTK themes that use the GDK drawing APIs, and
  // 2) need to use a unified theme for layout tests anyway.
  g_object_set(gtk_settings_get_default(),
               "gtk-theme-name", "Mist",
               NULL);
}

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
}

bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  return true;
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
}

void TestShellPlatformDelegate::InitializeGUI() {
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(TestShell *) {
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
}
<commit_msg>Do no use custom gtkrc files in layout test mode.<commit_after>// Copyright (c) 2009 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 <stdlib.h>  // required by _set_abort_behavior
#include <gtk/gtk.h>

#include "base/command_line.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
  gtk_init(argc, argv);
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  // Stop custom gtkrc files from messing with the theme.
  gchar* default_gtkrc_files[] = { NULL };
  gtk_rc_set_default_files(default_gtkrc_files);
  gtk_rc_reparse_all_for_settings(gtk_settings_get_default(), TRUE);

  // Pick a theme that uses Cairo for drawing, since we:
  // 1) currently don't support GTK themes that use the GDK drawing APIs, and
  // 2) need to use a unified theme for layout tests anyway.
  g_object_set(gtk_settings_get_default(),
               "gtk-theme-name", "Mist",
               NULL);
}

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
}

bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  return true;
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
}

void TestShellPlatformDelegate::InitializeGUI() {
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(TestShell *) {
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
}
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 "stdafx.h"

// standard
#include <cstring>
#include <iomanip>

// local
#include "ascii_util.h"

using namespace std;

namespace zorba {
namespace ascii {

///////////////////////////////////////////////////////////////////////////////

bool is_whitespace( char const *s ) {
  for ( ; *s; ++s ) {
    if ( !is_space( *s ) )
      return false;
  }
  return true;
}

char* itoa( long long n, char *buf ) {
  //
  // This implementation is much faster than using sprintf(3).
  //
  char *s = buf;
  long long n_prev;
  do {
    n_prev = n;
    n /= 10;
    *s++ = "9876543210123456789" [ 9 + n_prev - n * 10 ];
  } while ( n );

  if ( n_prev < 0 ) *s++ = '-';
  *s = '\0';

  for ( char *t = buf; t < s; ++t ) {
    char const c = *--s; *s = *t; *t = c;
  }
  return buf;
}

char* itoa( unsigned long long n, char *buf ) {
  char *s = buf;
  unsigned long long n_prev;
  do {
    n_prev = n;
    n /= 10;
    *s++ = "0123456789" [ n_prev - n * 10 ];
  } while ( n );

  *s = '\0';

  for ( char *t = buf; t < s; ++t ) {
    char const c = *--s; *s = *t; *t = c;
  }
  return buf;
}

ostream& printable_char( ostream &o, char c ) {
  if ( ascii::is_print( c ) )
    o << c;
  else
    switch ( c ) {
      case '\n': o << "\\n"; break;
      case '\r': o << "\\r"; break;
      case '\t': o << "\\t"; break;
      default: {
        ios::fmtflags const old_flags = o.flags();
        o << "#x" << uppercase << hex << (static_cast<unsigned>( c ) & 0xFF);
        o.flags( old_flags );
      }
    }
  return o;
}

size_type remove_chars( char *s, size_type s_len, char const *chars ) {
  char *end = s + s_len;
  char *c;

  // remove trailing chars first
  for ( c = end - 1; c >= s; --c )
    if ( !std::strchr( chars, *c ) ) {
      end = c + 1;
      break;
    }
  if ( c < s )                          // it was all chars
    return 0;

  // remove all other chars
  char *first_char = nullptr;
  for ( c = s; c < end; ++c ) {
    if ( std::strchr( chars, *c ) ) {
      if ( !first_char )
        first_char = c;
    } else {
      if ( first_char ) {
        std::memmove( first_char, c, end - c );
        end -= c - first_char;
        c = first_char;
        first_char = nullptr;
      }
    }
  }

  return end - s;
}

char const* trim_start( char const *s, char const *chars ) {
  for ( ; *s; ++s ) {
    if ( !std::strchr( chars, *s ) )
      break;
  }
  return s;
}

char const* trim_start( char const *s, size_type s_len, char const *chars ) {
  for ( ; s_len-- > 0; ++s ) {
    if ( !std::strchr( chars, *s ) )
      break;
  }
  return s;
}

size_type trim_end( char const *s, size_type s_len, char const *chars ) {
  s += s_len - 1;
  for ( ; s_len > 0; --s, --s_len ) {
    if ( !std::strchr( chars, *s ) )
      break;
  }
  return s_len;
}

///////////////////////////////////////////////////////////////////////////////

} // namespace ascii
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<commit_msg>Now using std::reverse().<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 "stdafx.h"

// standard
#include <algorithm>
#include <cstring>
#include <iomanip>

// local
#include "ascii_util.h"

using namespace std;

namespace zorba {
namespace ascii {

///////////////////////////////////////////////////////////////////////////////

bool is_whitespace( char const *s ) {
  for ( ; *s; ++s ) {
    if ( !is_space( *s ) )
      return false;
  }
  return true;
}

char* itoa( long long n, char *buf ) {
  //
  // This implementation is much faster than using sprintf(3).
  //
  char *s = buf;
  long long n_prev;
  do {
    n_prev = n;
    n /= 10;
    *s++ = "9876543210123456789" [ 9 + n_prev - n * 10 ];
  } while ( n );

  if ( n_prev < 0 ) *s++ = '-';
  *s = '\0';
  std::reverse( buf, s );
  return buf;
}

char* itoa( unsigned long long n, char *buf ) {
  char *s = buf;
  do {
    unsigned long long const n_prev = n;
    n /= 10;
    *s++ = "0123456789" [ n_prev - n * 10 ];
  } while ( n );

  *s = '\0';
  std::reverse( buf, s );
  return buf;
}

ostream& printable_char( ostream &o, char c ) {
  if ( ascii::is_print( c ) )
    o << c;
  else
    switch ( c ) {
      case '\n': o << "\\n"; break;
      case '\r': o << "\\r"; break;
      case '\t': o << "\\t"; break;
      default: {
        ios::fmtflags const old_flags = o.flags();
        o << "#x" << uppercase << hex << (static_cast<unsigned>( c ) & 0xFF);
        o.flags( old_flags );
      }
    }
  return o;
}

size_type remove_chars( char *s, size_type s_len, char const *chars ) {
  char *end = s + s_len;
  char *c;

  // remove trailing chars first
  for ( c = end - 1; c >= s; --c )
    if ( !std::strchr( chars, *c ) ) {
      end = c + 1;
      break;
    }
  if ( c < s )                          // it was all chars
    return 0;

  // remove all other chars
  char *first_char = nullptr;
  for ( c = s; c < end; ++c ) {
    if ( std::strchr( chars, *c ) ) {
      if ( !first_char )
        first_char = c;
    } else {
      if ( first_char ) {
        std::memmove( first_char, c, end - c );
        end -= c - first_char;
        c = first_char;
        first_char = nullptr;
      }
    }
  }

  return end - s;
}

char const* trim_start( char const *s, char const *chars ) {
  for ( ; *s; ++s ) {
    if ( !std::strchr( chars, *s ) )
      break;
  }
  return s;
}

char const* trim_start( char const *s, size_type s_len, char const *chars ) {
  for ( ; s_len-- > 0; ++s ) {
    if ( !std::strchr( chars, *s ) )
      break;
  }
  return s;
}

size_type trim_end( char const *s, size_type s_len, char const *chars ) {
  s += s_len - 1;
  for ( ; s_len > 0; --s, --s_len ) {
    if ( !std::strchr( chars, *s ) )
      break;
  }
  return s_len;
}

///////////////////////////////////////////////////////////////////////////////

} // namespace ascii
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<|endoftext|>


<commit_before>//
// Copyright (c) 2017 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_STEERING_METHOD_CONSTANT_CURVATURE_HH
# define HPP_CORE_STEERING_METHOD_CONSTANT_CURVATURE_HH

# include <hpp/core/fwd.hh>
# include <hpp/core/path.hh>
# include <hpp/core/steering-method/fwd.hh>

namespace hpp {
  namespace core {
    namespace steeringMethod {
      /// Path of constant curvature for a carlike robot
      class ConstantCurvature : public Path {
      public:
        typedef Path parent_t;
        virtual ~ConstantCurvature () {}
         /// Create instance and return shared pointer.
        /// \param robot the carlike robot,
        /// \param init, end Initial and final configurations of the path,
        /// \param curveLength distance traveled by the middle of the rear
        ///        wheel axis, negative values correspond to backward motions
        /// \param pathLength length of the interval of definition. Should be
        ///        positive,
        /// \param curvature curvature of the path,
        /// \param xyId id of degrees of freedom corresponding to (x,y)
        /// coordinates of robot,
        /// \param rzId id of degrees of freedom corresponding to orientation
        /// of robot.
        /// \param rz joint corresponding to orientation of robot,
        /// \param wheels vector of joints corresponding to wheels,
        /// \param constraints set of contraints the path is suject to.
        static ConstantCurvaturePtr_t create
        (const DevicePtr_t& robot, ConfigurationIn_t init,
         ConfigurationIn_t end,
         value_type curveLength, value_type pathLength,
         value_type curvature, size_type xyId, size_type rzId,
         const JointPtr_t rz, const std::vector<JointPtr_t> wheels,
         const ConstraintSetPtr_t& constraints);

         /// Create instance and return shared pointer.
        static ConstantCurvaturePtr_t createCopy
        (const ConstantCurvaturePtr_t& other);

        /// Create instance and return shared pointer.
        static ConstantCurvaturePtr_t createCopy
        (const ConstantCurvaturePtr_t& other,
         const ConstraintSetPtr_t& constraints);

        /// Return a shared pointer to a copy of this
        virtual PathPtr_t copy () const;

        /// Return a shared pointer to a copy of this with constraints
        /// \param constraints constraints to apply to the copy
        /// \pre *this should not have constraints.
        virtual PathPtr_t copy (const ConstraintSetPtr_t& constraints) const
        {
	  return createCopy (weak_.lock (), constraints);
        }

       /// Get the initial configuration
        inline Configuration_t initial () const
        {
          return initial_;
        }

        /// Get the final configuration
        inline Configuration_t end () const
        {
          return end_;
        }

        virtual PathPtr_t reverse () const;

      protected:
        /// Print path in a stream
        virtual std::ostream& print (std::ostream &os) const;

        /// Constructor
        /// \param robot the carlike robot,
        /// \param init, end Initial and final configurations of the path,
        /// \param curveLength distance traveled by the middle of the rear
        ///        wheel axis, negative values correspond to backward motions
        /// \param pathLength length of the interval of definition. Should be
        ///        positive,
        /// \param curvature curvature of the path,
        /// \param xyId id of degrees of freedom corresponding to (x,y)
        /// coordinates of robot,
        /// \param rzId id of degrees of freedom corresponding to orientation
        /// of robot.
        /// \param rz joint corresponding to orientation of robot,
        /// \param wheels vector of joints corresponding to wheels.
        ConstantCurvature (const DevicePtr_t& robot, ConfigurationIn_t init,
                           ConfigurationIn_t end,
                           value_type curveLength, value_type pathLength,
                           value_type curvature, size_type xyId,
                           size_type rzId, const JointPtr_t rz,
                           const std::vector<JointPtr_t> wheels);

        /// Constructor
        /// \param robot the carlike robot,
        /// \param init, end Initial and final configurations of the path,
        /// \param curveLength distance traveled by the middle of the rear
        ///        wheel axis, negative values correspond to backward motions
        /// \param pathLength length of the interval of definition. Should be
        ///        positive,
        /// \param curvature curvature of the path,
        /// \param xyId id of degrees of freedom corresponding to (x,y)
        /// coordinates of robot,
        /// \param rzId id of degrees of freedom corresponding to orientation
        /// of robot.
        /// \param rz joint corresponding to orientation of robot,
        /// \param wheels vector of joints corresponding to wheels,
        /// \param constraints set of contraints the path is suject to.
        ConstantCurvature (const DevicePtr_t& robot, ConfigurationIn_t init,
                           ConfigurationIn_t end,
                           value_type curveLength, value_type pathLength,
                           value_type curvature, size_type xyId, size_type rzId,
                           const JointPtr_t rz,
                           const std::vector<JointPtr_t> wheels,
                           ConstraintSetPtr_t constraints);

        /// Copy constructor
        ConstantCurvature (const ConstantCurvature& other);

        /// Copy constructor with constraints
        ConstantCurvature (const ConstantCurvature& other,
                           const ConstraintSetPtr_t& constraints);

        virtual bool impl_compute (ConfigurationOut_t result,
                                   value_type param) const;
        /// Virtual implementation of derivative
        virtual void impl_derivative
        (vectorOut_t result, const value_type& param, size_type order) const;
        /// Virtual implementation of velocity bound
        virtual void impl_velocityBound (vectorOut_t bound,
                                         const value_type& param0,
                                         const value_type& param1) const;

        /// Virtual implementation of path extraction
        virtual PathPtr_t impl_extract (const interval_t& paramInterval) const;

        /// store weak pointer to itself
        void init (const ConstantCurvatureWkPtr_t& weak)
        {
          parent_t::init (weak);
          weak_ = weak;
        }

        /// For serialization only.
        ConstantCurvature() : curvature_(0), xyId_(0), rzId_(0) {}
    private:
        /// Set the wheel joints for a car-like vehicle.
        ///
        /// \param rz joint from which the turning radius was computed.
        /// \param wheels bounded rotation joints.
        void setWheelJoints (const JointPtr_t rz,
                             const std::vector<JointPtr_t> wheels);

        DevicePtr_t robot_;
        Configuration_t initial_;
        Configuration_t end_;
        value_type curveLength_;
        const value_type curvature_;
        const size_type xyId_,rzId_;
        size_type dxyId_,drzId_;
        value_type forward_;
        struct Wheels_t {
          value_type value; // Constant value of the wheel angle
          JointPtr_t j;
          Wheels_t () : j () {}
        };
        std::vector<Wheels_t> wheels_;
        ConstantCurvatureWkPtr_t weak_;

        HPP_SERIALIZABLE();
      }; // class ConstantCurvature
    } // namespace steeringMethod
  } // namespace core
} // namespace hpp

#endif // HPP_CORE_STEERING_METHOD_CONSTANT_CURVATURE_HH
<commit_msg>make ConstantCurvature::Wheels_t public<commit_after>//
// Copyright (c) 2017 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_STEERING_METHOD_CONSTANT_CURVATURE_HH
# define HPP_CORE_STEERING_METHOD_CONSTANT_CURVATURE_HH

# include <hpp/core/fwd.hh>
# include <hpp/core/path.hh>
# include <hpp/core/steering-method/fwd.hh>

namespace hpp {
  namespace core {
    namespace steeringMethod {
      /// Path of constant curvature for a carlike robot
      class ConstantCurvature : public Path {
      public:
        typedef Path parent_t;
        virtual ~ConstantCurvature () {}
         /// Create instance and return shared pointer.
        /// \param robot the carlike robot,
        /// \param init, end Initial and final configurations of the path,
        /// \param curveLength distance traveled by the middle of the rear
        ///        wheel axis, negative values correspond to backward motions
        /// \param pathLength length of the interval of definition. Should be
        ///        positive,
        /// \param curvature curvature of the path,
        /// \param xyId id of degrees of freedom corresponding to (x,y)
        /// coordinates of robot,
        /// \param rzId id of degrees of freedom corresponding to orientation
        /// of robot.
        /// \param rz joint corresponding to orientation of robot,
        /// \param wheels vector of joints corresponding to wheels,
        /// \param constraints set of contraints the path is suject to.
        static ConstantCurvaturePtr_t create
        (const DevicePtr_t& robot, ConfigurationIn_t init,
         ConfigurationIn_t end,
         value_type curveLength, value_type pathLength,
         value_type curvature, size_type xyId, size_type rzId,
         const JointPtr_t rz, const std::vector<JointPtr_t> wheels,
         const ConstraintSetPtr_t& constraints);

         /// Create instance and return shared pointer.
        static ConstantCurvaturePtr_t createCopy
        (const ConstantCurvaturePtr_t& other);

        /// Create instance and return shared pointer.
        static ConstantCurvaturePtr_t createCopy
        (const ConstantCurvaturePtr_t& other,
         const ConstraintSetPtr_t& constraints);

        /// Return a shared pointer to a copy of this
        virtual PathPtr_t copy () const;

        /// Return a shared pointer to a copy of this with constraints
        /// \param constraints constraints to apply to the copy
        /// \pre *this should not have constraints.
        virtual PathPtr_t copy (const ConstraintSetPtr_t& constraints) const
        {
	  return createCopy (weak_.lock (), constraints);
        }

       /// Get the initial configuration
        inline Configuration_t initial () const
        {
          return initial_;
        }

        /// Get the final configuration
        inline Configuration_t end () const
        {
          return end_;
        }

        virtual PathPtr_t reverse () const;

        struct Wheels_t {
          value_type value; // Constant value of the wheel angle
          JointPtr_t j;
          Wheels_t () : j () {}
        };

      protected:
        /// Print path in a stream
        virtual std::ostream& print (std::ostream &os) const;

        /// Constructor
        /// \param robot the carlike robot,
        /// \param init, end Initial and final configurations of the path,
        /// \param curveLength distance traveled by the middle of the rear
        ///        wheel axis, negative values correspond to backward motions
        /// \param pathLength length of the interval of definition. Should be
        ///        positive,
        /// \param curvature curvature of the path,
        /// \param xyId id of degrees of freedom corresponding to (x,y)
        /// coordinates of robot,
        /// \param rzId id of degrees of freedom corresponding to orientation
        /// of robot.
        /// \param rz joint corresponding to orientation of robot,
        /// \param wheels vector of joints corresponding to wheels.
        ConstantCurvature (const DevicePtr_t& robot, ConfigurationIn_t init,
                           ConfigurationIn_t end,
                           value_type curveLength, value_type pathLength,
                           value_type curvature, size_type xyId,
                           size_type rzId, const JointPtr_t rz,
                           const std::vector<JointPtr_t> wheels);

        /// Constructor
        /// \param robot the carlike robot,
        /// \param init, end Initial and final configurations of the path,
        /// \param curveLength distance traveled by the middle of the rear
        ///        wheel axis, negative values correspond to backward motions
        /// \param pathLength length of the interval of definition. Should be
        ///        positive,
        /// \param curvature curvature of the path,
        /// \param xyId id of degrees of freedom corresponding to (x,y)
        /// coordinates of robot,
        /// \param rzId id of degrees of freedom corresponding to orientation
        /// of robot.
        /// \param rz joint corresponding to orientation of robot,
        /// \param wheels vector of joints corresponding to wheels,
        /// \param constraints set of contraints the path is suject to.
        ConstantCurvature (const DevicePtr_t& robot, ConfigurationIn_t init,
                           ConfigurationIn_t end,
                           value_type curveLength, value_type pathLength,
                           value_type curvature, size_type xyId, size_type rzId,
                           const JointPtr_t rz,
                           const std::vector<JointPtr_t> wheels,
                           ConstraintSetPtr_t constraints);

        /// Copy constructor
        ConstantCurvature (const ConstantCurvature& other);

        /// Copy constructor with constraints
        ConstantCurvature (const ConstantCurvature& other,
                           const ConstraintSetPtr_t& constraints);

        virtual bool impl_compute (ConfigurationOut_t result,
                                   value_type param) const;
        /// Virtual implementation of derivative
        virtual void impl_derivative
        (vectorOut_t result, const value_type& param, size_type order) const;
        /// Virtual implementation of velocity bound
        virtual void impl_velocityBound (vectorOut_t bound,
                                         const value_type& param0,
                                         const value_type& param1) const;

        /// Virtual implementation of path extraction
        virtual PathPtr_t impl_extract (const interval_t& paramInterval) const;

        /// store weak pointer to itself
        void init (const ConstantCurvatureWkPtr_t& weak)
        {
          parent_t::init (weak);
          weak_ = weak;
        }

        /// For serialization only.
        ConstantCurvature() : curvature_(0), xyId_(0), rzId_(0) {}
    private:
        /// Set the wheel joints for a car-like vehicle.
        ///
        /// \param rz joint from which the turning radius was computed.
        /// \param wheels bounded rotation joints.
        void setWheelJoints (const JointPtr_t rz,
                             const std::vector<JointPtr_t> wheels);

        DevicePtr_t robot_;
        Configuration_t initial_;
        Configuration_t end_;
        value_type curveLength_;
        const value_type curvature_;
        const size_type xyId_,rzId_;
        size_type dxyId_,drzId_;
        value_type forward_;
        std::vector<Wheels_t> wheels_;
        ConstantCurvatureWkPtr_t weak_;

        HPP_SERIALIZABLE();
      }; // class ConstantCurvature
    } // namespace steeringMethod
  } // namespace core
} // namespace hpp

#endif // HPP_CORE_STEERING_METHOD_CONSTANT_CURVATURE_HH
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_ISATRAITS_HH__
#define __ARCH_X86_ISATRAITS_HH__

#include "arch/x86/types.hh"
#include "arch/x86/x86_traits.hh"
#include "base/types.hh"

class StaticInstPtr;

namespace LittleEndianGuest {}

namespace X86ISA
{
    //This makes sure the little endian version of certain functions
    //are used.
    using namespace LittleEndianGuest;

    // X86 does not have a delay slot
#define ISA_HAS_DELAY_SLOT 0

    // X86 NOP (XCHG rAX, rAX)
    //XXX This needs to be set to an intermediate instruction struct
    //which encodes this instruction

    //4k. This value is not constant on x86.
    const int LogVMPageSize = 12;
    const int VMPageSize = (1 << LogVMPageSize);

    const int PageShift = 12;
    const int PageBytes = 1ULL << PageShift;

    const int BranchPredAddrShiftAmt = 0;

    StaticInstPtr decodeInst(ExtMachInst);

    // Memory accesses can be unaligned
    const bool HasUnalignedMemAcc = true;
};

#endif // __ARCH_X86_ISATRAITS_HH__
<commit_msg>X86: Define a noop ExtMachInst.<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_ISATRAITS_HH__
#define __ARCH_X86_ISATRAITS_HH__

#include "arch/x86/types.hh"
#include "arch/x86/x86_traits.hh"
#include "base/types.hh"

class StaticInstPtr;

namespace LittleEndianGuest {}

namespace X86ISA
{
    //This makes sure the little endian version of certain functions
    //are used.
    using namespace LittleEndianGuest;

    // X86 does not have a delay slot
#define ISA_HAS_DELAY_SLOT 0

    // X86 NOP (XCHG rAX, rAX)
    //XXX This needs to be set to an intermediate instruction struct
    //which encodes this instruction

    //4k. This value is not constant on x86.
    const int LogVMPageSize = 12;
    const int VMPageSize = (1 << LogVMPageSize);

    const int PageShift = 12;
    const int PageBytes = 1ULL << PageShift;

    const int BranchPredAddrShiftAmt = 0;

    StaticInstPtr decodeInst(ExtMachInst);

    // Memory accesses can be unaligned
    const bool HasUnalignedMemAcc = true;

    const ExtMachInst NoopMachInst = {
        0x0,                            // No legacy prefixes.
        0x0,                            // No rex prefix.
        { 1, 0x0, 0x0, 0x90 },          // One opcode byte, 0x90.
        0x0, 0x0,                       // No modrm or sib.
        0, 0,                           // No immediate or displacement.
        8, 8, 8,                        // All sizes are 8.
        0,                              // Displacement size is 0.
        SixtyFourBitMode                // Behave as if we're in 64 bit
                                        // mode (this doesn't actually matter).
    };
};

#endif // __ARCH_X86_ISATRAITS_HH__
<|endoftext|>


<commit_before>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp)
// Apache 2.0 License
#pragma once

namespace Jni
{
namespace Marshaling
{
	inline void NativeTypeTraits<bool>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source == JNI_TRUE;
	};

	inline void NativeTypeTraits<std::string>::FromJava( const JavaType& source, NativeType& destination )
	{
		auto local_env				= VirtualMachine::GetLocalEnvironment();
		const jsize string_length	= local_env->GetStringUTFLength( source );

		destination.clear();
		JNI_RETURN_IF( string_length == 0 );

		destination.resize( string_length, ' ' );
		local_env->GetStringUTFRegion( source, 0, string_length, &destination.front() );
	};

	inline void NativeTypeTraits<std::u16string>::FromJava( const JavaType& source, NativeType& destination )
	{
		auto local_env				= VirtualMachine::GetLocalEnvironment();
		const jsize string_length	= local_env->GetStringLength( source );

		destination.clear();
		JNI_RETURN_IF( string_length == 0 );

		destination.resize( string_length, ' ' );
		local_env->GetStringRegion( source, 0, string_length, reinterpret_cast<jchar*>( &destination.front() ) );
	};

	inline void NativeTypeTraits<float>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<double>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<int8_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<char16_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<int16_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<int32_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<int64_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<uint8_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<uint16_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<uint32_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<uint64_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	template< typename TNativeElementType, typename TAllocatorType >
	inline void NativeTypeTraits<std::vector<TNativeElementType, TAllocatorType>>::FromJava( const JavaType& source, NativeType& destination )
	{

	};
};
};
<commit_msg>Java array translation function.<commit_after>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp)
// Apache 2.0 License
#pragma once

namespace Jni
{
namespace Marshaling
{
	inline void NativeTypeTraits<bool>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source == JNI_TRUE;
	};

	inline void NativeTypeTraits<std::string>::FromJava( const JavaType& source, NativeType& destination )
	{
		auto local_env				= VirtualMachine::GetLocalEnvironment();
		const jsize string_length	= local_env->GetStringUTFLength( source );

		destination.clear();
		JNI_RETURN_IF( string_length == 0 );

		destination.resize( static_cast<size_t>( string_length ), ' ' );
		local_env->GetStringUTFRegion( source, 0, string_length, &destination.front() );
	};

	inline void NativeTypeTraits<std::u16string>::FromJava( const JavaType& source, NativeType& destination )
	{
		auto local_env				= VirtualMachine::GetLocalEnvironment();
		const jsize string_length	= local_env->GetStringLength( source );

		destination.clear();
		JNI_RETURN_IF( string_length == 0 );

		destination.resize( static_cast<size_t>( string_length ), ' ' );
		local_env->GetStringRegion( source, 0, string_length, reinterpret_cast<jchar*>( &destination.front() ) );
	};

	inline void NativeTypeTraits<float>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<double>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<int8_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<char16_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<int16_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<int32_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<int64_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<uint8_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<uint16_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<uint32_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	inline void NativeTypeTraits<uint64_t>::FromJava( const JavaType& source, NativeType& destination )
	{
		destination = source;
	};

	template< typename TNativeElementType, typename TAllocatorType >
	inline void NativeTypeTraits<std::vector<TNativeElementType, TAllocatorType>>::FromJava( const JavaType& source, NativeType& destination )
	{
		using ElementTraits = NativeTypeTraits<TNativeElementType>;

		destination.clear();

		auto local_env				= VirtualMachine::GetLocalEnvironment();
		const jsize array_length	= local_env->GetArrayLength( source );
		JNI_RETURN_IF( array_length == 0 );

		destination.reserve( static_cast<size_t>( array_length ) );
		if( ElementTraits::IS_PLAIN )
		{
			constexpr auto ARRAY_ELEMENTS_ACQUIRE_HANDLER	= ElementTraits::ARRAY_ELEMENTS_ACQUIRE_HANDLER;
			constexpr auto ARRAY_ELEMENTS_RELEASE_HANDLER	= ElementTraits::ARRAY_ELEMENTS_RELEASE_HANDLER;

			auto array_elements = (local_env->*ARRAY_ELEMENTS_ACQUIRE_HANDLER)( source, nullptr );
			JNI_RETURN_IF_E( array_elements == nullptr, , "Failed to read elements of array." );

			std::transform(
				array_elements, array_elements + array_length, std::back_inserter( destination ),
				[]( const ElementTraits::JavaType& stored_value )
				{
					return FromJava( stored_value );
				}
			);

			(local_env->*ARRAY_ELEMENTS_RELEASE_HANDLER)( source, array_elements, JNI_ABORT );
		}
		else
		{
			constexpr auto ARRAY_ELEMENT_READ_HANDLER = ElementTraits::ARRAY_ELEMENT_READ_HANDLER;

			for( jsize element_index = 0; element_index < array_length; ++element_index )
			{
				auto element = (local_env->*ARRAY_ELEMENT_READ_HANDLER)( source, element_index );
				destination.emplace_back( FromJava( element ) );
			};
		};
	};
};
};
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/qtimer.h>
#include <QtCore/qdebug.h>

#include <QtCore/qcoreevent.h>

#include <multimedia/qmediaplayer.h>

#include <multimedia/qmediaobject_p.h>
#include <multimedia/qmediaservice.h>
#include <multimedia/qmediaplayercontrol.h>
#include <multimedia/qmediaserviceprovider.h>
#include <multimedia/qmediaplaylist.h>
#include <multimedia/qmediaplaylistcontrol.h>

/*!
    \class QMediaPlayer
    \ingroup multimedia

    \preliminary
    \brief

    \sa
*/

class QMediaPlayerPrivate : public QMediaObjectPrivate
{
    Q_DECLARE_PUBLIC(QMediaPlayer)

public:
    QMediaPlayerPrivate():service(0), control(0) {}

    QMediaServiceProvider *provider;
    QMediaService* service;
    QMediaPlayerControl* control;
    QMediaPlayer::Error error;
    QString errorString;
    bool hasPlaylistControl;

    QMediaPlaylist *playlist;

    void _q_stateChanged(QMediaPlayer::State state);
    void _q_mediaStatusChanged(QMediaPlayer::MediaStatus status);
    void _q_error(int error, const QString &errorString);
    void _q_updateMedia(const QMediaSource&);
};

void QMediaPlayerPrivate::_q_stateChanged(QMediaPlayer::State ps)
{
    Q_Q(QMediaPlayer);

    if (ps == QMediaPlayer::PlayingState)
        q->addPropertyWatch("position");
    else
        q->removePropertyWatch("position");

    emit q->stateChanged(ps);
}

void QMediaPlayerPrivate::_q_mediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    Q_Q(QMediaPlayer);

    switch (status) {
    case QMediaPlayer::StalledMedia:
    case QMediaPlayer::BufferingMedia:
        q->addPropertyWatch("bufferStatus");
        emit q->mediaStatusChanged(status);
        break;
    case QMediaPlayer::EndOfMedia:
        q->removePropertyWatch("bufferStatus");
        if (playlist) {
            if (playlist->nextPosition(1) == -1)
                emit q->mediaStatusChanged(status);
            playlist->advance();
        }
        break;
    default:
        q->removePropertyWatch("bufferStatus");
        emit q->mediaStatusChanged(status);
        break;
    }

}

void QMediaPlayerPrivate::_q_error(int error, const QString &errorString)
{
    Q_Q(QMediaPlayer);

    this->error = QMediaPlayer::Error(error);
    this->errorString = errorString;

    emit q->error(this->error);
}

void QMediaPlayerPrivate::_q_updateMedia(const QMediaSource &media)
{
    Q_Q(QMediaPlayer);
    q->setMedia(media);
    if (!media.isNull())
        q->play();
    else
        q->stop();
}

/*!
    Construct a QMediaPlayer that uses the playback service from \a provider, parented to \a parent.

    If a playback service is not specified the system default will be used.
*/

QMediaPlayer::QMediaPlayer(QObject *parent, QMediaServiceProvider *provider):
    QMediaObject(*new QMediaPlayerPrivate, parent, provider->requestService("mediaplayer"))
{
    Q_D(QMediaPlayer);

    d->provider = provider;

    Q_ASSERT(d->service != 0);
    if (d->service != 0) {
        d->control = qobject_cast<QMediaPlayerControl*>(d->service->control(QMediaPlayerControl_iid));
        if (d->control != 0) {
            connect(d->control, SIGNAL(stateChanged(QMediaPlayer::State)), SLOT(_q_stateChanged(QMediaPlayer::State)));
            connect(d->control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
                    SLOT(_q_mediaStatusChanged(QMediaPlayer::MediaStatus)));
            connect(d->control, SIGNAL(error(int,QString)), SLOT(_q_error(int,QString)));

            connect(d->control, SIGNAL(durationChanged(qint64)), SIGNAL(durationChanged(qint64)));
            connect(d->control, SIGNAL(positionChanged(qint64)), SIGNAL(positionChanged(qint64)));
            connect(d->control, SIGNAL(videoAvailabilityChanged(bool)), SIGNAL(videoAvailabilityChanged(bool)));
            connect(d->control, SIGNAL(volumeChanged(int)), SIGNAL(volumeChanged(int)));
            connect(d->control, SIGNAL(mutingChanged(bool)), SIGNAL(mutingChanged(bool)));
            connect(d->control, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool)));

            if (d->control->state() == PlayingState)
                addPropertyWatch("position");

            if (d->control->mediaStatus() == StalledMedia || d->control->mediaStatus() == BufferingMedia)
                addPropertyWatch("bufferStatus");

            d->hasPlaylistControl = (d->service->control(QMediaPlaylistControl_iid) != 0);
        }
    }
}

/*!
    Destroys the player object.
*/

QMediaPlayer::~QMediaPlayer()
{
    Q_D(QMediaPlayer);

    d->provider->releaseService(d->service);
}

/*!
    \reimp
*/

bool QMediaPlayer::isValid() const
{
    return QMediaObject::isValid() && d_func()->control != 0;
}

QMediaSource QMediaPlayer::media() const
{
    return d_func()->control->media();
}

/*!
    Returns the stream source of media data.

    This is only valid if a stream was passed to setMedia().

    \sa setMedia()
*/

const QIODevice *QMediaPlayer::mediaStream() const
{
    return d_func()->control->mediaStream();
}

QMediaPlayer::State QMediaPlayer::state() const
{
    return QMediaPlayer::State(d_func()->control->state());
}

QMediaPlayer::MediaStatus QMediaPlayer::mediaStatus() const
{
    return QMediaPlayer::MediaStatus(d_func()->control->mediaStatus());
}

qint64 QMediaPlayer::duration() const
{
    return d_func()->control->duration();
}

qint64 QMediaPlayer::position() const
{
    return d_func()->control->position();
}

int QMediaPlayer::volume() const
{
    return d_func()->control->volume();
}

bool QMediaPlayer::isMuted() const
{
    return d_func()->control->isMuted();
}

int QMediaPlayer::bufferStatus() const
{
    return d_func()->control->bufferStatus();
}

bool QMediaPlayer::isVideoAvailable() const
{
    return d_func()->control->isVideoAvailable();
}

bool QMediaPlayer::isSeekable() const
{
    return d_func()->control->isSeekable();
}

float QMediaPlayer::playbackRate() const
{
    return d_func()->control->playbackRate();
}

/*!
    Returns the current error state.
*/

QMediaPlayer::Error QMediaPlayer::error() const
{
    return d_func()->error;
}

QString QMediaPlayer::errorString() const
{
    return d_func()->errorString;
}

//public Q_SLOTS:
/*!
    Start or resume playing the current source.
*/

void QMediaPlayer::play()
{
    Q_D(QMediaPlayer);

    if (d->playlist &&
        d->playlist->currentPosition() == -1 &&
        !d->playlist->isEmpty())
    {
        d->playlist->setCurrentPosition(0);
        return;
    }

    // Reset error conditions
    d->error = NoError;
    d->errorString = QString();

    d->control->play();
}

/*!
    Pause playing the current source.
*/

void QMediaPlayer::pause()
{
    d_func()->control->pause();
}

/*!
    Stop playing, and reset the play position to the beginning.
*/

void QMediaPlayer::stop()
{
    d_func()->control->stop();
}

void QMediaPlayer::setPosition(qint64 position)
{
    if (!isSeekable())
        return;

    d_func()->control->setPosition(qBound(qint64(0), duration(), position));
}

void QMediaPlayer::setVolume(int v)
{
    int clamped = qBound(0, v, 100);
    if (clamped == volume())
        return;

    d_func()->control->setVolume(clamped);
}

void QMediaPlayer::setMuted(bool muted)
{
    if (muted == isMuted())
        return;

    d_func()->control->setMuted(muted);
}

void QMediaPlayer::setPlaybackRate(float rate)
{
    d_func()->control->setPlaybackRate(rate);
}

/*!
    Sets the current \a media source.

    If a \a stream is supplied; media data will be read from it instead of resolving the media
    source.  In this case the media source may still be used to resolve additional information
    about the media such as mime type.
*/
void QMediaPlayer::setMedia(const QMediaSource &media, QIODevice *stream)
{
    d_func()->control->setMedia(media, stream);
}

/*!
    \internal
*/

void QMediaPlayer::bind(QObject *obj)
{
    Q_D(QMediaPlayer);

    if (!d->hasPlaylistControl) {
        QMediaPlaylist *playlist = qobject_cast<QMediaPlaylist*>(obj);

        if (playlist) {
            qDebug() << "playlist attached";
            d->playlist = playlist;
            connect(d->playlist, SIGNAL(currentMediaChanged(QMediaSource)),
                    this, SLOT(_q_updateMedia(QMediaSource)));
        }
    }
}

// Enums
/*!
    \enum QMediaPlayer::State

    Defines the current state of a media player.

    \value PlayingState The media player is currently playing content.
    \value PausedState The media player has paused playback, playback of the current track will
    resume from the position the player was paused at.
    \value StoppedState The media player is not playing content, playback will begin from the start
    of the current track.
*/

/*!
    \enum QMediaPlayer::MediaStatus

    Defines the status of a media player's current media.

    \value UnknownMediaStatus The status of the media cannot be determined.
    \value NoMedia The is no current media.  The player is in the StoppedState.
    \value LoadingMedia The current media is being loaded. The player may be in any state.
    \value LoadedMedia The current media has been loaded. The player is in the StoppedState.
    \value StalledMedia Playback of the current media has stalled due to insufficient buffering or
    some other temporary interruption.  The player is in the PlayingState or PausedState.
    \value BufferingMedia The player is buffering data but has enough data buffered for playback to
    continue for the immediate future.  The player is in the PlayingState or PausedState.
    \value BufferedMedia The player has fully buffered the current media.  The player is in the
    PlayingState or PausedState.
    \value EndOfMedia Playback has reached the end of the current media.  The player is in the
    StoppedState.
    \value InvalidMedia The current media cannot be played.  The player is in the StoppedState.
*/

/*!
    \enum QMediaPlayer::Error

    Defines a media player error condition.

    \value NoError No error has occurred.
    \value ResourceError A media resource couldn't be resolved.
    \value FormatError The format of a media resource isn't (fully) supported.  Playback may still
    be possible, but without an audio or video component.
    \value NetworkError A network error occurred.
    \value AccessDeniedError There are not the appropriate permissions to play a media resource
*/

// Signals
/*!
    \fn QMediaPlayer::error(QMediaPlayer::Error error)

    Signals that an \a error condition has occurred.

    \sa errorString()
*/

/*!
    \fn void QMediaPlayer::stateChanged(State state)

    Signal the \a state of the Player object has changed.
*/

/*!
    \fn QMediaPlayer::mediaStatusChanged(QMediaPlayer::MediaStatus status)

    Signals that the \a status of the current media has changed.

    \sa mediaStatus()
*/

/*!
    \fn void QMediaPlayer::mediaChanged(const QMediaSource &media);

    Signals that the current playing content will be obtained from \a media.

    \sa media()
*/

/*!
    \fn void QMediaPlayer::playbackRateChanged(float rate);

    Signals the playbackRate has changed to \a rate.
*/

/*!
    \fn void QMediaPlayer::seekableChanged(bool seekable);

    Signals the \a seekable status of the player object has changed.
*/

// Properties
/*!
    \property QMediaPlayer::state
    \brief the media player's playback state.

    By default this property is QMediaPlayer::Stopped

    \sa mediaStatus(), play(), pause(), stop()
*/

/*!
    \property QMediaPlayer::error
    \brief a string describing the last error condition.

    \sa error()
*/

/*!
    \property QMediaPlayer::media
    \brief The media currently being by the player object.

    The player object will use the QMediaSource for selection of the content to
    be played.

    By default this property has a null QMediaSource.

    \sa QMediaSource
*/

/*!
    \property QMediaPlayer::mediaStatus
    \brief the status of the current media stream.

    The stream status describes how the playback of the current stream is progressing.

    By default this property is QMediaPlayer::NoMedia

    \sa state
*/

/*!
    \property QMediaPlayer::duration
    \brief The total playback time in milliseconds of the current source.
*/

/*!
    \property QMediaPlayer::position
    \brief The current playback position in milliseconds from the beginning.
*/

/*!
    \property QMediaPlayer::volume
    \brief The current playback volume. Volume is a linear effect from 0-100.
*/

/*!
    \property QMediaPlayer::muted
    \brief true if the playback volume is muted; otherwise false.
*/

/*!
    \property QMediaPlayer::bufferStatus
    \brief When buffering; returns the percent of the local buffer filled.
*/

/*!
    \property QMediaPlayer::videoAvailable
    \brief true if there is visual content available; otherwise false.
*/

/*!
    \property QMediaPlayer::seekable
    \brief true if the currently playing content is seekable; otherwise false.
*/

/*!
    \property QMediaPlayer::playbackRate
    \brief the rate of playback
*/

/*!
    \fn void QMediaPlayer::durationChanged(qint64 duration)

    Signal the duration of the content has changed to \a duration, expressed in milliseconds.
*/

/*!
    \fn void QMediaPlayer::positionChanged(qint64 position)

    Signal the position of the content has changed to \a position, expressed in
    milliseconds approximately every 1000milliseconds.
*/

/*!
    \fn void QMediaPlayer::volumeChanged(int volume)

    Signal the playback volume has changed to \a volume.
*/

/*!
    \fn void QMediaPlayer::mutingChanged(bool muted)

    Signal the mute state has changed to \a muted.
*/

/*!
    \fn void QMediaPlayer::videoAvailabilityChanged(bool videoAvailable)

    Signal the availability of visual cntent has changed to \a videoAvailable.
*/

/*!
    \fn void QMediaPlayer::bufferStatusChanged(int percentFilled)

    Signal the amount of the local buffer filled as a percentage by \a percentFilled.
*/

#include "moc_qmediaplayer.cpp"
<commit_msg>fixed QMediaPlayer according to QMediaObject changes<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/qtimer.h>
#include <QtCore/qdebug.h>

#include <QtCore/qcoreevent.h>

#include <multimedia/qmediaplayer.h>

#include <multimedia/qmediaobject_p.h>
#include <multimedia/qmediaservice.h>
#include <multimedia/qmediaplayercontrol.h>
#include <multimedia/qmediaserviceprovider.h>
#include <multimedia/qmediaplaylist.h>
#include <multimedia/qmediaplaylistcontrol.h>

/*!
    \class QMediaPlayer
    \ingroup multimedia

    \preliminary
    \brief

    \sa
*/

class QMediaPlayerPrivate : public QMediaObjectPrivate
{
    Q_DECLARE_PUBLIC(QMediaPlayer)

public:
    QMediaPlayerPrivate(): control(0) {}

    QMediaServiceProvider *provider;
    QMediaPlayerControl* control;
    QMediaPlayer::Error error;
    QString errorString;
    bool hasPlaylistControl;

    QMediaPlaylist *playlist;

    void _q_stateChanged(QMediaPlayer::State state);
    void _q_mediaStatusChanged(QMediaPlayer::MediaStatus status);
    void _q_error(int error, const QString &errorString);
    void _q_updateMedia(const QMediaSource&);
};

void QMediaPlayerPrivate::_q_stateChanged(QMediaPlayer::State ps)
{
    Q_Q(QMediaPlayer);

    if (ps == QMediaPlayer::PlayingState)
        q->addPropertyWatch("position");
    else
        q->removePropertyWatch("position");

    emit q->stateChanged(ps);
}

void QMediaPlayerPrivate::_q_mediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    Q_Q(QMediaPlayer);

    switch (status) {
    case QMediaPlayer::StalledMedia:
    case QMediaPlayer::BufferingMedia:
        q->addPropertyWatch("bufferStatus");
        emit q->mediaStatusChanged(status);
        break;
    case QMediaPlayer::EndOfMedia:
        q->removePropertyWatch("bufferStatus");
        if (playlist) {
            if (playlist->nextPosition(1) == -1)
                emit q->mediaStatusChanged(status);
            playlist->advance();
        }
        break;
    default:
        q->removePropertyWatch("bufferStatus");
        emit q->mediaStatusChanged(status);
        break;
    }

}

void QMediaPlayerPrivate::_q_error(int error, const QString &errorString)
{
    Q_Q(QMediaPlayer);

    this->error = QMediaPlayer::Error(error);
    this->errorString = errorString;

    emit q->error(this->error);
}

void QMediaPlayerPrivate::_q_updateMedia(const QMediaSource &media)
{
    Q_Q(QMediaPlayer);
    q->setMedia(media);
    if (!media.isNull())
        q->play();
    else
        q->stop();
}

/*!
    Construct a QMediaPlayer that uses the playback service from \a provider, parented to \a parent.

    If a playback service is not specified the system default will be used.
*/

QMediaPlayer::QMediaPlayer(QObject *parent, QMediaServiceProvider *provider):
    QMediaObject(*new QMediaPlayerPrivate, parent, provider->requestService("mediaplayer"))
{
    Q_D(QMediaPlayer);

    d->provider = provider;

    Q_ASSERT(service() != 0);
    if (service() != 0) {
        d->control = qobject_cast<QMediaPlayerControl*>(service()->control(QMediaPlayerControl_iid));
        if (d->control != 0) {
            connect(d->control, SIGNAL(stateChanged(QMediaPlayer::State)), SLOT(_q_stateChanged(QMediaPlayer::State)));
            connect(d->control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
                    SLOT(_q_mediaStatusChanged(QMediaPlayer::MediaStatus)));
            connect(d->control, SIGNAL(error(int,QString)), SLOT(_q_error(int,QString)));

            connect(d->control, SIGNAL(durationChanged(qint64)), SIGNAL(durationChanged(qint64)));
            connect(d->control, SIGNAL(positionChanged(qint64)), SIGNAL(positionChanged(qint64)));
            connect(d->control, SIGNAL(videoAvailabilityChanged(bool)), SIGNAL(videoAvailabilityChanged(bool)));
            connect(d->control, SIGNAL(volumeChanged(int)), SIGNAL(volumeChanged(int)));
            connect(d->control, SIGNAL(mutingChanged(bool)), SIGNAL(mutingChanged(bool)));
            connect(d->control, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool)));

            if (d->control->state() == PlayingState)
                addPropertyWatch("position");

            if (d->control->mediaStatus() == StalledMedia || d->control->mediaStatus() == BufferingMedia)
                addPropertyWatch("bufferStatus");

            d->hasPlaylistControl = (service()->control(QMediaPlaylistControl_iid) != 0);
        }
    }
}

/*!
    Destroys the player object.
*/

QMediaPlayer::~QMediaPlayer()
{
    Q_D(QMediaPlayer);

    d->provider->releaseService(service());
}

/*!
    \reimp
*/

bool QMediaPlayer::isValid() const
{
    return QMediaObject::isValid() && d_func()->control != 0;
}

QMediaSource QMediaPlayer::media() const
{
    return d_func()->control->media();
}

/*!
    Returns the stream source of media data.

    This is only valid if a stream was passed to setMedia().

    \sa setMedia()
*/

const QIODevice *QMediaPlayer::mediaStream() const
{
    return d_func()->control->mediaStream();
}

QMediaPlayer::State QMediaPlayer::state() const
{
    return QMediaPlayer::State(d_func()->control->state());
}

QMediaPlayer::MediaStatus QMediaPlayer::mediaStatus() const
{
    return QMediaPlayer::MediaStatus(d_func()->control->mediaStatus());
}

qint64 QMediaPlayer::duration() const
{
    return d_func()->control->duration();
}

qint64 QMediaPlayer::position() const
{
    return d_func()->control->position();
}

int QMediaPlayer::volume() const
{
    return d_func()->control->volume();
}

bool QMediaPlayer::isMuted() const
{
    return d_func()->control->isMuted();
}

int QMediaPlayer::bufferStatus() const
{
    return d_func()->control->bufferStatus();
}

bool QMediaPlayer::isVideoAvailable() const
{
    return d_func()->control->isVideoAvailable();
}

bool QMediaPlayer::isSeekable() const
{
    return d_func()->control->isSeekable();
}

float QMediaPlayer::playbackRate() const
{
    return d_func()->control->playbackRate();
}

/*!
    Returns the current error state.
*/

QMediaPlayer::Error QMediaPlayer::error() const
{
    return d_func()->error;
}

QString QMediaPlayer::errorString() const
{
    return d_func()->errorString;
}

//public Q_SLOTS:
/*!
    Start or resume playing the current source.
*/

void QMediaPlayer::play()
{
    Q_D(QMediaPlayer);

    if (d->playlist &&
        d->playlist->currentPosition() == -1 &&
        !d->playlist->isEmpty())
    {
        d->playlist->setCurrentPosition(0);
        return;
    }

    // Reset error conditions
    d->error = NoError;
    d->errorString = QString();

    d->control->play();
}

/*!
    Pause playing the current source.
*/

void QMediaPlayer::pause()
{
    d_func()->control->pause();
}

/*!
    Stop playing, and reset the play position to the beginning.
*/

void QMediaPlayer::stop()
{
    d_func()->control->stop();
}

void QMediaPlayer::setPosition(qint64 position)
{
    if (!isSeekable())
        return;

    d_func()->control->setPosition(qBound(qint64(0), duration(), position));
}

void QMediaPlayer::setVolume(int v)
{
    int clamped = qBound(0, v, 100);
    if (clamped == volume())
        return;

    d_func()->control->setVolume(clamped);
}

void QMediaPlayer::setMuted(bool muted)
{
    if (muted == isMuted())
        return;

    d_func()->control->setMuted(muted);
}

void QMediaPlayer::setPlaybackRate(float rate)
{
    d_func()->control->setPlaybackRate(rate);
}

/*!
    Sets the current \a media source.

    If a \a stream is supplied; media data will be read from it instead of resolving the media
    source.  In this case the media source may still be used to resolve additional information
    about the media such as mime type.
*/
void QMediaPlayer::setMedia(const QMediaSource &media, QIODevice *stream)
{
    d_func()->control->setMedia(media, stream);
}

/*!
    \internal
*/

void QMediaPlayer::bind(QObject *obj)
{
    Q_D(QMediaPlayer);

    if (!d->hasPlaylistControl) {
        QMediaPlaylist *playlist = qobject_cast<QMediaPlaylist*>(obj);

        if (playlist) {
            qDebug() << "playlist attached";
            d->playlist = playlist;
            connect(d->playlist, SIGNAL(currentMediaChanged(QMediaSource)),
                    this, SLOT(_q_updateMedia(QMediaSource)));
        }
    }
}

// Enums
/*!
    \enum QMediaPlayer::State

    Defines the current state of a media player.

    \value PlayingState The media player is currently playing content.
    \value PausedState The media player has paused playback, playback of the current track will
    resume from the position the player was paused at.
    \value StoppedState The media player is not playing content, playback will begin from the start
    of the current track.
*/

/*!
    \enum QMediaPlayer::MediaStatus

    Defines the status of a media player's current media.

    \value UnknownMediaStatus The status of the media cannot be determined.
    \value NoMedia The is no current media.  The player is in the StoppedState.
    \value LoadingMedia The current media is being loaded. The player may be in any state.
    \value LoadedMedia The current media has been loaded. The player is in the StoppedState.
    \value StalledMedia Playback of the current media has stalled due to insufficient buffering or
    some other temporary interruption.  The player is in the PlayingState or PausedState.
    \value BufferingMedia The player is buffering data but has enough data buffered for playback to
    continue for the immediate future.  The player is in the PlayingState or PausedState.
    \value BufferedMedia The player has fully buffered the current media.  The player is in the
    PlayingState or PausedState.
    \value EndOfMedia Playback has reached the end of the current media.  The player is in the
    StoppedState.
    \value InvalidMedia The current media cannot be played.  The player is in the StoppedState.
*/

/*!
    \enum QMediaPlayer::Error

    Defines a media player error condition.

    \value NoError No error has occurred.
    \value ResourceError A media resource couldn't be resolved.
    \value FormatError The format of a media resource isn't (fully) supported.  Playback may still
    be possible, but without an audio or video component.
    \value NetworkError A network error occurred.
    \value AccessDeniedError There are not the appropriate permissions to play a media resource
*/

// Signals
/*!
    \fn QMediaPlayer::error(QMediaPlayer::Error error)

    Signals that an \a error condition has occurred.

    \sa errorString()
*/

/*!
    \fn void QMediaPlayer::stateChanged(State state)

    Signal the \a state of the Player object has changed.
*/

/*!
    \fn QMediaPlayer::mediaStatusChanged(QMediaPlayer::MediaStatus status)

    Signals that the \a status of the current media has changed.

    \sa mediaStatus()
*/

/*!
    \fn void QMediaPlayer::mediaChanged(const QMediaSource &media);

    Signals that the current playing content will be obtained from \a media.

    \sa media()
*/

/*!
    \fn void QMediaPlayer::playbackRateChanged(float rate);

    Signals the playbackRate has changed to \a rate.
*/

/*!
    \fn void QMediaPlayer::seekableChanged(bool seekable);

    Signals the \a seekable status of the player object has changed.
*/

// Properties
/*!
    \property QMediaPlayer::state
    \brief the media player's playback state.

    By default this property is QMediaPlayer::Stopped

    \sa mediaStatus(), play(), pause(), stop()
*/

/*!
    \property QMediaPlayer::error
    \brief a string describing the last error condition.

    \sa error()
*/

/*!
    \property QMediaPlayer::media
    \brief The media currently being by the player object.

    The player object will use the QMediaSource for selection of the content to
    be played.

    By default this property has a null QMediaSource.

    \sa QMediaSource
*/

/*!
    \property QMediaPlayer::mediaStatus
    \brief the status of the current media stream.

    The stream status describes how the playback of the current stream is progressing.

    By default this property is QMediaPlayer::NoMedia

    \sa state
*/

/*!
    \property QMediaPlayer::duration
    \brief The total playback time in milliseconds of the current source.
*/

/*!
    \property QMediaPlayer::position
    \brief The current playback position in milliseconds from the beginning.
*/

/*!
    \property QMediaPlayer::volume
    \brief The current playback volume. Volume is a linear effect from 0-100.
*/

/*!
    \property QMediaPlayer::muted
    \brief true if the playback volume is muted; otherwise false.
*/

/*!
    \property QMediaPlayer::bufferStatus
    \brief When buffering; returns the percent of the local buffer filled.
*/

/*!
    \property QMediaPlayer::videoAvailable
    \brief true if there is visual content available; otherwise false.
*/

/*!
    \property QMediaPlayer::seekable
    \brief true if the currently playing content is seekable; otherwise false.
*/

/*!
    \property QMediaPlayer::playbackRate
    \brief the rate of playback
*/

/*!
    \fn void QMediaPlayer::durationChanged(qint64 duration)

    Signal the duration of the content has changed to \a duration, expressed in milliseconds.
*/

/*!
    \fn void QMediaPlayer::positionChanged(qint64 position)

    Signal the position of the content has changed to \a position, expressed in
    milliseconds approximately every 1000milliseconds.
*/

/*!
    \fn void QMediaPlayer::volumeChanged(int volume)

    Signal the playback volume has changed to \a volume.
*/

/*!
    \fn void QMediaPlayer::mutingChanged(bool muted)

    Signal the mute state has changed to \a muted.
*/

/*!
    \fn void QMediaPlayer::videoAvailabilityChanged(bool videoAvailable)

    Signal the availability of visual cntent has changed to \a videoAvailable.
*/

/*!
    \fn void QMediaPlayer::bufferStatusChanged(int percentFilled)

    Signal the amount of the local buffer filled as a percentage by \a percentFilled.
*/

#include "moc_qmediaplayer.cpp"
<|endoftext|>


<commit_before>
#include <gloperate-qt/scripting/ScriptEnvironment.h>

#include <QObject>

#include <scriptzeug/ScriptContext.h>

#include <widgetzeug/ScriptPromptWidget.h>
#include <widgetzeug/ECMA26251_SyntaxHighlighter.h>
#include <widgetzeug/ECMA26251_Completer.h>

#include <gloperate-qt/viewer/QtOpenGLWindow.h>
#include <gloperate-qt/scripting/SystemApi.h>
#include <gloperate-qt/scripting/SystemApi.h>
#include <gloperate-qt/scripting/TimerApi.h>

namespace gloperate_qt
{

ScriptEnvironment::ScriptEnvironment(QtOpenGLWindow * openGLWindow)
: m_openGLWindow(nullptr)
, m_scriptPrompt(nullptr)
{
    // Create JavaScript context
    m_scriptContext.reset(new scriptzeug::ScriptContext("javascript"));

    // Register default scripting APIs
    m_systemApi.reset(new SystemApi(openGLWindow));
    addScriptApi(m_systemApi.get());

    m_timerApi.reset(new TimerApi);
    addScriptApi(m_timerApi.get());

    // Connect events to scripting
    if (openGLWindow) {
        // Promote keyboard events to scripting api
        openGLWindow->installEventFilter(m_systemApi.get());

        // Promote tick events to scripting api
        openGLWindow->setTimerApi(m_timerApi.get());
    }

    // Connect commands that have been loaded by API functions (e.g., system.load)
    m_systemApi->command.connect([this] (const std::string & cmd) {
        // Execute code
        execute(cmd);
    } );

    // Add global functions
    std::string script =
        "function help() {\n"
        "  system.help();\n"
        "}\n"
        "\n"
        "function load(filename) {\n"
        "  system.load(filename);\n"
        "}\n"
        "\n"
        "function print(value) {\n"
        "  system.print(value);\n"
        "}\n"
        "\n"
        "function exit() {\n"
        "  system.exit();\n"
        "}\n"
        "\n"
        "function quit() {\n"
        "  system.exit();\n"
        "}\n";
    execute(script);
}

ScriptEnvironment::~ScriptEnvironment()
{
}

const scriptzeug::ScriptContext * ScriptEnvironment::scriptContext() const
{
    return m_scriptContext.get();
}

scriptzeug::ScriptContext * ScriptEnvironment::scriptContext()
{
    return m_scriptContext.get();
}

void ScriptEnvironment::addScriptApi(reflectionzeug::Object * api)
{
    // Add script API to list
    m_apis.push_back(api);

    // Connect object to scripting engine
    m_scriptContext->registerObject(api);

    // Register name as extra word for word completion
    if (m_scriptPrompt) {
        widgetzeug::ScriptCompleter * completer = static_cast<widgetzeug::ScriptCompleter *>(m_scriptPrompt->completer());
        if (completer) {
            completer->registerWord(QString::fromStdString(api->name()));
        }
    }
}

void ScriptEnvironment::removeScriptApi(reflectionzeug::Object * api)
{
    // Unregister object from scripting engine
    m_scriptContext->unregisterObject(api);
}

void ScriptEnvironment::connectScriptingConsole(widgetzeug::ScriptPromptWidget * console)
{
    // Check parameters
    if (!console) {
        return;
    }

    // Save scripting console
    m_scriptPrompt = console;

    // Execute commands that have been typed on the scripting console
    QObject::connect(m_scriptPrompt, &widgetzeug::ScriptPromptWidget::evaluate, [this] (const QString & cmd) {
        this->execute(cmd.toStdString());
    });

    // Connect script output (system.print)
    m_systemApi->output.connect([this] (const std::string & msg) {
        // Print message onto the scripting console
        m_scriptPrompt->print(QString::fromStdString(msg));
    });

    // Add additional auto completion words
    widgetzeug::ScriptCompleter * completer = static_cast<widgetzeug::ScriptCompleter *>(m_scriptPrompt->completer());
    if (completer) {
        // Add script API names
        for (reflectionzeug::Object * api : m_apis) {
            completer->registerWord(QString::fromStdString(api->name()));
        }

        // Add global function names
        completer->registerWords(QStringList() << "help" << "load" << "print" << "exit");
    }
}

reflectionzeug::Variant ScriptEnvironment::execute(const std::string & command)
{
    // Substitute shortcut commands
    std::string cmd = command;
    if (cmd == "help") {
        cmd = "help()";
    } else if (cmd == "exit" || cmd == "quit") {
        cmd = "exit()";
    }

    // Execute command
    return m_scriptContext->evaluate(cmd);
}

void ScriptEnvironment::setHelpText(const std::string & text)
{
    m_systemApi->setHelpText(text);
}

} // namespace gloperate_qt
<commit_msg>Register scriptException callback in ScriptEnvironment.<commit_after>
#include <gloperate-qt/scripting/ScriptEnvironment.h>

#include <iostream>

#include <QObject>

#include <scriptzeug/ScriptContext.h>

#include <widgetzeug/ScriptPromptWidget.h>
#include <widgetzeug/ECMA26251_SyntaxHighlighter.h>
#include <widgetzeug/ECMA26251_Completer.h>

#include <gloperate-qt/viewer/QtOpenGLWindow.h>
#include <gloperate-qt/scripting/SystemApi.h>
#include <gloperate-qt/scripting/SystemApi.h>
#include <gloperate-qt/scripting/TimerApi.h>

namespace gloperate_qt
{

ScriptEnvironment::ScriptEnvironment(QtOpenGLWindow * openGLWindow)
: m_openGLWindow(nullptr)
, m_scriptPrompt(nullptr)
{
    // Create JavaScript context
    m_scriptContext.reset(new scriptzeug::ScriptContext("javascript"));

    // Output scripting errors to console
    m_scriptContext->scriptException.connect( [] (const std::string & error) -> void {
        std::cerr << "Scripting Error: " << error << std::endl;
    });

    // Register default scripting APIs
    m_systemApi.reset(new SystemApi(openGLWindow));
    addScriptApi(m_systemApi.get());

    m_timerApi.reset(new TimerApi);
    addScriptApi(m_timerApi.get());

    // Connect events to scripting
    if (openGLWindow) {
        // Promote keyboard events to scripting api
        openGLWindow->installEventFilter(m_systemApi.get());

        // Promote tick events to scripting api
        openGLWindow->setTimerApi(m_timerApi.get());
    }

    // Connect commands that have been loaded by API functions (e.g., system.load)
    m_systemApi->command.connect([this] (const std::string & cmd) {
        // Execute code
        execute(cmd);
    } );

    // Add global functions
    std::string script =
        "function help() {\n"
        "  system.help();\n"
        "}\n"
        "\n"
        "function load(filename) {\n"
        "  system.load(filename);\n"
        "}\n"
        "\n"
        "function print(value) {\n"
        "  system.print(value);\n"
        "}\n"
        "\n"
        "function exit() {\n"
        "  system.exit();\n"
        "}\n"
        "\n"
        "function quit() {\n"
        "  system.exit();\n"
        "}\n";
    execute(script);
}

ScriptEnvironment::~ScriptEnvironment()
{
}

const scriptzeug::ScriptContext * ScriptEnvironment::scriptContext() const
{
    return m_scriptContext.get();
}

scriptzeug::ScriptContext * ScriptEnvironment::scriptContext()
{
    return m_scriptContext.get();
}

void ScriptEnvironment::addScriptApi(reflectionzeug::Object * api)
{
    // Add script API to list
    m_apis.push_back(api);

    // Connect object to scripting engine
    m_scriptContext->registerObject(api);

    // Register name as extra word for word completion
    if (m_scriptPrompt) {
        widgetzeug::ScriptCompleter * completer = static_cast<widgetzeug::ScriptCompleter *>(m_scriptPrompt->completer());
        if (completer) {
            completer->registerWord(QString::fromStdString(api->name()));
        }
    }
}

void ScriptEnvironment::removeScriptApi(reflectionzeug::Object * api)
{
    // Unregister object from scripting engine
    m_scriptContext->unregisterObject(api);
}

void ScriptEnvironment::connectScriptingConsole(widgetzeug::ScriptPromptWidget * console)
{
    // Check parameters
    if (!console) {
        return;
    }

    // Save scripting console
    m_scriptPrompt = console;

    // Execute commands that have been typed on the scripting console
    QObject::connect(m_scriptPrompt, &widgetzeug::ScriptPromptWidget::evaluate, [this] (const QString & cmd) {
        this->execute(cmd.toStdString());
    });

    // Connect script output (system.print)
    m_systemApi->output.connect([this] (const std::string & msg) {
        // Print message onto the scripting console
        m_scriptPrompt->print(QString::fromStdString(msg));
    });

    // Add additional auto completion words
    widgetzeug::ScriptCompleter * completer = static_cast<widgetzeug::ScriptCompleter *>(m_scriptPrompt->completer());
    if (completer) {
        // Add script API names
        for (reflectionzeug::Object * api : m_apis) {
            completer->registerWord(QString::fromStdString(api->name()));
        }

        // Add global function names
        completer->registerWords(QStringList() << "help" << "load" << "print" << "exit");
    }
}

reflectionzeug::Variant ScriptEnvironment::execute(const std::string & command)
{
    // Substitute shortcut commands
    std::string cmd = command;
    if (cmd == "help") {
        cmd = "help()";
    } else if (cmd == "exit" || cmd == "quit") {
        cmd = "exit()";
    }

    // Execute command
    return m_scriptContext->evaluate(cmd);
}

void ScriptEnvironment::setHelpText(const std::string & text)
{
    m_systemApi->setHelpText(text);
}

} // namespace gloperate_qt
<|endoftext|>