diff options
author | Zeno Albisser <zeno.albisser@digia.com> | 2013-08-15 21:46:11 +0200 |
---|---|---|
committer | Zeno Albisser <zeno.albisser@digia.com> | 2013-08-15 21:46:11 +0200 |
commit | 679147eead574d186ebf3069647b4c23e8ccace6 (patch) | |
tree | fc247a0ac8ff119f7c8550879ebb6d3dd8d1ff69 /chromium/ppapi/cpp | |
download | qtwebengine-chromium-679147eead574d186ebf3069647b4c23e8ccace6.tar.gz |
Initial import.
Diffstat (limited to 'chromium/ppapi/cpp')
226 files changed, 26522 insertions, 0 deletions
diff --git a/chromium/ppapi/cpp/DEPS b/chromium/ppapi/cpp/DEPS new file mode 100644 index 00000000000..af2aa4c055f --- /dev/null +++ b/chromium/ppapi/cpp/DEPS @@ -0,0 +1,16 @@ +# ppapi/cpp should not be dependent on other parts of chromium; it should stay +# browser-neutral as much as possible. +include_rules = [ + "-base", + "-build", + "-ipc", + "-uncode", + "-testing", + "-ppapi", + "+ppapi/c", + "-ppapi/c/private", + "-ppapi/c/trusted", + "+ppapi/cpp", + "-ppapi/cpp/private", + "-ppapi/cpp/trusted", +] diff --git a/chromium/ppapi/cpp/array_output.cc b/chromium/ppapi/cpp/array_output.cc new file mode 100644 index 00000000000..62252f72562 --- /dev/null +++ b/chromium/ppapi/cpp/array_output.cc @@ -0,0 +1,41 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/array_output.h" + +#include "ppapi/cpp/logging.h" + +namespace pp { + +// static +void* ArrayOutputAdapterBase::GetDataBufferThunk(void* user_data, + uint32_t element_count, + uint32_t element_size) { + return static_cast<ArrayOutputAdapterBase*>(user_data)-> + GetDataBuffer(element_count, element_size); +} + +VarArrayOutputAdapterWithStorage::VarArrayOutputAdapterWithStorage() + : ArrayOutputAdapter<PP_Var>() { + set_output(&temp_storage_); +} + +VarArrayOutputAdapterWithStorage::~VarArrayOutputAdapterWithStorage() { + if (!temp_storage_.empty()) { + // An easy way to release the var references held by this object. + output(); + } +} + +std::vector<Var>& VarArrayOutputAdapterWithStorage::output() { + PP_DCHECK(output_storage_.empty()); + + output_storage_.reserve(temp_storage_.size()); + for (size_t i = 0; i < temp_storage_.size(); i++) + output_storage_.push_back(Var(PASS_REF, temp_storage_[i])); + temp_storage_.clear(); + return output_storage_; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/array_output.h b/chromium/ppapi/cpp/array_output.h new file mode 100644 index 00000000000..fe0bbc335bc --- /dev/null +++ b/chromium/ppapi/cpp/array_output.h @@ -0,0 +1,272 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_ARRAY_OUTPUT_H_ +#define PPAPI_CPP_ARRAY_OUTPUT_H_ + +#include <vector> + +#include "ppapi/c/pp_array_output.h" +#include "ppapi/c/pp_resource.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +// Converts the given array of PP_Resources into an array of the requested +// C++ resource types, passing ownership of a reference in the process. +// +// This is used to convert output arrays of resources that the browser has +// generated into the more convenient C++ wrappers for those resources. The +// initial "PassRef" parameter is there to emphasize what happens to the +// reference count of the input resource and to match the resource constructors +// that look the same. +template<typename ResourceObjectType> +inline void ConvertPPResourceArrayToObjects( + PassRef, + const std::vector<PP_Resource>& input, + std::vector<ResourceObjectType>* output) { + output->resize(0); + output->reserve(input.size()); + for (size_t i = 0; i < input.size(); i++) + output->push_back(ResourceObjectType(PASS_REF, input[i])); +} + +// Non-templatized base class for the array output conversion. It provides the +// C implementation of a PP_ArrayOutput whose callback function is implemented +// as a virtual call on a derived class. Do not use directly, use one of the +// derived classes below. +class ArrayOutputAdapterBase { + public: + ArrayOutputAdapterBase() { + pp_array_output_.GetDataBuffer = + &ArrayOutputAdapterBase::GetDataBufferThunk; + pp_array_output_.user_data = this; + } + virtual ~ArrayOutputAdapterBase() {} + + const PP_ArrayOutput& pp_array_output() { return pp_array_output_; } + + protected: + virtual void* GetDataBuffer(uint32_t element_count, + uint32_t element_size) = 0; + + private: + static void* GetDataBufferThunk(void* user_data, + uint32_t element_count, + uint32_t element_size); + + PP_ArrayOutput pp_array_output_; + + // Disallow copying and assignment. This will do the wrong thing for most + // subclasses. + ArrayOutputAdapterBase(const ArrayOutputAdapterBase&); + ArrayOutputAdapterBase& operator=(const ArrayOutputAdapterBase&); +}; + +// This adapter provides functionality for implementing a PP_ArrayOutput +// structure as writing to a given vector object. +// +// This is generally used internally in the C++ wrapper objects to +// write into an output parameter supplied by the plugin. If the element size +// that the browser is writing does not match the size of the type we're using +// this will assert and return NULL (which will cause the browser to fail the +// call). +// +// Example that allows the browser to write into a given vector: +// void DoFoo(std::vector<int>* results) { +// ArrayOutputAdapter<int> adapter(results); +// ppb_foo->DoFoo(adapter.pp_array_output()); +// } +template<typename T> +class ArrayOutputAdapter : public ArrayOutputAdapterBase { + public: + ArrayOutputAdapter(std::vector<T>* output) : output_(output) {} + + protected: + // Two-step init for the "with storage" version below. + ArrayOutputAdapter() : output_(NULL) {} + void set_output(std::vector<T>* output) { output_ = output; } + + // ArrayOutputAdapterBase implementation. + virtual void* GetDataBuffer(uint32_t element_count, uint32_t element_size) { + if (element_count == 0) + return NULL; + PP_DCHECK(element_size == sizeof(T)); + if (element_size != sizeof(T)) + return NULL; + output_->resize(element_count); + return &(*output_)[0]; + } + + private: + std::vector<T>* output_; +}; + +// This adapter provides functionality for implementing a PP_ArrayOutput +// structure as writing resources to a given vector object. +// +// When returning an array of resources, the browser will write PP_Resources +// via a PP_ArrayOutput. This code will automatically convert the PP_Resources +// to the given wrapper type, (as long as that wrapper type supports the +// correct constructor). The ownership of the resources that the browser passed +// to us will be transferred to the C++ wrapper object. +// +// Conversion of the PP_Resources to the C++ wrapper object occurs in the +// destructor. This object is intended to be used on the stack in a C++ wrapper +// object for a call. +// +// Example: +// void GetFiles(std::vector<pp::FileRef>* results) { +// ResourceArrayOutputAdapter<pp::FileRef> adapter(results); +// ppb_foo->DoFoo(adapter.pp_array_output()); +// } +template<typename T> +class ResourceArrayOutputAdapter : public ArrayOutputAdapterBase { + public: + explicit ResourceArrayOutputAdapter(std::vector<T>* output) + : output_(output) { + output_->resize(0); + } + virtual ~ResourceArrayOutputAdapter() { + ConvertPPResourceArrayToObjects(PASS_REF, intermediate_output_, output_); + } + + protected: + // Two-step init for the "with storage" version below. + ResourceArrayOutputAdapter() : output_(NULL) {} + void set_output(T* output) { output_ = output; } + + // ArrayOutputAdapterBase implementation. + virtual void* GetDataBuffer(uint32_t element_count, + uint32_t element_size) { + if (element_count == 0) + return NULL; + PP_DCHECK(element_size == sizeof(PP_Resource)); + if (element_size != sizeof(PP_Resource)) + return NULL; + intermediate_output_.resize(element_count); + return &intermediate_output_[0]; + } + + private: + std::vector<PP_Resource> intermediate_output_; + std::vector<T>* output_; +}; + +// This adapter is like the ArrayOutputAdapter except that it also contains +// the underlying std::vector that will be populated (rather than writing it to +// an object passed into the constructor). +// +// This is used by the CompletionCallbackFactory system to collect the output +// parameters from an async function call. The collected data is then passed to +// the plugins callback function. +// +// You can also use it directly if you want to have an array output and aren't +// using the CompletionCallbackFactory. For example, if you're calling a +// PPAPI function DoFoo that takes a PP_OutputArray that is supposed to be +// writing integers, do this: +// +// ArrayOutputAdapterWithStorage<int> adapter; +// ppb_foo->DoFoo(adapter.pp_output_array()); +// const std::vector<int>& result = adapter.output(); +template<typename T> +class ArrayOutputAdapterWithStorage : public ArrayOutputAdapter<T> { + public: + ArrayOutputAdapterWithStorage() { + this->set_output(&output_storage_); + } + + std::vector<T>& output() { return output_storage_; } + + private: + std::vector<T> output_storage_; +}; + +// This adapter is like the ArrayOutputAdapterWithStorage except this +// additionally converts PP_Var structs to pp::Var objects. +// +// You can also use it directly if you want to have an array output and aren't +// using the CompletionCallbackFactory. For example, if you're calling a +// PPAPI function GetVars that takes a PP_OutputArray that is supposed to be +// writing PP_Vars, do this: +// +// VarArrayOutputAdapterWithStorage adapter; +// ppb_foo->GetVars(adapter.pp_output_array()); +// const std::vector<pp::Var>& result = adapter.output(). +// +// This one is non-inline since it's not templatized. +class VarArrayOutputAdapterWithStorage : public ArrayOutputAdapter<PP_Var> { + public: + VarArrayOutputAdapterWithStorage(); + virtual ~VarArrayOutputAdapterWithStorage(); + + // Returns the final array of resource objects, converting the PP_Vars + // written by the browser to pp::Var objects. + // + // This function should only be called once or we would end up converting + // the array more than once, which would mess up the refcounting. + std::vector<Var>& output(); + + private: + // The browser will write the PP_Vars into this array. + std::vector<PP_Var> temp_storage_; + + // When asked for the output, the resources above will be converted to the + // C++ resource objects in this array for passing to the calling code. + std::vector<Var> output_storage_; +}; + +// This adapter is like the ArrayOutputAdapterWithStorage except this +// additionally converts PP_Resources to C++ wrapper objects of the given type. +// +// You can also use it directly if you want to have an array output and aren't +// using the CompletionCallbackFactory. For example, if you're calling a +// PPAPI function GetFiles that takes a PP_OutputArray that is supposed to be +// writing PP_Resources cooresponding to FileRefs, do this: +// +// ResourceArrayOutputAdapterWithStorage<FileRef> adapter; +// ppb_foo->GetFiles(adapter.pp_output_array()); +// std::vector<FileRef> result = adapter.output(). +template<typename T> +class ResourceArrayOutputAdapterWithStorage + : public ArrayOutputAdapter<PP_Resource> { + public: + ResourceArrayOutputAdapterWithStorage() { + set_output(&temp_storage_); + } + + virtual ~ResourceArrayOutputAdapterWithStorage() { + if (!temp_storage_.empty()) { + // An easy way to release the resource references held by this object. + output(); + } + } + + // Returns the final array of resource objects, converting the PP_Resources + // written by the browser to resource objects. + // + // This function should only be called once or we would end up converting + // the array more than once, which would mess up the refcounting. + std::vector<T>& output() { + PP_DCHECK(output_storage_.empty()); + + ConvertPPResourceArrayToObjects(PASS_REF, temp_storage_, &output_storage_); + temp_storage_.clear(); + return output_storage_; + } + + private: + // The browser will write the PP_Resources into this array. + std::vector<PP_Resource> temp_storage_; + + // When asked for the output, the resources above will be converted to the + // C++ resource objects in this array for passing to the calling code. + std::vector<T> output_storage_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_ARRAY_OUTPUT_H_ diff --git a/chromium/ppapi/cpp/audio.cc b/chromium/ppapi/cpp/audio.cc new file mode 100644 index 00000000000..89702be0072 --- /dev/null +++ b/chromium/ppapi/cpp/audio.cc @@ -0,0 +1,41 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/audio.h" + +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Audio_1_0>() { + return PPB_AUDIO_INTERFACE_1_0; +} + +} // namespace + +Audio::Audio(const InstanceHandle& instance, + const AudioConfig& config, + PPB_Audio_Callback callback, + void* user_data) + : config_(config) { + if (has_interface<PPB_Audio_1_0>()) { + PassRefFromConstructor(get_interface<PPB_Audio_1_0>()->Create( + instance.pp_instance(), config.pp_resource(), callback, user_data)); + } +} + +bool Audio::StartPlayback() { + return has_interface<PPB_Audio_1_0>() && + get_interface<PPB_Audio_1_0>()->StartPlayback(pp_resource()); +} + +bool Audio::StopPlayback() { + return has_interface<PPB_Audio_1_0>() && + get_interface<PPB_Audio_1_0>()->StopPlayback(pp_resource()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/audio.h b/chromium/ppapi/cpp/audio.h new file mode 100644 index 00000000000..a07fcf58067 --- /dev/null +++ b/chromium/ppapi/cpp/audio.h @@ -0,0 +1,87 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_AUDIO_H_ +#define PPAPI_CPP_AUDIO_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/ppb_audio.h" +#include "ppapi/cpp/audio_config.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the API to create realtime stereo audio streaming +/// capabilities. + +namespace pp { + +class InstanceHandle; + +/// An audio resource. Refer to the +/// <a href="/native-client/devguide/coding/audio">Audio</a> +/// chapter in the Developer's Guide for information on using this interface. +class Audio : public Resource { + public: + + /// An empty constructor for an Audio resource. + Audio() {} + + /// A constructor that creates an Audio resource. No sound will be heard + /// until StartPlayback() is called. The callback is called with the buffer + /// address and given user data whenever the buffer needs to be filled. + /// From within the callback, you should not call <code>PPB_Audio</code> + /// functions. The callback will be called on a different thread than the one + /// which created the interface. For performance-critical applications (such + /// as low-latency audio), the callback should avoid blocking or calling + /// functions that can obtain locks, such as malloc. The layout and the size + /// of the buffer passed to the audio callback will be determined by + /// the device configuration and is specified in the <code>AudioConfig</code> + /// documentation. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + // + /// @param[in] config An <code>AudioConfig</code> containing the audio config + /// resource. + // + /// @param[in] callback A <code>PPB_Audio_Callback</code> callback function + /// that the browser calls when it needs more samples to play. + // + /// @param[in] user_data A pointer to user data used in the callback function. + Audio(const InstanceHandle& instance, + const AudioConfig& config, + PPB_Audio_Callback callback, + void* user_data); + + /// Getter function for returning the internal <code>PPB_AudioConfig</code> + /// struct. + /// + /// @return A mutable reference to the PPB_AudioConfig struct. + AudioConfig& config() { return config_; } + + /// Getter function for returning the internal <code>PPB_AudioConfig</code> + /// struct. + /// + /// @return A const reference to the internal <code>PPB_AudioConfig</code> + /// struct. + const AudioConfig& config() const { return config_; } + + /// StartPlayback() starts playback of audio. + /// + /// @return true if successful, otherwise false. + bool StartPlayback(); + + /// StopPlayback stops playback of audio. + /// + /// @return true if successful, otherwise false. + bool StopPlayback(); + + private: + AudioConfig config_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_AUDIO_H_ + diff --git a/chromium/ppapi/cpp/audio_config.cc b/chromium/ppapi/cpp/audio_config.cc new file mode 100644 index 00000000000..eaf019c2278 --- /dev/null +++ b/chromium/ppapi/cpp/audio_config.cc @@ -0,0 +1,75 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/audio_config.h" + +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_AudioConfig_1_1>() { + return PPB_AUDIO_CONFIG_INTERFACE_1_1; +} + +template <> const char* interface_name<PPB_AudioConfig_1_0>() { + return PPB_AUDIO_CONFIG_INTERFACE_1_0; +} + +} // namespace + +AudioConfig::AudioConfig() + : sample_rate_(PP_AUDIOSAMPLERATE_NONE), + sample_frame_count_(0) { +} + +AudioConfig::AudioConfig(const InstanceHandle& instance, + PP_AudioSampleRate sample_rate, + uint32_t sample_frame_count) + : sample_rate_(sample_rate), + sample_frame_count_(sample_frame_count) { + if (has_interface<PPB_AudioConfig_1_1>()) { + PassRefFromConstructor( + get_interface<PPB_AudioConfig_1_1>()->CreateStereo16Bit( + instance.pp_instance(), sample_rate, sample_frame_count)); + } else if (has_interface<PPB_AudioConfig_1_0>()) { + PassRefFromConstructor( + get_interface<PPB_AudioConfig_1_0>()->CreateStereo16Bit( + instance.pp_instance(), sample_rate, sample_frame_count)); + } +} + +// static +PP_AudioSampleRate AudioConfig::RecommendSampleRate( + const InstanceHandle& instance) { + if (has_interface<PPB_AudioConfig_1_1>()) { + return get_interface<PPB_AudioConfig_1_1>()-> + RecommendSampleRate(instance.pp_instance()); + } + return PP_AUDIOSAMPLERATE_NONE; +} + +// static +uint32_t AudioConfig::RecommendSampleFrameCount( + const InstanceHandle& instance, + PP_AudioSampleRate sample_rate, + uint32_t requested_sample_frame_count) { + if (has_interface<PPB_AudioConfig_1_1>()) { + return get_interface<PPB_AudioConfig_1_1>()-> + RecommendSampleFrameCount(instance.pp_instance(), + sample_rate, + requested_sample_frame_count); + } + if (has_interface<PPB_AudioConfig_1_0>()) { + return get_interface<PPB_AudioConfig_1_0>()-> + RecommendSampleFrameCount(sample_rate, + requested_sample_frame_count); + } + return 0; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/audio_config.h b/chromium/ppapi/cpp/audio_config.h new file mode 100644 index 00000000000..e7ade547906 --- /dev/null +++ b/chromium/ppapi/cpp/audio_config.h @@ -0,0 +1,132 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_AUDIO_CONFIG_H_ +#define PPAPI_CPP_AUDIO_CONFIG_H_ + +#include "ppapi/c/ppb_audio_config.h" +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the interface for establishing an +/// audio configuration resource within the browser. + +namespace pp { + +class InstanceHandle; + +/// A 16 bit stereo AudioConfig resource. Refer to the +/// <a href="/native-client/{{pepperversion}}/devguide/coding/audio">Audio +/// </a>chapter in the Developer's Guide for information on using this +/// interface. +/// +/// A single sample frame on a stereo device means one value for the left +/// channel and one value for the right channel. +/// +/// Buffer layout for a stereo int16 configuration: +/// +/// <code>int16_t *buffer16;</code> +/// <code>buffer16[0]</code> is the first left channel sample. +/// <code>buffer16[1]</code> is the first right channel sample. +/// <code>buffer16[2]</code> is the second left channel sample. +/// <code>buffer16[3]</code> is the second right channel sample. +/// <code>...</code> +/// <code>buffer16[2 * (sample_frame_count - 1)]</code> is the last left +/// channel sample. +/// <code>buffer16[2 * (sample_frame_count - 1) + 1]</code> is the last right +/// channel sample. +/// Data will always be in the native endian format of the platform. +/// +/// <strong>Example:</strong> +/// @code +/// +/// // Create an audio config with a supported frame count. +/// uint32_t sample_frame_count = AudioConfig::RecommendSampleFrameCount( +/// PP_AUDIOSAMPLERATE_44100, 4096); +/// AudioConfig config(PP_AUDIOSAMPLERATE_44100, sample_frame_count); +/// if (config.is_null()) +/// return false; // Couldn't configure audio. +/// +/// // Then use the config to create your audio resource. +/// Audio audio(instance, config, callback, user_data); +/// if (audio.is_null()) +/// return false; // Couldn't create audio. +/// @endcode +class AudioConfig : public Resource { + public: + /// An empty constructor for an <code>AudioConfig</code> resource. + AudioConfig(); + + /// A constructor that creates an audio config based on the given sample rate + /// and frame count. If the rate and frame count aren't supported, the + /// resulting resource will be is_null(). You can pass the result of + /// RecommendSampleFrameCount() as the sample frame count. + /// + /// @param[in] instance The instance associated with this resource. + /// + /// @param[in] sample_rate A <code>PP_AudioSampleRate</code> which is either + /// <code>PP_AUDIOSAMPLERATE_44100</code> or + /// <code>PP_AUDIOSAMPLERATE_48000</code>. + /// + /// @param[in] sample_frame_count A uint32_t frame count returned from the + /// <code>RecommendSampleFrameCount</code> function. + AudioConfig(const InstanceHandle& instance, + PP_AudioSampleRate sample_rate, + uint32_t sample_frame_count); + + /// RecommendSampleRate() returns the native sample rate used by the + /// audio system. Applications that use the recommended sample rate might + /// obtain lower latency and higher fidelity output. + /// + /// @param[in] instance The instance associated with this resource. + static PP_AudioSampleRate RecommendSampleRate( + const InstanceHandle& instance); + + /// RecommendSampleFrameCount() returns a supported frame count closest to + /// the requested count. The sample frame count determines the overall + /// latency of audio. Smaller frame counts will yield lower latency, but + /// higher CPU utilization. Supported sample frame counts will vary by + /// hardware and system (consider that the local system might be anywhere + /// from a cell phone or a high-end audio workstation). Sample counts less + /// than <code>PP_AUDIOMINSAMPLEFRAMECOUNT</code> and greater than + /// <code>PP_AUDIOMAXSAMPLEFRAMECOUNT</code> are never supported on any + /// system, but values in between aren't necessarily valid. This function + /// will return a supported count closest to the requested value for use in + /// the constructor. + /// + /// @param[in] instance The instance associated with this resource. + /// @param[in] sample_rate A <code>PP_AudioSampleRate</code> which is either + /// <code>PP_AUDIOSAMPLERATE_44100</code> or + /// <code>PP_AUDIOSAMPLERATE_48000</code>. + /// @param[in] requested_sample_frame_count A uint32_t requested frame count. + /// + /// @return A uint32_t containing the recommended sample frame count if + /// successful. If the sample frame count or bit rate is not supported, + /// this function will fail and return 0. + static uint32_t RecommendSampleFrameCount( + const InstanceHandle& instance, + PP_AudioSampleRate sample_rate, + uint32_t requested_sample_frame_count); + + /// Getter function for returning the internal + /// <code>PP_AudioSampleRate</code> enum. + /// + /// @return The <code>PP_AudioSampleRate</code> enum. + PP_AudioSampleRate sample_rate() const { return sample_rate_; } + + /// Getter function for returning the internal sample frame count. + /// + /// @return A uint32_t containing the sample frame count. + uint32_t sample_frame_count() const { return sample_frame_count_; } + + private: + PP_AudioSampleRate sample_rate_; + uint32_t sample_frame_count_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_AUDIO_CONFIG_H_ + diff --git a/chromium/ppapi/cpp/completion_callback.h b/chromium/ppapi/cpp/completion_callback.h new file mode 100644 index 00000000000..14d67846aa1 --- /dev/null +++ b/chromium/ppapi/cpp/completion_callback.h @@ -0,0 +1,383 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_COMPLETION_CALLBACK_H_ +#define PPAPI_CPP_COMPLETION_CALLBACK_H_ + +#include "ppapi/c/pp_completion_callback.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/extensions/ext_output_traits.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/output_traits.h" + +/// @file +/// This file defines the API to create and run a callback. +namespace pp { + +/// This API enables you to implement and receive callbacks when +/// Pepper operations complete asynchronously. +/// +/// You can create these objects yourself, but it is most common to use the +/// CompletionCallbackFactory to allow the callbacks to call class member +/// functions. +class CompletionCallback { + public: + /// The default constructor will create a blocking + /// <code>CompletionCallback</code> that can be passed to a method to + /// indicate that the calling thread should be blocked until the asynchronous + /// operation corresponding to the method completes. + /// + /// <strong>Note:</strong> Blocking completion callbacks are only allowed from + /// from background threads. + CompletionCallback() { + cc_ = PP_BlockUntilComplete(); + } + + /// A constructor for creating a <code>CompletionCallback</code>. + /// + /// @param[in] func The function to be called on completion. + /// @param[in] user_data The user data to be passed to the callback function. + /// This is optional and is typically used to help track state in case of + /// multiple pending callbacks. + CompletionCallback(PP_CompletionCallback_Func func, void* user_data) { + cc_ = PP_MakeCompletionCallback(func, user_data); + } + + /// A constructor for creating a <code>CompletionCallback</code> with + /// specified flags. + /// + /// @param[in] func The function to be called on completion. + /// @param[in] user_data The user data to be passed to the callback function. + /// This is optional and is typically used to help track state in case of + /// multiple pending callbacks. + /// @param[in] flags Bit field combination of + /// <code>PP_CompletionCallback_Flag</code> flags used to control how + /// non-NULL callbacks are scheduled by asynchronous methods. + CompletionCallback(PP_CompletionCallback_Func func, void* user_data, + int32_t flags) { + cc_ = PP_MakeCompletionCallback(func, user_data); + cc_.flags = flags; + } + + /// The set_flags() function is used to set the flags used to control + /// how non-NULL callbacks are scheduled by asynchronous methods. + /// + /// @param[in] flags Bit field combination of + /// <code>PP_CompletionCallback_Flag</code> flags used to control how + /// non-NULL callbacks are scheduled by asynchronous methods. + void set_flags(int32_t flags) { cc_.flags = flags; } + + /// Run() is used to run the <code>CompletionCallback</code>. + /// Normally, the system runs a <code>CompletionCallback</code> after an + /// asynchronous operation completes, but programs may wish to run the + /// <code>CompletionCallback</code> manually in order to reuse the same code + /// paths. + /// + /// @param[in] result The result of the operation to be passed to the + /// callback function. Non-positive values correspond to the error codes + /// from <code>pp_errors.h</code> (excluding + /// <code>PP_OK_COMPLETIONPENDING</code>). Positive values indicate + /// additional information such as bytes read. + void Run(int32_t result) { + PP_DCHECK(cc_.func); + PP_RunCompletionCallback(&cc_, result); + } + + /// RunAndClear() is used to run the <code>CompletionCallback</code> and + /// clear out the callback so that it cannot be run a second time. + /// + /// @param[in] result The result of the operation to be passed to the + /// callback function. Non-positive values correspond to the error codes + /// from <code>pp_errors.h</code> (excluding + /// <code>PP_OK_COMPLETIONPENDING</code>). Positive values indicate + /// additional information such as bytes read. + void RunAndClear(int32_t result) { + PP_DCHECK(cc_.func); + PP_RunAndClearCompletionCallback(&cc_, result); + } + + /// IsOptional() is used to determine the setting of the + /// <code>PP_COMPLETIONCALLBACK_FLAG_OPTIONAL</code> flag. This flag allows + /// any method taking such callback to complete synchronously + /// and not call the callback if the operation would not block. This is useful + /// when performance is an issue, and the operation bandwidth should not be + /// limited to the processing speed of the message loop. + /// + /// On synchronous method completion, the completion result will be returned + /// by the method itself. Otherwise, the method will return + /// PP_OK_COMPLETIONPENDING, and the callback will be invoked asynchronously + /// on the same thread where the PPB method was invoked. + /// + /// @return true if this callback is optional, otherwise false. + bool IsOptional() const { + return (cc_.func == NULL || + (cc_.flags & PP_COMPLETIONCALLBACK_FLAG_OPTIONAL) != 0); + } + + /// The pp_completion_callback() function returns the underlying + /// <code>PP_CompletionCallback</code> + /// + /// @return A <code>PP_CompletionCallback</code>. + const PP_CompletionCallback& pp_completion_callback() const { return cc_; } + + /// The flags() function returns flags used to control how non-NULL callbacks + /// are scheduled by asynchronous methods. + /// + /// @return An int32_t containing a bit field combination of + /// <code>PP_CompletionCallback_Flag</code> flags. + int32_t flags() const { return cc_.flags; } + + /// MayForce() is used when implementing functions taking callbacks. + /// If the callback is required and <code>result</code> indicates that it has + /// not been scheduled, it will be forced on the main thread. + /// + /// <strong>Example:</strong> + /// + /// @code + /// + /// int32_t OpenURL(pp::URLLoader* loader, + /// pp::URLRequestInfo* url_request_info, + /// const CompletionCallback& cc) { + /// if (loader == NULL || url_request_info == NULL) + /// return cc.MayForce(PP_ERROR_BADRESOURCE); + /// return loader->Open(*loader, *url_request_info, cc); + /// } + /// + /// @endcode + /// + /// @param[in] result PP_OK_COMPLETIONPENDING or the result of the completed + /// operation to be passed to the callback function. PP_OK_COMPLETIONPENDING + /// indicates that the callback has already been scheduled. Other + /// non-positive values correspond to error codes from + /// <code>pp_errors.h</code>. Positive values indicate additional information + /// such as bytes read. + /// + /// @return <code>PP_OK_COMPLETIONPENDING</code> if the callback has been + /// forced, result parameter otherwise. + int32_t MayForce(int32_t result) const { + if (result == PP_OK_COMPLETIONPENDING || IsOptional()) + return result; + // FIXME(dmichael): Use pp::MessageLoop here once it's out of Dev. + Module::Get()->core()->CallOnMainThread(0, *this, result); + return PP_OK_COMPLETIONPENDING; + } + + protected: + PP_CompletionCallback cc_; +}; + +namespace internal { + +/// The base class of [Ext]CompletionCallbackWithOutput. +/// +/// The template parameter Traits determines the storage type +/// (OutputStorageType), the output parameter type used by the browser +/// (APIArgType), and how to map OutputStorageType to APIArgType. +template <typename T, typename Traits> +class CompletionCallbackWithOutputBase : public CompletionCallback { + public: + typedef typename Traits::StorageType OutputStorageType; + typedef typename Traits::APIArgType APIArgType; + typedef Traits TraitsType; + + explicit CompletionCallbackWithOutputBase(OutputStorageType* output) + : CompletionCallback(), + output_(output) { + } + + CompletionCallbackWithOutputBase(PP_CompletionCallback_Func func, + void* user_data, + OutputStorageType* output) + : CompletionCallback(func, user_data), + output_(output) { + } + + CompletionCallbackWithOutputBase(PP_CompletionCallback_Func func, + void* user_data, + int32_t flags, + OutputStorageType* output) + : CompletionCallback(func, user_data, flags), + output_(output) { + } + + APIArgType output() const { + return Traits::StorageToAPIArg(*output_); + } + + private: + OutputStorageType* output_; +}; + +} // namespace internal + +/// A CompletionCallbackWithOutput defines a completion callback that +/// additionally stores a pointer to some output data. Some C++ wrappers +/// take a CompletionCallbackWithOutput when the browser is returning a +/// bit of data as part of the function call. The "output" parameter +/// stored in the CompletionCallbackWithOutput will receive the data from +/// the browser. +/// +/// You can create this yourself, but it is most common to use with the +/// CompletionCallbackFactory's NewCallbackWithOutput, which manages the +/// storage for the output parameter for you and passes it as an argument +/// to your callback function. +/// +/// Note that this class doesn't actually do anything with the output data, +/// it just stores a pointer to it. C++ wrapper objects that accept a +/// CompletionCallbackWithOutput will retrieve this pointer and pass it to +/// the browser as the output parameter. +template <typename T> +class CompletionCallbackWithOutput + : public internal::CompletionCallbackWithOutputBase< + T, internal::CallbackOutputTraits<T> > { + public: + typedef internal::CompletionCallbackWithOutputBase< + T, internal::CallbackOutputTraits<T> > BaseType; + + /// The default constructor will create a blocking + /// <code>CompletionCallbackWithOutput</code> that references the given output + /// data. + /// + /// @param[in] output A pointer to the data associated with the callback. The + /// caller must ensure that this pointer outlives the completion callback. + /// In the common case, <code>OutputStorageType</code> will be equal to the + /// template parameter T (for example, + /// <code>CompletionCallbackWithOutput<int></code> would obviously take an + /// int*. However, resources are passed as PP_Resource, vars as PP_Var, and + /// arrays as our special ArrayOutputAdapter object. + /// <code>internal::CallbackOutputTraits</code> defines specializations for + /// all of these cases. + /// + /// <strong>Note:</strong> Blocking completion callbacks are only allowed from + /// background threads. + explicit CompletionCallbackWithOutput( + typename BaseType::OutputStorageType* output) + : BaseType(output) { + } + + /// A constructor for creating a <code>CompletionCallbackWithOutput</code> + /// that references the given output data. + /// + /// @param[in] func The function to be called on completion. + /// @param[in] user_data The user data to be passed to the callback function. + /// This is optional and is typically used to help track state in case of + /// multiple pending callbacks. + /// @param[in] output A pointer to the data associated with the callback. The + /// caller must ensure that this pointer outlives the completion callback. + CompletionCallbackWithOutput(PP_CompletionCallback_Func func, + void* user_data, + typename BaseType::OutputStorageType* output) + : BaseType(func, user_data, output) { + } + + /// A constructor for creating a <code>CompletionCallbackWithOutput</code> + /// that references the given output data. + /// + /// @param[in] func The function to be called on completion. + /// + /// @param[in] user_data The user data to be passed to the callback function. + /// This is optional and is typically used to help track state in case of + /// multiple pending callbacks. + /// + /// @param[in] flags Bit field combination of + /// <code>PP_CompletionCallback_Flag</code> flags used to control how + /// non-NULL callbacks are scheduled by asynchronous methods. + /// + /// @param[in] output A pointer to the data associated with the callback. The + /// caller must ensure that this pointer outlives the completion callback. + CompletionCallbackWithOutput(PP_CompletionCallback_Func func, + void* user_data, + int32_t flags, + typename BaseType::OutputStorageType* output) + : BaseType(func, user_data, flags, output) { + } +}; + +namespace ext { + +/// ExtCompletionCallbackWithOutput is similar to CompletionCallbackWithOutput, +/// but used by APIs within the pp::ext namespace. Usually it is used with the +/// CompletionCallbackFactory's NewExtCallbackWithOutput. +template <typename T> +class ExtCompletionCallbackWithOutput + : public ::pp::internal::CompletionCallbackWithOutputBase< + T, internal::ExtCallbackOutputTraits<T> > { + public: + typedef ::pp::internal::CompletionCallbackWithOutputBase< + T, internal::ExtCallbackOutputTraits<T> > BaseType; + + /// The default constructor will create a blocking + /// <code>ExtCompletionCallbackWithOutput</code> that references the given + /// output data. + /// + /// @param[in] output A pointer to the data associated with the callback. The + /// caller must ensure that this pointer outlives the completion callback. + /// <code>OutputStorageType</code> is either + /// <code>ext::internal::ArrayVarOutputAdapterWithStorage<U></code> (if the + /// template parameter T is of the form std::vector<U>) or + /// <code>ext::internal::VarOutputAdapterWithStorage<T></code> (otherwise). + /// + /// <strong>Note:</strong> Blocking completion callbacks are only allowed from + /// background threads. + explicit ExtCompletionCallbackWithOutput( + typename BaseType::OutputStorageType* output) + : BaseType(output) { + } + + /// A constructor for creating an <code>ExtCompletionCallbackWithOutput</code> + /// that references the given output data. + /// + /// @param[in] func The function to be called on completion. + /// @param[in] user_data The user data to be passed to the callback function. + /// This is optional and is typically used to help track state in case of + /// multiple pending callbacks. + /// @param[in] output A pointer to the data associated with the callback. The + /// caller must ensure that this pointer outlives the completion callback. + ExtCompletionCallbackWithOutput(PP_CompletionCallback_Func func, + void* user_data, + typename BaseType::OutputStorageType* output) + : BaseType(func, user_data, output) { + } + + /// A constructor for creating an <code>ExtCompletionCallbackWithOutput</code> + /// that references the given output data. + /// + /// @param[in] func The function to be called on completion. + /// + /// @param[in] user_data The user data to be passed to the callback function. + /// This is optional and is typically used to help track state in case of + /// multiple pending callbacks. + /// + /// @param[in] flags Bit field combination of + /// <code>PP_CompletionCallback_Flag</code> flags used to control how + /// non-NULL callbacks are scheduled by asynchronous methods. + /// + /// @param[in] output A pointer to the data associated with the callback. The + /// caller must ensure that this pointer outlives the completion callback. + ExtCompletionCallbackWithOutput(PP_CompletionCallback_Func func, + void* user_data, + int32_t flags, + typename BaseType::OutputStorageType* output) + : BaseType(func, user_data, flags, output) { + } +}; + +} // namespace ext + +/// BlockUntilComplete() is used in place of an actual completion callback +/// to request blocking behavior. If specified, the calling thread will block +/// until the function completes. Blocking completion callbacks are only +/// allowed from background threads. +/// +/// @return A <code>CompletionCallback</code> corresponding to a NULL callback. +inline CompletionCallback BlockUntilComplete() { + // Note: Explicitly inlined to avoid link errors when included into + // ppapi_proxy and ppapi_cpp_objects. + return CompletionCallback(); +} + +} // namespace pp + +#endif // PPAPI_CPP_COMPLETION_CALLBACK_H_ diff --git a/chromium/ppapi/cpp/core.cc b/chromium/ppapi/cpp/core.cc new file mode 100644 index 00000000000..36c4e8a2a20 --- /dev/null +++ b/chromium/ppapi/cpp/core.cc @@ -0,0 +1,25 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/core.h" + +#include "ppapi/cpp/completion_callback.h" + +namespace pp { + +// This function is implemented in the .cc file to avoid including completion +// callback all over the project. +void Core::CallOnMainThread(int32_t delay_in_milliseconds, + const CompletionCallback& callback, + int32_t result) { + return interface_->CallOnMainThread(delay_in_milliseconds, + callback.pp_completion_callback(), + result); +} + +bool Core::IsMainThread() { + return PP_ToBool(interface_->IsMainThread()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/core.h b/chromium/ppapi/cpp/core.h new file mode 100644 index 00000000000..35b8655f604 --- /dev/null +++ b/chromium/ppapi/cpp/core.h @@ -0,0 +1,119 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_CORE_H_ +#define PPAPI_CPP_CORE_H_ + +#include "ppapi/c/ppb_core.h" + +/// @file +/// This file defines APIs related to memory management, time, and threads. + +namespace pp { + +class CompletionCallback; +class Module; + +/// APIs related to memory management, time, and threads. +class Core { + public: + // Note that we explicitly don't expose Resource& versions of this function + // since Resource will normally manage the refcount properly. These should + // be called only when doing manual management on raw PP_Resource handles, + // which should be fairly rare. + + /// AddRefResource() increments the reference count for the provided + /// <code>resource</code>. + /// + /// @param[in] resource A <code>PP_Resource</code> corresponding to a + /// resource. + void AddRefResource(PP_Resource resource) { + interface_->AddRefResource(resource); + } + + /// ReleaseResource() decrements the reference count for the provided + /// <code>resource</code>. The resource will be deallocated if the + /// reference count reaches zero. + /// + /// @param[in] resource A <code>PP_Resource</code> corresponding to a + /// resource. + void ReleaseResource(PP_Resource resource) { + interface_->ReleaseResource(resource); + } + + /// GetTime() returns the "wall clock time" according to the + /// browser. + /// + /// @return A <code>PP_Time</code> containing the "wall clock time" according + /// to the browser. + PP_Time GetTime() { + return interface_->GetTime(); + } + + /// GetTimeTicks() returns the "tick time" according to the browser. + /// This clock is used by the browser when passing some event times to the + /// module (for example, using the + /// <code>PP_InputEvent::time_stamp_seconds</code> field). It is not + /// correlated to any actual wall clock time (like GetTime()). Because + /// of this, it will not change if the user changes their computer clock. + /// + /// @return A <code>PP_TimeTicks</code> containing the "tick time" according + /// to the browser. + PP_TimeTicks GetTimeTicks() { + return interface_->GetTimeTicks(); + } + + /// CallOnMainThread() schedules work to be executed on the main pepper + /// thread after the specified delay. The delay may be 0 to specify a call + /// back as soon as possible. + /// + /// The |result| parameter will just be passed as the second argument to the + /// callback. Many applications won't need this, but it allows a module to + /// emulate calls of some callbacks which do use this value. + /// + /// <strong>Note:</strong> CallOnMainThread(), even when used from the main + /// thread with a delay of 0 milliseconds, will never directly invoke the + /// callback. Even in this case, the callback will be scheduled + /// asynchronously. + /// + /// <strong>Note:</strong> If the browser is shutting down or if the module + /// has no instances, then the callback function may not be called. + /// + /// @param[in] delay_in_milliseconds An int32_t delay in milliseconds. + /// @param[in] callback A <code>CompletionCallback</code> callback function + /// that the browser will call after the specified delay. + /// @param[in] result An int32_t that the browser will pass to the given + /// <code>CompletionCallback</code>. + void CallOnMainThread(int32_t delay_in_milliseconds, + const CompletionCallback& callback, + int32_t result = 0); + + + /// IsMainThread() returns true if the current thread is the main pepper + /// thread. + /// + /// This function is useful for implementing sanity checks, and deciding if + /// dispatching using CallOnMainThread() is required. + /// + /// @return true if the current thread is the main pepper thread, otherwise + /// false. + bool IsMainThread(); + + private: + // Allow Module to construct. + friend class Module; + + // Only module should make this class so this constructor is private. + Core(const PPB_Core* inter) : interface_(inter) {} + + // Copy and assignment are disallowed. + Core(const Core& other); + Core& operator=(const Core& other); + + const PPB_Core* interface_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_CORE_H_ diff --git a/chromium/ppapi/cpp/dev/audio_input_dev.cc b/chromium/ppapi/cpp/dev/audio_input_dev.cc new file mode 100644 index 00000000000..0c2f37786fe --- /dev/null +++ b/chromium/ppapi/cpp/dev/audio_input_dev.cc @@ -0,0 +1,177 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/audio_input_dev.h" + +#include "ppapi/c/pp_bool.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/dev/resource_array_dev.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_AudioInput_Dev_0_2>() { + return PPB_AUDIO_INPUT_DEV_INTERFACE_0_2; +} + +template <> const char* interface_name<PPB_AudioInput_Dev_0_3>() { + return PPB_AUDIO_INPUT_DEV_INTERFACE_0_3; +} + +template <> const char* interface_name<PPB_AudioInput_Dev_0_4>() { + return PPB_AUDIO_INPUT_DEV_INTERFACE_0_4; +} + +} // namespace + +AudioInput_Dev::AudioInput_Dev() { +} + +AudioInput_Dev::AudioInput_Dev(const InstanceHandle& instance) { + if (has_interface<PPB_AudioInput_Dev_0_4>()) { + PassRefFromConstructor(get_interface<PPB_AudioInput_Dev_0_4>()->Create( + instance.pp_instance())); + } else if (has_interface<PPB_AudioInput_Dev_0_3>()) { + PassRefFromConstructor(get_interface<PPB_AudioInput_Dev_0_3>()->Create( + instance.pp_instance())); + } else if (has_interface<PPB_AudioInput_Dev_0_2>()) { + PassRefFromConstructor(get_interface<PPB_AudioInput_Dev_0_2>()->Create( + instance.pp_instance())); + } +} + +AudioInput_Dev::~AudioInput_Dev() { +} + +// static +bool AudioInput_Dev::IsAvailable() { + return has_interface<PPB_AudioInput_Dev_0_4>() || + has_interface<PPB_AudioInput_Dev_0_3>() || + has_interface<PPB_AudioInput_Dev_0_2>(); +} + +int32_t AudioInput_Dev::EnumerateDevices( + const CompletionCallbackWithOutput<std::vector<DeviceRef_Dev> >& callback) { + if (has_interface<PPB_AudioInput_Dev_0_4>()) { + return get_interface<PPB_AudioInput_Dev_0_4>()->EnumerateDevices( + pp_resource(), callback.output(), callback.pp_completion_callback()); + } + if (has_interface<PPB_AudioInput_Dev_0_3>()) { + return get_interface<PPB_AudioInput_Dev_0_3>()->EnumerateDevices( + pp_resource(), callback.output(), callback.pp_completion_callback()); + } + if (has_interface<PPB_AudioInput_Dev_0_2>()) { + if (!callback.pp_completion_callback().func) + return callback.MayForce(PP_ERROR_BLOCKS_MAIN_THREAD); + + // ArrayOutputCallbackConverter is responsible to delete it. + ResourceArray_Dev::ArrayOutputCallbackData* data = + new ResourceArray_Dev::ArrayOutputCallbackData( + callback.output(), callback.pp_completion_callback()); + return get_interface<PPB_AudioInput_Dev_0_2>()->EnumerateDevices( + pp_resource(), &data->resource_array_output, + PP_MakeCompletionCallback( + &ResourceArray_Dev::ArrayOutputCallbackConverter, data)); + } + + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t AudioInput_Dev::MonitorDeviceChange( + PP_MonitorDeviceChangeCallback callback, + void* user_data) { + if (has_interface<PPB_AudioInput_Dev_0_4>()) { + return get_interface<PPB_AudioInput_Dev_0_4>()->MonitorDeviceChange( + pp_resource(), callback, user_data); + } + if (has_interface<PPB_AudioInput_Dev_0_3>()) { + return get_interface<PPB_AudioInput_Dev_0_3>()->MonitorDeviceChange( + pp_resource(), callback, user_data); + } + + return PP_ERROR_NOINTERFACE; +} + +int32_t AudioInput_Dev::Open(const DeviceRef_Dev& device_ref, + const AudioConfig& config, + PPB_AudioInput_Callback audio_input_callback, + void* user_data, + const CompletionCallback& callback) { + if (has_interface<PPB_AudioInput_Dev_0_4>()) { + return get_interface<PPB_AudioInput_Dev_0_4>()->Open( + pp_resource(), device_ref.pp_resource(), config.pp_resource(), + audio_input_callback, user_data, callback.pp_completion_callback()); + } + + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t AudioInput_Dev::Open( + const DeviceRef_Dev& device_ref, + const AudioConfig& config, + PPB_AudioInput_Callback_0_2 audio_input_callback_0_2, + void* user_data, + const CompletionCallback& callback) { + if (has_interface<PPB_AudioInput_Dev_0_3>()) { + return get_interface<PPB_AudioInput_Dev_0_3>()->Open( + pp_resource(), device_ref.pp_resource(), config.pp_resource(), + audio_input_callback_0_2, user_data, callback.pp_completion_callback()); + } + if (has_interface<PPB_AudioInput_Dev_0_2>()) { + return get_interface<PPB_AudioInput_Dev_0_2>()->Open( + pp_resource(), device_ref.pp_resource(), config.pp_resource(), + audio_input_callback_0_2, user_data, callback.pp_completion_callback()); + } + + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +bool AudioInput_Dev::StartCapture() { + if (has_interface<PPB_AudioInput_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_AudioInput_Dev_0_4>()->StartCapture( + pp_resource())); + } + if (has_interface<PPB_AudioInput_Dev_0_3>()) { + return PP_ToBool(get_interface<PPB_AudioInput_Dev_0_3>()->StartCapture( + pp_resource())); + } + if (has_interface<PPB_AudioInput_Dev_0_2>()) { + return PP_ToBool(get_interface<PPB_AudioInput_Dev_0_2>()->StartCapture( + pp_resource())); + } + + return false; +} + +bool AudioInput_Dev::StopCapture() { + if (has_interface<PPB_AudioInput_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_AudioInput_Dev_0_4>()->StopCapture( + pp_resource())); + } + if (has_interface<PPB_AudioInput_Dev_0_3>()) { + return PP_ToBool(get_interface<PPB_AudioInput_Dev_0_3>()->StopCapture( + pp_resource())); + } + if (has_interface<PPB_AudioInput_Dev_0_2>()) { + return PP_ToBool(get_interface<PPB_AudioInput_Dev_0_2>()->StopCapture( + pp_resource())); + } + + return false; +} + +void AudioInput_Dev::Close() { + if (has_interface<PPB_AudioInput_Dev_0_4>()) { + get_interface<PPB_AudioInput_Dev_0_4>()->Close(pp_resource()); + } else if (has_interface<PPB_AudioInput_Dev_0_3>()) { + get_interface<PPB_AudioInput_Dev_0_3>()->Close(pp_resource()); + } else if (has_interface<PPB_AudioInput_Dev_0_2>()) { + get_interface<PPB_AudioInput_Dev_0_2>()->Close(pp_resource()); + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/audio_input_dev.h b/chromium/ppapi/cpp/dev/audio_input_dev.h new file mode 100644 index 00000000000..cb1f4ef6cd3 --- /dev/null +++ b/chromium/ppapi/cpp/dev/audio_input_dev.h @@ -0,0 +1,67 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_AUDIO_INPUT_DEV_H_ +#define PPAPI_CPP_DEV_AUDIO_INPUT_DEV_H_ + +#include <vector> + +#include "ppapi/c/dev/ppb_audio_input_dev.h" +#include "ppapi/cpp/audio_config.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/dev/device_ref_dev.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class InstanceHandle; + +class AudioInput_Dev : public Resource { + public: + /// An empty constructor for an AudioInput resource. + AudioInput_Dev(); + + /// Constructor to create an audio input resource. + explicit AudioInput_Dev(const InstanceHandle& instance); + + virtual ~AudioInput_Dev(); + + /// Static function for determining whether the browser supports the required + /// AudioInput interface. + /// + /// @return true if the interface is available, false otherwise. + static bool IsAvailable(); + + int32_t EnumerateDevices( + const CompletionCallbackWithOutput<std::vector<DeviceRef_Dev> >& + callback); + + int32_t MonitorDeviceChange(PP_MonitorDeviceChangeCallback callback, + void* user_data); + + /// If |device_ref| is null (i.e., is_null() returns true), the default device + /// will be used. + /// + /// Requires <code>PPB_AudioInput_Dev</code> version 0.4 or up. + int32_t Open(const DeviceRef_Dev& device_ref, + const AudioConfig& config, + PPB_AudioInput_Callback audio_input_callback, + void* user_data, + const CompletionCallback& callback); + + /// Requires <code>PPB_AudioInput_Dev</code> version 0.2 or 0.3. + int32_t Open(const DeviceRef_Dev& device_ref, + const AudioConfig& config, + PPB_AudioInput_Callback_0_2 audio_input_callback_0_2, + void* user_data, + const CompletionCallback& callback); + + bool StartCapture(); + bool StopCapture(); + void Close(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_AUDIO_INPUT_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/buffer_dev.cc b/chromium/ppapi/cpp/dev/buffer_dev.cc new file mode 100644 index 00000000000..aca7b1b795f --- /dev/null +++ b/chromium/ppapi/cpp/dev/buffer_dev.cc @@ -0,0 +1,69 @@ +// Copyright (c) 2011 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 "ppapi/cpp/dev/buffer_dev.h" + +#include "ppapi/c/dev/ppb_buffer_dev.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Buffer_Dev>() { + return PPB_BUFFER_DEV_INTERFACE; +} + +} // namespace + +Buffer_Dev::Buffer_Dev() : data_(NULL), size_(0) { +} + +Buffer_Dev::Buffer_Dev(const Buffer_Dev& other) + : Resource(other) { + Init(); +} + +Buffer_Dev::Buffer_Dev(PP_Resource resource) + : Resource(resource) { + Init(); +} + +Buffer_Dev::Buffer_Dev(const InstanceHandle& instance, uint32_t size) + : data_(NULL), + size_(0) { + if (!has_interface<PPB_Buffer_Dev>()) + return; + + PassRefFromConstructor(get_interface<PPB_Buffer_Dev>()->Create( + instance.pp_instance(), size)); + Init(); +} + +Buffer_Dev::Buffer_Dev(PassRef, PP_Resource resource) + : Resource(PassRef(), resource) { + Init(); +} + +Buffer_Dev::~Buffer_Dev() { + get_interface<PPB_Buffer_Dev>()->Unmap(pp_resource()); +} + +Buffer_Dev& Buffer_Dev::operator=(const Buffer_Dev& rhs) { + Resource::operator=(rhs); + Init(); + return *this; +} + +void Buffer_Dev::Init() { + if (!get_interface<PPB_Buffer_Dev>()->Describe(pp_resource(), &size_) || + !(data_ = get_interface<PPB_Buffer_Dev>()->Map(pp_resource()))) { + data_ = NULL; + size_ = 0; + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/buffer_dev.h b/chromium/ppapi/cpp/dev/buffer_dev.h new file mode 100644 index 00000000000..d82f92d5cc8 --- /dev/null +++ b/chromium/ppapi/cpp/dev/buffer_dev.h @@ -0,0 +1,46 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_DEV_BUFFER_DEV_H_ +#define PPAPI_CPP_DEV_BUFFER_DEV_H_ + +#include "ppapi/cpp/resource.h" + +namespace pp { + +class InstanceHandle; + +class Buffer_Dev : public Resource { + public: + // Creates an is_null() Buffer object. + Buffer_Dev(); + Buffer_Dev(const Buffer_Dev& other); + explicit Buffer_Dev(PP_Resource resource); + + // Creates & Maps a new Buffer in the browser with the given size. The + // resulting object will be is_null() if either Create() or Map() fails. + Buffer_Dev(const InstanceHandle& instance, uint32_t size); + + // Constructor used when the buffer resource already has a reference count + // assigned. No additional reference is taken. + Buffer_Dev(PassRef, PP_Resource resource); + + // Unmap the underlying shared memory. + virtual ~Buffer_Dev(); + + Buffer_Dev& operator=(const Buffer_Dev& rhs); + + uint32_t size() const { return size_; } + void* data() const { return data_; } + + private: + void Init(); + + void* data_; + uint32_t size_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_BUFFER_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/crypto_dev.cc b/chromium/ppapi/cpp/dev/crypto_dev.cc new file mode 100644 index 00000000000..fb9328d2e14 --- /dev/null +++ b/chromium/ppapi/cpp/dev/crypto_dev.cc @@ -0,0 +1,29 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/crypto_dev.h" + +#include "ppapi/c/dev/ppb_crypto_dev.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Crypto_Dev_0_1>() { + return PPB_CRYPTO_DEV_INTERFACE_0_1; +} + +} // namespace + +bool Crypto_Dev::GetRandomBytes(char* buffer, uint32_t num_bytes) { + if (has_interface<PPB_Crypto_Dev_0_1>()) { + get_interface<PPB_Crypto_Dev_0_1>()->GetRandomBytes(buffer, num_bytes); + return true; + } + return false; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/crypto_dev.h b/chromium/ppapi/cpp/dev/crypto_dev.h new file mode 100644 index 00000000000..2bbd43d8da9 --- /dev/null +++ b/chromium/ppapi/cpp/dev/crypto_dev.h @@ -0,0 +1,31 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_CRYPTO_DEV_H_ +#define PPAPI_CPP_DEV_CRYPTO_DEV_H_ + +#include "ppapi/c/pp_stdint.h" + +/// @file +/// This file defines APIs related to cryptography. + +namespace pp { + +/// APIs related to cryptography. +class Crypto_Dev { + public: + Crypto_Dev() {} + + /// A function that fills the buffer with random bytes. This may be slow, so + /// avoid getting more bytes than needed. + /// + /// @param[out] buffer The buffer to receive the random bytes. + /// @param[in] num_bytes A number of random bytes to produce. + /// @return True on success, false on failure. + bool GetRandomBytes(char* buffer, uint32_t num_bytes); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_CRYPTO_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/cursor_control_dev.cc b/chromium/ppapi/cpp/dev/cursor_control_dev.cc new file mode 100644 index 00000000000..6df0107098d --- /dev/null +++ b/chromium/ppapi/cpp/dev/cursor_control_dev.cc @@ -0,0 +1,67 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/cursor_control_dev.h" + +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/point.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_CursorControl_Dev_0_4>() { + return PPB_CURSOR_CONTROL_DEV_INTERFACE_0_4; +} + +} // namespace + +bool CursorControl_Dev::SetCursor(const InstanceHandle& instance, + PP_CursorType_Dev type, + const ImageData& custom_image, + const Point& hot_spot) { + if (has_interface<PPB_CursorControl_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_CursorControl_Dev_0_4>()->SetCursor( + instance.pp_instance(), type, custom_image.pp_resource(), + &hot_spot.pp_point())); + } + return false; +} + +bool LockCursor(const InstanceHandle& instance) { + if (has_interface<PPB_CursorControl_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_CursorControl_Dev_0_4>()->LockCursor( + instance.pp_instance())); + } + return false; +} + +bool UnlockCursor(const InstanceHandle& instance) { + if (has_interface<PPB_CursorControl_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_CursorControl_Dev_0_4>()->UnlockCursor( + instance.pp_instance())); + } + return false; +} + +bool HasCursorLock(const InstanceHandle& instance) { + if (has_interface<PPB_CursorControl_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_CursorControl_Dev_0_4>()->HasCursorLock( + instance.pp_instance())); + } + return false; +} + +bool CanLockCursor(const InstanceHandle& instance) { + if (has_interface<PPB_CursorControl_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_CursorControl_Dev_0_4>()->CanLockCursor( + instance.pp_instance())); + } + return false; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/cursor_control_dev.h b/chromium/ppapi/cpp/dev/cursor_control_dev.h new file mode 100644 index 00000000000..0ad974806e9 --- /dev/null +++ b/chromium/ppapi/cpp/dev/cursor_control_dev.h @@ -0,0 +1,36 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_CURSOR_CONTROL_DEV_H_ +#define PPAPI_CPP_DEV_CURSOR_CONTROL_DEV_H_ + +#include "ppapi/c/dev/ppb_cursor_control_dev.h" + +/// @file +/// This file defines APIs for controlling the cursor. + +namespace pp { + +class ImageData; +class InstanceHandle; +class Point; + +/// APIs for controlling the cursor. +class CursorControl_Dev { + public: + CursorControl_Dev() {} + + bool SetCursor(const InstanceHandle& instance, + PP_CursorType_Dev type, + const ImageData& custom_image, + const Point& hot_spot); + bool LockCursor(const InstanceHandle& instance); + bool UnlockCursor(const InstanceHandle& instance); + bool HasCursorLock(const InstanceHandle& instance); + bool CanLockCursor(const InstanceHandle& instance); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_CURSOR_CONTROL_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/device_ref_dev.cc b/chromium/ppapi/cpp/dev/device_ref_dev.cc new file mode 100644 index 00000000000..525739e16fc --- /dev/null +++ b/chromium/ppapi/cpp/dev/device_ref_dev.cc @@ -0,0 +1,48 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/device_ref_dev.h" + +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_DeviceRef_Dev>() { + return PPB_DEVICEREF_DEV_INTERFACE; +} + +} // namespace + +DeviceRef_Dev::DeviceRef_Dev() { +} + +DeviceRef_Dev::DeviceRef_Dev(PP_Resource resource) : Resource(resource) { +} + +DeviceRef_Dev::DeviceRef_Dev(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +DeviceRef_Dev::DeviceRef_Dev(const DeviceRef_Dev& other) : Resource(other) { +} + +DeviceRef_Dev::~DeviceRef_Dev() { +} + +PP_DeviceType_Dev DeviceRef_Dev::GetType() const { + if (!has_interface<PPB_DeviceRef_Dev>()) + return PP_DEVICETYPE_DEV_INVALID; + return get_interface<PPB_DeviceRef_Dev>()->GetType(pp_resource()); +} + +Var DeviceRef_Dev::GetName() const { + if (!has_interface<PPB_DeviceRef_Dev>()) + return Var(); + return Var(PASS_REF, + get_interface<PPB_DeviceRef_Dev>()->GetName(pp_resource())); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/device_ref_dev.h b/chromium/ppapi/cpp/dev/device_ref_dev.h new file mode 100644 index 00000000000..048b95654c7 --- /dev/null +++ b/chromium/ppapi/cpp/dev/device_ref_dev.h @@ -0,0 +1,33 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_DEVICE_REF_DEV_H_ +#define PPAPI_CPP_DEV_DEVICE_REF_DEV_H_ + +#include "ppapi/c/dev/ppb_device_ref_dev.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +class DeviceRef_Dev : public Resource { + public: + DeviceRef_Dev(); + + explicit DeviceRef_Dev(PP_Resource resource); + + DeviceRef_Dev(PassRef, PP_Resource resource); + + DeviceRef_Dev(const DeviceRef_Dev& other); + + virtual ~DeviceRef_Dev(); + + PP_DeviceType_Dev GetType() const; + + Var GetName() const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_DEVICE_REF_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/file_chooser_dev.cc b/chromium/ppapi/cpp/dev/file_chooser_dev.cc new file mode 100644 index 00000000000..b7124a1044b --- /dev/null +++ b/chromium/ppapi/cpp/dev/file_chooser_dev.cc @@ -0,0 +1,102 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/file_chooser_dev.h" + +#include <string.h> + +#include "ppapi/c/dev/ppb_file_chooser_dev.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_FileChooser_Dev_0_5>() { + return PPB_FILECHOOSER_DEV_INTERFACE_0_5; +} + +template <> const char* interface_name<PPB_FileChooser_Dev_0_6>() { + return PPB_FILECHOOSER_DEV_INTERFACE_0_6; +} + +} // namespace + +FileChooser_Dev::FileChooser_Dev(const InstanceHandle& instance, + PP_FileChooserMode_Dev mode, + const Var& accept_types) { + if (has_interface<PPB_FileChooser_Dev_0_6>()) { + PassRefFromConstructor(get_interface<PPB_FileChooser_Dev_0_6>()->Create( + instance.pp_instance(), mode, accept_types.pp_var())); + } else if (has_interface<PPB_FileChooser_Dev_0_5>()) { + PassRefFromConstructor(get_interface<PPB_FileChooser_Dev_0_5>()->Create( + instance.pp_instance(), mode, accept_types.pp_var())); + } +} + +FileChooser_Dev::FileChooser_Dev(const FileChooser_Dev& other) + : Resource(other) { +} + +int32_t FileChooser_Dev::Show( + const CompletionCallbackWithOutput< std::vector<FileRef> >& callback) { + if (has_interface<PPB_FileChooser_Dev_0_6>()) { + return get_interface<PPB_FileChooser_Dev_0_6>()->Show( + pp_resource(), + callback.output(), + callback.pp_completion_callback()); + } + if (has_interface<PPB_FileChooser_Dev_0_5>()) { + // Data for our callback wrapper. The callback handler will delete it. + ChooseCallbackData0_5* data = new ChooseCallbackData0_5; + data->file_chooser = pp_resource(); + data->output = callback.output(); + data->original_callback = callback.pp_completion_callback(); + + return get_interface<PPB_FileChooser_Dev_0_5>()->Show( + pp_resource(), PP_MakeCompletionCallback(&CallbackConverter, data)); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +// static +void FileChooser_Dev::CallbackConverter(void* user_data, int32_t result) { + ChooseCallbackData0_5* data = static_cast<ChooseCallbackData0_5*>(user_data); + + // Get all of the selected file resources using the iterator API. + std::vector<PP_Resource> selected_files; + if (result == PP_OK) { + const PPB_FileChooser_Dev_0_5* chooser = + get_interface<PPB_FileChooser_Dev_0_5>(); + while (PP_Resource cur = chooser->GetNextChosenFile(data->file_chooser)) + selected_files.push_back(cur); + } + + // Need to issue the "GetDataBuffer" even for error cases & when the + // number of items is 0. + void* output_buf = data->output.GetDataBuffer( + data->output.user_data, + selected_files.size(), sizeof(PP_Resource)); + if (output_buf) { + if (!selected_files.empty()) { + memcpy(output_buf, &selected_files[0], + sizeof(PP_Resource) * selected_files.size()); + } + } else { + // Error allocating, need to free the resource IDs. + for (size_t i = 0; i < selected_files.size(); i++) + Module::Get()->core()->ReleaseResource(selected_files[i]); + } + + // Now execute the original callback. + PP_RunCompletionCallback(&data->original_callback, result); + delete data; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/file_chooser_dev.h b/chromium/ppapi/cpp/dev/file_chooser_dev.h new file mode 100644 index 00000000000..3d5ee00c136 --- /dev/null +++ b/chromium/ppapi/cpp/dev/file_chooser_dev.h @@ -0,0 +1,100 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_FILE_CHOOSER_DEV_H_ +#define PPAPI_CPP_DEV_FILE_CHOOSER_DEV_H_ + +#include <vector> + +#include "ppapi/c/dev/ppb_file_chooser_dev.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class CompletionCallback; +class FileRef; +class InstanceHandle; +class Var; + +class FileChooser_Dev : public Resource { + public: + /// Creates an is_null() FileChooser object. + FileChooser_Dev() {} + + /// This function creates a file chooser dialog resource. The chooser is + /// associated with a particular instance, so that it may be positioned on the + /// screen relative to the tab containing the instance. Returns 0 if passed + /// an invalid instance. + /// + /// @param mode A PPB_FileChooser_Dev instance can be used to select a single + /// file (PP_FILECHOOSERMODE_OPEN) or multiple files + /// (PP_FILECHOOSERMODE_OPENMULTIPLE). Unlike the HTML5 <input type="file"> + /// tag, a PPB_FileChooser_Dev instance cannot be used to select a directory. + /// In order to get the list of files in a directory, the + /// PPB_FileRef::ReadDirectoryEntries interface must be used. + /// + /// @param accept_types A comma-separated list of MIME types and file + /// extensions such as "audio/ *,text/plain,.html" (note there should be + /// no space between the '/' and the '*', but one is added to avoid confusing + /// C++ comments). The dialog may restrict selectable files to the specified + /// MIME types and file extensions. If a string in the comma-separated list + /// begins with a period (.) then the string is interpreted as a file + /// extension, otherwise it is interpreted as a MIME-type. An empty string or + /// an undefined var may be given to indicate that all types should be + /// accepted. + FileChooser_Dev(const InstanceHandle& instance, + PP_FileChooserMode_Dev mode, + const Var& accept_types); + + FileChooser_Dev(const FileChooser_Dev& other); + + /// This function displays a previously created file chooser resource as a + /// dialog box, prompting the user to choose a file or files. This function + /// must be called in response to a user gesture, such as a mouse click or + /// touch event. The callback is called with PP_OK on successful completion + /// with a file (or files) selected, PP_ERROR_USERCANCEL if the user selected + /// no file, or another error code from pp_errors.h on failure. + /// + /// @param callback The completion callback that will be executed. On success, + /// the selected files will be passed to the given function. + /// + /// Normally you would use a CompletionCallbackFactory to allow callbacks to + /// be bound to your class. See completion_callback_factory.h for more + /// discussion on how to use this. Your callback will generally look like: + /// + /// @code + /// void OnFilesSelected(int32_t result, + /// const std::vector<pp::FileRef>& files) { + /// if (result == PP_OK) + /// // use files... + /// } + /// @endcode + /// + /// @return PP_OK_COMPLETIONPENDING if request to show the dialog was + /// successful, another error code from pp_errors.h on failure. + virtual int32_t Show( + const CompletionCallbackWithOutput< std::vector<FileRef> >& callback); + + protected: + // Heap-allocated data passed to the CallbackConverter for backwards compat. + struct ChooseCallbackData0_5 { + PP_Resource file_chooser; + PP_ArrayOutput output; + PP_CompletionCallback original_callback; + }; + + // Provide backwards-compatibility for older versions. Converts the old-style + // 0.5 "iterator" interface to the new-style 0.6 "array output" interface that + // the caller is expecting. + // + // This takes a heap-allocated ChooseCallbackData0_5 struct passed as the + // user data and deletes it when the call completes. + static void CallbackConverter(void* user_data, int32_t result); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_FILE_CHOOSER_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/find_dev.cc b/chromium/ppapi/cpp/dev/find_dev.cc new file mode 100644 index 00000000000..e9640bc7e11 --- /dev/null +++ b/chromium/ppapi/cpp/dev/find_dev.cc @@ -0,0 +1,77 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/find_dev.h" + +#include "ppapi/c/dev/ppb_find_dev.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Find_Dev>() { + return PPB_FIND_DEV_INTERFACE; +} + +static const char kPPPFindInterface[] = PPP_FIND_DEV_INTERFACE; + +PP_Bool StartFind(PP_Instance instance, + const char* text, + PP_Bool case_sensitive) { + void* object = Instance::GetPerInstanceObject(instance, kPPPFindInterface); + if (!object) + return PP_FALSE; + bool return_value = static_cast<Find_Dev*>(object)->StartFind( + text, PP_ToBool(case_sensitive)); + return PP_FromBool(return_value); +} + +void SelectFindResult(PP_Instance instance, PP_Bool forward) { + void* object = Instance::GetPerInstanceObject(instance, kPPPFindInterface); + if (object) + static_cast<Find_Dev*>(object)->SelectFindResult(PP_ToBool(forward)); +} + +void StopFind(PP_Instance instance) { + void* object = Instance::GetPerInstanceObject(instance, kPPPFindInterface); + if (object) + static_cast<Find_Dev*>(object)->StopFind(); +} + +const PPP_Find_Dev ppp_find = { + &StartFind, + &SelectFindResult, + &StopFind +}; + +} // namespace + +Find_Dev::Find_Dev(Instance* instance) : associated_instance_(instance) { + Module::Get()->AddPluginInterface(kPPPFindInterface, &ppp_find); + instance->AddPerInstanceObject(kPPPFindInterface, this); +} + +Find_Dev::~Find_Dev() { + Instance::RemovePerInstanceObject(associated_instance_, + kPPPFindInterface, this); +} + +void Find_Dev::NumberOfFindResultsChanged(int32_t total, bool final_result) { + if (has_interface<PPB_Find_Dev>()) { + get_interface<PPB_Find_Dev>()->NumberOfFindResultsChanged( + associated_instance_.pp_instance(), total, PP_FromBool(final_result)); + } +} + +void Find_Dev::SelectedFindResultChanged(int32_t index) { + if (has_interface<PPB_Find_Dev>()) { + get_interface<PPB_Find_Dev>()->SelectedFindResultChanged( + associated_instance_.pp_instance(), index); + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/find_dev.h b/chromium/ppapi/cpp/dev/find_dev.h new file mode 100644 index 00000000000..89c2d5a0cf5 --- /dev/null +++ b/chromium/ppapi/cpp/dev/find_dev.h @@ -0,0 +1,62 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_FIND_DEV_H_ +#define PPAPI_CPP_DEV_FIND_DEV_H_ + +#include <string> + +#include "ppapi/c/dev/ppp_find_dev.h" +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +class Instance; + +// This class allows you to associate the PPP_Find and PPB_Find C-based +// interfaces with an object. It associates itself with the given instance, and +// registers as the global handler for handling the PPP_Find interface that the +// browser calls. +// +// You would typically use this either via inheritance on your instance: +// class MyInstance : public pp::Instance, public pp::Find_Dev { +// class MyInstance() : pp::Find_Dev(this) { +// } +// ... +// }; +// +// or by composition: +// class MyFinder : public pp::Find { +// ... +// }; +// +// class MyInstance : public pp::Instance { +// MyInstance() : finder_(this) { +// } +// +// MyFinder finder_; +// }; +class Find_Dev { + public: + // The instance parameter must outlive this class. + Find_Dev(Instance* instance); + virtual ~Find_Dev(); + + // PPP_Find_Dev functions exposed as virtual functions for you to + // override. + virtual bool StartFind(const std::string& text, bool case_sensitive) = 0; + virtual void SelectFindResult(bool forward) = 0; + virtual void StopFind() = 0; + + // PPB_Find_Def functions for you to call to report find results. + void NumberOfFindResultsChanged(int32_t total, bool final_result); + void SelectedFindResultChanged(int32_t index); + + private: + InstanceHandle associated_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_FIND_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/font_dev.cc b/chromium/ppapi/cpp/dev/font_dev.cc new file mode 100644 index 00000000000..4c74d472903 --- /dev/null +++ b/chromium/ppapi/cpp/dev/font_dev.cc @@ -0,0 +1,200 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/font_dev.h" + +#include <algorithm> + +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/rect.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Font_Dev>() { + return PPB_FONT_DEV_INTERFACE; +} + +} // namespace + +// FontDescription_Dev --------------------------------------------------------- + +FontDescription_Dev::FontDescription_Dev() { + pp_font_description_.face = face_.pp_var(); + set_family(PP_FONTFAMILY_DEFAULT); + set_size(0); + set_weight(PP_FONTWEIGHT_NORMAL); + set_italic(false); + set_small_caps(false); + set_letter_spacing(0); + set_word_spacing(0); +} + +FontDescription_Dev::FontDescription_Dev(const FontDescription_Dev& other) { + set_face(other.face()); + set_family(other.family()); + set_size(other.size()); + set_weight(other.weight()); + set_italic(other.italic()); + set_small_caps(other.small_caps()); + set_letter_spacing(other.letter_spacing()); + set_word_spacing(other.word_spacing()); +} + +FontDescription_Dev::~FontDescription_Dev() { +} + +FontDescription_Dev& FontDescription_Dev::operator=( + const FontDescription_Dev& other) { + pp_font_description_ = other.pp_font_description_; + + // Be careful about the refcount of the string, the copy that operator= made + // above didn't copy a ref. + pp_font_description_.face = PP_MakeUndefined(); + set_face(other.face()); + + return *this; +} + +// TextRun_Dev ----------------------------------------------------------------- + +TextRun_Dev::TextRun_Dev() { + pp_text_run_.text = text_.pp_var(); + pp_text_run_.rtl = PP_FALSE; + pp_text_run_.override_direction = PP_FALSE; +} + +TextRun_Dev::TextRun_Dev(const std::string& text, + bool rtl, + bool override_direction) + : text_(text) { + pp_text_run_.text = text_.pp_var(); + pp_text_run_.rtl = PP_FromBool(rtl); + pp_text_run_.override_direction = PP_FromBool(override_direction); +} + +TextRun_Dev::TextRun_Dev(const TextRun_Dev& other) : text_(other.text_) { + pp_text_run_.text = text_.pp_var(); + pp_text_run_.rtl = other.pp_text_run_.rtl; + pp_text_run_.override_direction = other.pp_text_run_.override_direction; +} + +TextRun_Dev::~TextRun_Dev() { +} + +TextRun_Dev& TextRun_Dev::operator=(const TextRun_Dev& other) { + pp_text_run_ = other.pp_text_run_; + text_ = other.text_; + pp_text_run_.text = text_.pp_var(); + return *this; +} + +// Font ------------------------------------------------------------------------ + +Font_Dev::Font_Dev() : Resource() { +} + +Font_Dev::Font_Dev(PP_Resource resource) : Resource(resource) { +} + +Font_Dev::Font_Dev(const InstanceHandle& instance, + const FontDescription_Dev& description) { + if (!has_interface<PPB_Font_Dev>()) + return; + PassRefFromConstructor(get_interface<PPB_Font_Dev>()->Create( + instance.pp_instance(), &description.pp_font_description())); +} + +Font_Dev::Font_Dev(const Font_Dev& other) : Resource(other) { +} + +Font_Dev& Font_Dev::operator=(const Font_Dev& other) { + Resource::operator=(other); + return *this; +} + +// static +Var Font_Dev::GetFontFamilies(const InstanceHandle& instance) { + if (!has_interface<PPB_Font_Dev>()) + return Var(); + return Var(PASS_REF, get_interface<PPB_Font_Dev>()->GetFontFamilies( + instance.pp_instance())); +} + +bool Font_Dev::Describe(FontDescription_Dev* description, + PP_FontMetrics_Dev* metrics) const { + if (!has_interface<PPB_Font_Dev>()) + return false; + + // Be careful with ownership of the |face| string. It will come back with + // a ref of 1, which we want to assign to the |face_| member of the C++ class. + if (!get_interface<PPB_Font_Dev>()->Describe( + pp_resource(), &description->pp_font_description_, metrics)) + return false; + description->face_ = Var(PASS_REF, + description->pp_font_description_.face); + + return true; +} + +bool Font_Dev::DrawTextAt(ImageData* dest, + const TextRun_Dev& text, + const Point& position, + uint32_t color, + const Rect& clip, + bool image_data_is_opaque) const { + if (!has_interface<PPB_Font_Dev>()) + return false; + return PP_ToBool(get_interface<PPB_Font_Dev>()->DrawTextAt( + pp_resource(), + dest->pp_resource(), + &text.pp_text_run(), + &position.pp_point(), + color, + &clip.pp_rect(), + PP_FromBool(image_data_is_opaque))); +} + +int32_t Font_Dev::MeasureText(const TextRun_Dev& text) const { + if (!has_interface<PPB_Font_Dev>()) + return -1; + return get_interface<PPB_Font_Dev>()->MeasureText(pp_resource(), + &text.pp_text_run()); +} + +uint32_t Font_Dev::CharacterOffsetForPixel(const TextRun_Dev& text, + int32_t pixel_position) const { + if (!has_interface<PPB_Font_Dev>()) + return 0; + return get_interface<PPB_Font_Dev>()->CharacterOffsetForPixel( + pp_resource(), &text.pp_text_run(), pixel_position); + +} + +int32_t Font_Dev::PixelOffsetForCharacter(const TextRun_Dev& text, + uint32_t char_offset) const { + if (!has_interface<PPB_Font_Dev>()) + return 0; + return get_interface<PPB_Font_Dev>()->PixelOffsetForCharacter( + pp_resource(), &text.pp_text_run(), char_offset); +} + +bool Font_Dev::DrawSimpleText(ImageData* dest, + const std::string& text, + const Point& position, + uint32_t color, + bool image_data_is_opaque) const { + return DrawTextAt(dest, TextRun_Dev(text), position, color, + Rect(dest->size()), image_data_is_opaque); +} + +int32_t Font_Dev::MeasureSimpleText(const std::string& text) const { + return MeasureText(TextRun_Dev(text)); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/font_dev.h b/chromium/ppapi/cpp/dev/font_dev.h new file mode 100644 index 00000000000..d0875a50cc3 --- /dev/null +++ b/chromium/ppapi/cpp/dev/font_dev.h @@ -0,0 +1,141 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_DEV_FONT_DEV_H_ +#define PPAPI_CPP_DEV_FONT_DEV_H_ + +#include <string> + +#include "ppapi/c/dev/ppb_font_dev.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" + +struct PP_FontDescription_Dev; + +namespace pp { + +class ImageData; +class InstanceHandle; +class Point; +class Rect; + +// FontDescription_Dev --------------------------------------------------------- + +class FontDescription_Dev { + public: + FontDescription_Dev(); + FontDescription_Dev(const FontDescription_Dev& other); + ~FontDescription_Dev(); + + FontDescription_Dev& operator=(const FontDescription_Dev& other); + + const PP_FontDescription_Dev& pp_font_description() const { + return pp_font_description_; + } + + Var face() const { return face_; } + void set_face(const Var& face) { + face_ = face; + pp_font_description_.face = face_.pp_var(); + } + + PP_FontFamily_Dev family() const { return pp_font_description_.family; } + void set_family(PP_FontFamily_Dev f) { pp_font_description_.family = f; } + + uint32_t size() const { return pp_font_description_.size; } + void set_size(uint32_t s) { pp_font_description_.size = s; } + + PP_FontWeight_Dev weight() const { return pp_font_description_.weight; } + void set_weight(PP_FontWeight_Dev w) { pp_font_description_.weight = w; } + + bool italic() const { return PP_ToBool(pp_font_description_.italic); } + void set_italic(bool i) { pp_font_description_.italic = PP_FromBool(i); } + + bool small_caps() const { + return PP_ToBool(pp_font_description_.small_caps); + } + void set_small_caps(bool s) { + pp_font_description_.small_caps = PP_FromBool(s); + } + + int letter_spacing() const { return pp_font_description_.letter_spacing; } + void set_letter_spacing(int s) { pp_font_description_.letter_spacing = s; } + + int word_spacing() const { return pp_font_description_.word_spacing; } + void set_word_spacing(int w) { pp_font_description_.word_spacing = w; } + + private: + friend class Font_Dev; + + Var face_; // Manages memory for pp_font_description_.face + PP_FontDescription_Dev pp_font_description_; +}; + +// TextRun_Dev ----------------------------------------------------------------- + +class TextRun_Dev { + public: + TextRun_Dev(); + TextRun_Dev(const std::string& text, + bool rtl = false, + bool override_direction = false); + TextRun_Dev(const TextRun_Dev& other); + ~TextRun_Dev(); + + TextRun_Dev& operator=(const TextRun_Dev& other); + + const PP_TextRun_Dev& pp_text_run() const { + return pp_text_run_; + } + + private: + Var text_; // Manages memory for the reference in pp_text_run_. + PP_TextRun_Dev pp_text_run_; +}; + +// Font ------------------------------------------------------------------------ + +// Provides access to system fonts. +class Font_Dev : public Resource { + public: + // Creates an is_null() Font object. + Font_Dev(); + + explicit Font_Dev(PP_Resource resource); + Font_Dev(const InstanceHandle& instance, + const FontDescription_Dev& description); + Font_Dev(const Font_Dev& other); + + Font_Dev& operator=(const Font_Dev& other); + + // PPB_Font methods: + static Var GetFontFamilies(const InstanceHandle& instance); + bool Describe(FontDescription_Dev* description, + PP_FontMetrics_Dev* metrics) const; + bool DrawTextAt(ImageData* dest, + const TextRun_Dev& text, + const Point& position, + uint32_t color, + const Rect& clip, + bool image_data_is_opaque) const; + int32_t MeasureText(const TextRun_Dev& text) const; + uint32_t CharacterOffsetForPixel(const TextRun_Dev& text, + int32_t pixel_position) const; + int32_t PixelOffsetForCharacter(const TextRun_Dev& text, + uint32_t char_offset) const; + + // Convenience function that assumes a left-to-right string with no clipping. + bool DrawSimpleText(ImageData* dest, + const std::string& text, + const Point& position, + uint32_t color, + bool image_data_is_opaque = false) const; + + // Convenience function that assumes a left-to-right string. + int32_t MeasureSimpleText(const std::string& text) const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_FONT_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/graphics_2d_dev.cc b/chromium/ppapi/cpp/dev/graphics_2d_dev.cc new file mode 100644 index 00000000000..e141bb6b705 --- /dev/null +++ b/chromium/ppapi/cpp/dev/graphics_2d_dev.cc @@ -0,0 +1,38 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/graphics_2d_dev.h" + +#include "ppapi/c/dev/ppb_graphics_2d_dev.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Graphics2D_Dev>() { + return PPB_GRAPHICS2D_DEV_INTERFACE; +} + +} // namespace + +// static +bool Graphics2D_Dev::SupportsScale() { + return has_interface<PPB_Graphics2D_Dev>(); +} + +bool Graphics2D_Dev::SetScale(float scale) { + if (!has_interface<PPB_Graphics2D_Dev>()) + return false; + return PP_ToBool(get_interface<PPB_Graphics2D_Dev>()->SetScale(pp_resource(), + scale)); +} + +float Graphics2D_Dev::GetScale() { + if (!has_interface<PPB_Graphics2D_Dev>()) + return 1.0f; + return get_interface<PPB_Graphics2D_Dev>()->GetScale(pp_resource()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/graphics_2d_dev.h b/chromium/ppapi/cpp/dev/graphics_2d_dev.h new file mode 100644 index 00000000000..3dc8c7190ae --- /dev/null +++ b/chromium/ppapi/cpp/dev/graphics_2d_dev.h @@ -0,0 +1,55 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_GRAPHICS_2D_DEV_H_ +#define PPAPI_CPP_DEV_GRAPHICS_2D_DEV_H_ + +#include "ppapi/cpp/graphics_2d.h" + +namespace pp { + +// Graphics2DDev is a version of Graphics2D that exposes under-development APIs +// for HiDPI +class Graphics2D_Dev : public Graphics2D { + public: + /// Default constructor for creating an is_null() + /// <code>Graphics2D_Dev</code> object. + Graphics2D_Dev() : Graphics2D() {} + + // Constructor for creating a <code>Graphics2DDev</code> object from an + // existing <code>Graphics2D</code> object. + Graphics2D_Dev(const Graphics2D& other) : Graphics2D(other) {} + + virtual ~Graphics2D_Dev() {} + + /// Returns true if SetScale and GetScale are supported. False if not. + static bool SupportsScale(); + + /// SetScale() sets the scale factor that will be applied when painting the + /// graphics context onto the output device. Typically, if rendering at device + /// resolution is desired, the context would be created with the width and + /// height scaled up by the view's GetDeviceScale and SetScale called with a + /// scale of 1.0 / GetDeviceScale(). For example, if the view resource passed + /// to DidChangeView has a rectangle of (w=200, h=100) and a device scale of + /// 2.0, one would call Create with a size of (w=400, h=200) and then call + /// SetScale with 0.5. One would then treat each pixel in the context as a + /// single device pixel. + /// + /// @param[in] scale The scale to apply when painting. + /// + /// @return Returns <code>true</code> on success or <code>false</code> + /// if the resource is invalid or the scale factor is 0 or less. + bool SetScale(float scale); + + /// GetScale() gets the scale factor that will be applied when painting the + /// graphics context onto the output device. + /// + /// @return Returns the scale factor for the graphics context. If the resource + /// is invalid, 0.0 will be returned. + float GetScale(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_GRAPHICS_2D_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/ime_input_event_dev.cc b/chromium/ppapi/cpp/dev/ime_input_event_dev.cc new file mode 100644 index 00000000000..9ddc16e9138 --- /dev/null +++ b/chromium/ppapi/cpp/dev/ime_input_event_dev.cc @@ -0,0 +1,131 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/ime_input_event_dev.h" + +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_IMEInputEvent_Dev_0_2>() { + return PPB_IME_INPUT_EVENT_DEV_INTERFACE_0_2; +} + +template <> const char* interface_name<PPB_IMEInputEvent_Dev_0_1>() { + return PPB_IME_INPUT_EVENT_DEV_INTERFACE_0_1; +} + +} // namespace + +// IMEInputEvent_Dev ------------------------------------------------------- + +IMEInputEvent_Dev::IMEInputEvent_Dev() : InputEvent() { +} + +IMEInputEvent_Dev::IMEInputEvent_Dev(const InputEvent& event) : InputEvent() { + bool is_ime_event = false; + if (has_interface<PPB_IMEInputEvent_Dev_0_2>()) { + if (get_interface<PPB_IMEInputEvent_Dev_0_2>()->IsIMEInputEvent( + event.pp_resource())) { + is_ime_event = true; + } + } else if (has_interface<PPB_IMEInputEvent_Dev_0_1>()) { + if (get_interface<PPB_IMEInputEvent_Dev_0_1>()->IsIMEInputEvent( + event.pp_resource())) { + is_ime_event = true; + } + } + + if (is_ime_event) { + Module::Get()->core()->AddRefResource(event.pp_resource()); + PassRefFromConstructor(event.pp_resource()); + } +} + +IMEInputEvent_Dev::IMEInputEvent_Dev( + const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + const Var& text, + const std::vector<uint32_t>& segment_offsets, + int32_t target_segment, + const std::pair<uint32_t, uint32_t>& selection) : InputEvent() { + if (!has_interface<PPB_IMEInputEvent_Dev_0_2>()) + return; + uint32_t dummy = 0; + PassRefFromConstructor(get_interface<PPB_IMEInputEvent_Dev_0_2>()->Create( + instance.pp_instance(), type, time_stamp, text.pp_var(), + segment_offsets.empty() ? 0 : segment_offsets.size() - 1, + segment_offsets.empty() ? &dummy : &segment_offsets[0], + target_segment, selection.first, selection.second)); +} + + +Var IMEInputEvent_Dev::GetText() const { + if (has_interface<PPB_IMEInputEvent_Dev_0_2>()) { + return Var(PASS_REF, + get_interface<PPB_IMEInputEvent_Dev_0_2>()->GetText( + pp_resource())); + } else if (has_interface<PPB_IMEInputEvent_Dev_0_1>()) { + return Var(PASS_REF, + get_interface<PPB_IMEInputEvent_Dev_0_1>()->GetText( + pp_resource())); + } + return Var(); +} + +uint32_t IMEInputEvent_Dev::GetSegmentNumber() const { + if (has_interface<PPB_IMEInputEvent_Dev_0_2>()) { + return get_interface<PPB_IMEInputEvent_Dev_0_2>()->GetSegmentNumber( + pp_resource()); + } else if (has_interface<PPB_IMEInputEvent_Dev_0_1>()) { + return get_interface<PPB_IMEInputEvent_Dev_0_1>()->GetSegmentNumber( + pp_resource()); + } + return 0; +} + +uint32_t IMEInputEvent_Dev::GetSegmentOffset(uint32_t index) const { + if (has_interface<PPB_IMEInputEvent_Dev_0_2>()) { + return get_interface<PPB_IMEInputEvent_Dev_0_2>()->GetSegmentOffset( + pp_resource(), index); + } else if (has_interface<PPB_IMEInputEvent_Dev_0_1>()) { + return get_interface<PPB_IMEInputEvent_Dev_0_1>()->GetSegmentOffset( + pp_resource(), index); + } + return 0; +} + +int32_t IMEInputEvent_Dev::GetTargetSegment() const { + if (has_interface<PPB_IMEInputEvent_Dev_0_2>()) { + return get_interface<PPB_IMEInputEvent_Dev_0_2>()->GetTargetSegment( + pp_resource()); + } else if (has_interface<PPB_IMEInputEvent_Dev_0_1>()) { + return get_interface<PPB_IMEInputEvent_Dev_0_1>()->GetTargetSegment( + pp_resource()); + } + return 0; +} + +std::pair<uint32_t, uint32_t> IMEInputEvent_Dev::GetSelection() const { + std::pair<uint32_t, uint32_t> range(0, 0); + if (has_interface<PPB_IMEInputEvent_Dev_0_2>()) { + get_interface<PPB_IMEInputEvent_Dev_0_2>()->GetSelection(pp_resource(), + &range.first, + &range.second); + } else if (has_interface<PPB_IMEInputEvent_Dev_0_1>()) { + get_interface<PPB_IMEInputEvent_Dev_0_1>()->GetSelection(pp_resource(), + &range.first, + &range.second); + } + return range; +} + + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/ime_input_event_dev.h b/chromium/ppapi/cpp/dev/ime_input_event_dev.h new file mode 100644 index 00000000000..f9126aa4a1b --- /dev/null +++ b/chromium/ppapi/cpp/dev/ime_input_event_dev.h @@ -0,0 +1,106 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_IME_INPUT_EVENT_DEV_H_ +#define PPAPI_CPP_DEV_IME_INPUT_EVENT_DEV_H_ + +#include <utility> +#include <vector> + +#include "ppapi/c/dev/ppb_ime_input_event_dev.h" +#include "ppapi/cpp/input_event.h" + +/// @file +/// This file defines the API used to handle IME input events. + +namespace pp { + +class Var; + +class IMEInputEvent_Dev : public InputEvent { + public: + /// Constructs an is_null() IME input event object. + IMEInputEvent_Dev(); + + /// Constructs an IME input event object from the provided generic input + /// event. If the given event is itself is_null() or is not an IME input + /// event, the object will be is_null(). + /// + /// @param[in] event A generic input event. + explicit IMEInputEvent_Dev(const InputEvent& event); + + /// This constructor manually constructs an IME event from the provided + /// parameters. + /// + /// @param[in] instance The instance for which this event occurred. + /// + /// @param[in] type A <code>PP_InputEvent_Type</code> identifying the type of + /// input event. The type must be one of the ime event types. + /// + /// @param[in] time_stamp A <code>PP_TimeTicks</code> indicating the time + /// when the event occurred. + /// + /// @param[in] text The string returned by <code>GetText</code>. + /// + /// @param[in] segment_offsets The array of numbers returned by + /// <code>GetSegmentOffset</code>. + /// + /// @param[in] target_segment The number returned by + /// <code>GetTargetSegment</code>. + /// + /// @param[in] selection The range returned by <code>GetSelection</code>. + IMEInputEvent_Dev(const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + const Var& text, + const std::vector<uint32_t>& segment_offsets, + int32_t target_segment, + const std::pair<uint32_t, uint32_t>& selection); + + /// Returns the composition text as a UTF-8 string for the given IME event. + /// + /// @return A string var representing the composition text. For non-IME + /// input events the return value will be an undefined var. + Var GetText() const; + + /// Returns the number of segments in the composition text. + /// + /// @return The number of segments. For events other than COMPOSITION_UPDATE, + /// returns 0. + uint32_t GetSegmentNumber() const; + + /// Returns the position of the index-th segmentation point in the composition + /// text. The position is given by a byte-offset (not a character-offset) of + /// the string returned by GetText(). It always satisfies + /// 0=GetSegmentOffset(0) < ... < GetSegmentOffset(i) < GetSegmentOffset(i+1) + /// < ... < GetSegmentOffset(GetSegmentNumber())=(byte-length of GetText()). + /// Note that [GetSegmentOffset(i), GetSegmentOffset(i+1)) represents the + /// range of the i-th segment, and hence GetSegmentNumber() can be a valid + /// argument to this function instead of an off-by-1 error. + /// + /// @param[in] ime_event A <code>PP_Resource</code> corresponding to an IME + /// event. + /// + /// @param[in] index An integer indicating a segment. + /// + /// @return The byte-offset of the segmentation point. If the event is not + /// COMPOSITION_UPDATE or index is out of range, returns 0. + uint32_t GetSegmentOffset(uint32_t index) const; + + /// Returns the index of the current target segment of composition. + /// + /// @return An integer indicating the index of the target segment. When there + /// is no active target segment, or the event is not COMPOSITION_UPDATE, + /// returns -1. + int32_t GetTargetSegment() const; + + /// Returns the range selected by caret in the composition text. + /// + /// @return A pair of integers indicating the selection range. + std::pair<uint32_t, uint32_t> GetSelection() const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_IME_INPUT_EVENT_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/memory_dev.cc b/chromium/ppapi/cpp/dev/memory_dev.cc new file mode 100644 index 00000000000..ca7c125f8dd --- /dev/null +++ b/chromium/ppapi/cpp/dev/memory_dev.cc @@ -0,0 +1,33 @@ +// Copyright (c) 2011 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 "ppapi/cpp/dev/memory_dev.h" + +#include "ppapi/c/dev/ppb_memory_dev.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Memory_Dev>() { + return PPB_MEMORY_DEV_INTERFACE; +} + +} // namespace + +void* Memory_Dev::MemAlloc(uint32_t num_bytes) { + if (!has_interface<PPB_Memory_Dev>()) + return NULL; + return get_interface<PPB_Memory_Dev>()->MemAlloc(num_bytes); +} + +void Memory_Dev::MemFree(void* ptr) { + if (!has_interface<PPB_Memory_Dev>() || !ptr) + return; + get_interface<PPB_Memory_Dev>()->MemFree(ptr); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/memory_dev.h b/chromium/ppapi/cpp/dev/memory_dev.h new file mode 100644 index 00000000000..2695cae0e64 --- /dev/null +++ b/chromium/ppapi/cpp/dev/memory_dev.h @@ -0,0 +1,36 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_DEV_MEMORY_DEV_H_ +#define PPAPI_CPP_DEV_MEMORY_DEV_H_ + +#include "ppapi/c/pp_stdint.h" + +/// @file +/// This file defines APIs related to memory management. + +namespace pp { + +/// APIs related to memory management, time, and threads. +class Memory_Dev { + public: + Memory_Dev() {} + + /// A function that allocates memory. + /// + /// @param[in] num_bytes A number of bytes to allocate. + /// @return A pointer to the memory if successful, NULL If the + /// allocation fails. + void* MemAlloc(uint32_t num_bytes); + + /// A function that deallocates memory. + /// + /// @param[in] ptr A pointer to the memory to deallocate. It is safe to + /// pass NULL to this function. + void MemFree(void* ptr); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_MEMORY_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/printing_dev.cc b/chromium/ppapi/cpp/dev/printing_dev.cc new file mode 100644 index 00000000000..60154cd0d37 --- /dev/null +++ b/chromium/ppapi/cpp/dev/printing_dev.cc @@ -0,0 +1,108 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/printing_dev.h" + +#include "ppapi/c/dev/ppb_printing_dev.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +static const char kPPPPrintingInterface[] = PPP_PRINTING_DEV_INTERFACE; + +template <> const char* interface_name<PPB_Printing_Dev_0_7>() { + return PPB_PRINTING_DEV_INTERFACE_0_7; +} + +uint32_t QuerySupportedFormats(PP_Instance instance) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPPrintingInterface); + if (!object) + return 0; + return static_cast<Printing_Dev*>(object)->QuerySupportedPrintOutputFormats(); +} + +int32_t Begin(PP_Instance instance, + const struct PP_PrintSettings_Dev* print_settings) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPPrintingInterface); + if (!object) + return 0; + return static_cast<Printing_Dev*>(object)->PrintBegin(*print_settings); +} + +PP_Resource PrintPages(PP_Instance instance, + const struct PP_PrintPageNumberRange_Dev* page_ranges, + uint32_t page_range_count) { + void* object = + pp::Instance::GetPerInstanceObject(instance, kPPPPrintingInterface); + if (!object) + return 0; + return static_cast<Printing_Dev*>(object)->PrintPages( + page_ranges, page_range_count).detach(); +} + +void End(PP_Instance instance) { + void* object = + pp::Instance::GetPerInstanceObject(instance, kPPPPrintingInterface); + if (object) + static_cast<Printing_Dev*>(object)->PrintEnd(); +} + +PP_Bool IsScalingDisabled(PP_Instance instance) { + void* object = + pp::Instance::GetPerInstanceObject(instance, kPPPPrintingInterface); + if (!object) + return PP_FALSE; + bool return_value = + static_cast<Printing_Dev*>(object)->IsPrintScalingDisabled(); + return PP_FromBool(return_value); +} + +const PPP_Printing_Dev ppp_printing = { + &QuerySupportedFormats, + &Begin, + &PrintPages, + &End, + &IsScalingDisabled +}; + +} // namespace + +Printing_Dev::Printing_Dev(Instance* instance) + : associated_instance_(instance) { + Module::Get()->AddPluginInterface(kPPPPrintingInterface, &ppp_printing); + instance->AddPerInstanceObject( + kPPPPrintingInterface, this); + if (has_interface<PPB_Printing_Dev_0_7>()) { + PassRefFromConstructor(get_interface<PPB_Printing_Dev_0_7>()->Create( + associated_instance_.pp_instance())); + } +} + +Printing_Dev::~Printing_Dev() { + Instance::RemovePerInstanceObject(associated_instance_, + kPPPPrintingInterface, this); +} + +// static +bool Printing_Dev::IsAvailable() { + return has_interface<PPB_Printing_Dev_0_7>(); +} + +int32_t Printing_Dev::GetDefaultPrintSettings( + const CompletionCallbackWithOutput<PP_PrintSettings_Dev>& callback) const { + if (has_interface<PPB_Printing_Dev_0_7>()) { + return get_interface<PPB_Printing_Dev_0_7>()->GetDefaultPrintSettings( + pp_resource(), callback.output(), callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/printing_dev.h b/chromium/ppapi/cpp/dev/printing_dev.h new file mode 100644 index 00000000000..b219b13116f --- /dev/null +++ b/chromium/ppapi/cpp/dev/printing_dev.h @@ -0,0 +1,49 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_PRINTING_DEV_H_ +#define PPAPI_CPP_DEV_PRINTING_DEV_H_ + +#include "ppapi/c/dev/ppp_printing_dev.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class Instance; + +// You would typically use this either via inheritance on your instance or +// by composition: see find_dev.h for an example. +class Printing_Dev : public Resource { + public: + // The instance parameter must outlive this class. + explicit Printing_Dev(Instance* instance); + virtual ~Printing_Dev(); + + // PPP_Printing_Dev functions exposed as virtual functions for you to + // override. + virtual uint32_t QuerySupportedPrintOutputFormats() = 0; + virtual int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) = 0; + virtual Resource PrintPages(const PP_PrintPageNumberRange_Dev* page_ranges, + uint32_t page_range_count) = 0; + virtual void PrintEnd() = 0; + virtual bool IsPrintScalingDisabled() = 0; + + // PPB_Printing_Dev functions. + // Returns true if the browser supports the required PPB_Printing_Dev + // interface. + static bool IsAvailable(); + + // Get the default print settings and store them in the output of |callback|. + int32_t GetDefaultPrintSettings( + const CompletionCallbackWithOutput<PP_PrintSettings_Dev>& callback) const; + + private: + InstanceHandle associated_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_PRINTING_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/resource_array_dev.cc b/chromium/ppapi/cpp/dev/resource_array_dev.cc new file mode 100644 index 00000000000..5bd25493264 --- /dev/null +++ b/chromium/ppapi/cpp/dev/resource_array_dev.cc @@ -0,0 +1,92 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/resource_array_dev.h" + +#include "ppapi/c/dev/ppb_resource_array_dev.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_ResourceArray_Dev>() { + return PPB_RESOURCEARRAY_DEV_INTERFACE; +} + +} // namespace + +ResourceArray_Dev::ResourceArray_Dev() { +} + +ResourceArray_Dev::ResourceArray_Dev(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +ResourceArray_Dev::ResourceArray_Dev(const ResourceArray_Dev& other) + : Resource(other) { +} + +ResourceArray_Dev::ResourceArray_Dev(const InstanceHandle& instance, + const PP_Resource elements[], + uint32_t size) { + if (has_interface<PPB_ResourceArray_Dev>()) { + PassRefFromConstructor(get_interface<PPB_ResourceArray_Dev>()->Create( + instance.pp_instance(), elements, size)); + } +} + +ResourceArray_Dev::~ResourceArray_Dev() { +} + +ResourceArray_Dev& ResourceArray_Dev::operator=( + const ResourceArray_Dev& other) { + Resource::operator=(other); + return *this; +} + +uint32_t ResourceArray_Dev::size() const { + if (!has_interface<PPB_ResourceArray_Dev>()) + return 0; + return get_interface<PPB_ResourceArray_Dev>()->GetSize(pp_resource()); +} + +PP_Resource ResourceArray_Dev::operator[](uint32_t index) const { + if (!has_interface<PPB_ResourceArray_Dev>()) + return 0; + return get_interface<PPB_ResourceArray_Dev>()->GetAt(pp_resource(), index); +} + +// static +void ResourceArray_Dev::ArrayOutputCallbackConverter(void* user_data, + int32_t result) { + ArrayOutputCallbackData* data = + static_cast<ArrayOutputCallbackData*>(user_data); + + // data->resource_array_output should remain 0 if the call failed. + ResourceArray_Dev resources(PASS_REF, data->resource_array_output); + PP_DCHECK(resources.is_null() || result == PP_OK); + + // Need to issue the "GetDataBuffer" even for error cases and when the number + // of items is 0. + PP_Resource* output_buf = static_cast<PP_Resource*>( + data->output.GetDataBuffer( + data->output.user_data, resources.is_null() ? 0 : resources.size(), + sizeof(PP_Resource))); + if (output_buf) { + for (uint32_t index = 0; index < resources.size(); ++index) { + output_buf[index] = resources[index]; + Module::Get()->core()->AddRefResource(output_buf[index]); + } + } + + PP_RunCompletionCallback(&data->original_callback, result); + delete data; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/resource_array_dev.h b/chromium/ppapi/cpp/dev/resource_array_dev.h new file mode 100644 index 00000000000..f9daf5f0320 --- /dev/null +++ b/chromium/ppapi/cpp/dev/resource_array_dev.h @@ -0,0 +1,71 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_RESOURCE_ARRAY_DEV_H_ +#define PPAPI_CPP_DEV_RESOURCE_ARRAY_DEV_H_ + +#include "ppapi/c/pp_array_output.h" +#include "ppapi/c/pp_completion_callback.h" +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class InstanceHandle; + +class ResourceArray_Dev : public Resource { + public: + // Heap-allocated data passed to ArrayOutputCallbackConverter(). Please see + // the comment of ArrayOutputCallbackConverter() for more details. + struct ArrayOutputCallbackData { + ArrayOutputCallbackData(const PP_ArrayOutput& array_output, + const PP_CompletionCallback& callback) + : resource_array_output(0), + output(array_output), + original_callback(callback) { + } + + PP_Resource resource_array_output; + PP_ArrayOutput output; + PP_CompletionCallback original_callback; + }; + + ResourceArray_Dev(); + + ResourceArray_Dev(PassRef, PP_Resource resource); + + ResourceArray_Dev(const ResourceArray_Dev& other); + + ResourceArray_Dev(const InstanceHandle& instance, + const PP_Resource elements[], + uint32_t size); + + virtual ~ResourceArray_Dev(); + + ResourceArray_Dev& operator=(const ResourceArray_Dev& other); + + uint32_t size() const; + + PP_Resource operator[](uint32_t index) const; + + // This is an adapter for backward compatibility. It works with those APIs + // which take a PPB_ResourceArray_Dev resource as output parameter, and + // returns results using PP_ArrayOutput. For example: + // + // ResourceArray_Dev::ArrayOutputCallbackData* data = + // new ResourceArray_Dev::ArrayOutputCallbackData( + // pp_array_output, callback); + // ppb_foo->Bar( + // foo_resource, &data->resource_array_output, + // PP_MakeCompletionCallback( + // &ResourceArray_Dev::ArrayOutputCallbackConverter, data)); + // + // It takes a heap-allocated ArrayOutputCallbackData struct passed as the user + // data, and deletes it when the call completes. + static void ArrayOutputCallbackConverter(void* user_data, int32_t result); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_RESOURCE_ARRAY_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/scriptable_object_deprecated.cc b/chromium/ppapi/cpp/dev/scriptable_object_deprecated.cc new file mode 100644 index 00000000000..1b701cb6651 --- /dev/null +++ b/chromium/ppapi/cpp/dev/scriptable_object_deprecated.cc @@ -0,0 +1,192 @@ +// Copyright (c) 2011 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 "ppapi/cpp/dev/scriptable_object_deprecated.h" +#include "ppapi/c/dev/ppb_memory_dev.h" +#include "ppapi/c/dev/ppp_class_deprecated.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace deprecated { + +namespace { + +// Allows converting an output param of a Var to an output param of a PP_Var +// for exceptions. The object is only copied if it is not void, which we +// take to mean an exception occurred. +class ExceptionConverter { + public: + ExceptionConverter(PP_Var* out) : out_(out) { + } + ~ExceptionConverter() { + if (!exception_.is_undefined()) + *out_ = exception_.Detach(); + } + + Var* Get() { return &exception_; } + + private: + PP_Var* out_; + Var exception_; +}; + +// Used internally to convert a C-style array of PP_Var to a vector of Var. +void ArgListToVector(uint32_t argc, PP_Var* argv, std::vector<Var>* output) { + output->reserve(argc); + for (size_t i = 0; i < argc; i++) + output->push_back(Var(Var::DontManage(), argv[i])); +} + +bool HasProperty(void* object, PP_Var name, PP_Var* exception) { + ExceptionConverter e(exception); + return static_cast<ScriptableObject*>(object)->HasProperty( + Var(Var::DontManage(), name), e.Get()); +} + +bool HasMethod(void* object, PP_Var name, PP_Var* exception) { + ExceptionConverter e(exception); + return static_cast<ScriptableObject*>(object)->HasMethod( + Var(Var::DontManage(), name), e.Get()); +} + +PP_Var GetProperty(void* object, + PP_Var name, + PP_Var* exception) { + ExceptionConverter e(exception); + return static_cast<ScriptableObject*>(object)->GetProperty( + Var(Var::DontManage(), name), e.Get()).Detach(); +} + +void GetAllPropertyNames(void* object, + uint32_t* property_count, + PP_Var** properties, + PP_Var* exception) { + ExceptionConverter e(exception); + std::vector<Var> props; + static_cast<ScriptableObject*>(object)->GetAllPropertyNames(&props, e.Get()); + if (props.empty()) + return; + *property_count = static_cast<uint32_t>(props.size()); + + const PPB_Memory_Dev* memory_if = static_cast<const PPB_Memory_Dev*>( + pp::Module::Get()->GetBrowserInterface(PPB_MEMORY_DEV_INTERFACE)); + *properties = static_cast<PP_Var*>( + memory_if->MemAlloc(sizeof(PP_Var) * props.size())); + + for (size_t i = 0; i < props.size(); ++i) + (*properties)[i] = props[i].Detach(); +} + +void SetProperty(void* object, + PP_Var name, + PP_Var value, + PP_Var* exception) { + ExceptionConverter e(exception); + static_cast<ScriptableObject*>(object)->SetProperty( + Var(Var::DontManage(), name), Var(Var::DontManage(), value), e.Get()); +} + +void RemoveProperty(void* object, + PP_Var name, + PP_Var* exception) { + ExceptionConverter e(exception); + static_cast<ScriptableObject*>(object)->RemoveProperty( + Var(Var::DontManage(), name), e.Get()); +} + +PP_Var Call(void* object, + PP_Var method_name, + uint32_t argc, + PP_Var* argv, + PP_Var* exception) { + ExceptionConverter e(exception); + + std::vector<Var> args; + ArgListToVector(argc, argv, &args); + return static_cast<ScriptableObject*>(object)->Call( + Var(Var::DontManage(), method_name), args, e.Get()).Detach(); +} + +PP_Var Construct(void* object, + uint32_t argc, + PP_Var* argv, + PP_Var* exception) { + ExceptionConverter e(exception); + + std::vector<Var> args; + ArgListToVector(argc, argv, &args); + return static_cast<ScriptableObject*>(object)->Construct( + args, e.Get()).Detach(); +} + +void Deallocate(void* object) { + delete static_cast<ScriptableObject*>(object); +} + +PPP_Class_Deprecated plugin_class = { + &HasProperty, + &HasMethod, + &GetProperty, + &GetAllPropertyNames, + &SetProperty, + &RemoveProperty, + &Call, + &Construct, + &Deallocate +}; + +} // namespace + +bool ScriptableObject::HasProperty(const Var& /*name*/, Var* /*exception*/) { + return false; +} + +bool ScriptableObject::HasMethod(const Var& /*name*/, Var* /*exception*/) { + return false; +} + +Var ScriptableObject::GetProperty(const Var& /*name*/, Var* exception) { + *exception = Var("Property does not exist on ScriptableObject"); + return Var(); +} + +void ScriptableObject::GetAllPropertyNames(std::vector<Var>* /*properties*/, + Var* /*exception*/) { +} + +void ScriptableObject::SetProperty(const Var& /*name*/, + const Var& /*value*/, + Var* exception) { + *exception = Var("Property can not be set on ScriptableObject"); +} + +void ScriptableObject::RemoveProperty(const Var& /*name*/, + Var* exception) { + *exception = Var( + "Property does does not exist to be removed in ScriptableObject"); +} + +Var ScriptableObject::Call(const Var& /*method_name*/, + const std::vector<Var>& /*args*/, + Var* exception) { + *exception = Var("Method does not exist to call in ScriptableObject"); + return Var(); +} + +Var ScriptableObject::Construct(const std::vector<Var>& /*args*/, + Var* exception) { + *exception = Var("Construct method does not exist in ScriptableObject"); + return Var(); +} + +// static +const PPP_Class_Deprecated* ScriptableObject::GetClass() { + return &plugin_class; +} + +} // namespace deprecated + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/scriptable_object_deprecated.h b/chromium/ppapi/cpp/dev/scriptable_object_deprecated.h new file mode 100644 index 00000000000..7423d232768 --- /dev/null +++ b/chromium/ppapi/cpp/dev/scriptable_object_deprecated.h @@ -0,0 +1,93 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_SCRIPTABLE_OBJECT_DEPRECATED_H_ +#define PPAPI_CPP_SCRIPTABLE_OBJECT_DEPRECATED_H_ + +#include <vector> + +struct PPP_Class_Deprecated; + +namespace pp { +class Var; +class VarPrivate; +} + +namespace pp { + +namespace deprecated { + +// This class allows you to implement objects accessible by JavaScript. Derive +// from this class and override the virtual functions you support. pp::Var has +// a constructor that takes a pointer to a ScriptableObject for when you want +// to convert your custom object to a var. +// +// Please see the PPB_Core C interface for more information on how to implement +// these functions. These functions are the backend implementation for the +// functions in PPB_Var, which contains further information. +// +// Please see: +// http://code.google.com/p/ppapi/wiki/InterfacingWithJavaScript +// for a general overview of interfacing with JavaScript. +class ScriptableObject { + public: + ScriptableObject() {} + virtual ~ScriptableObject() {} + + // The default implementation returns false. + virtual bool HasProperty(const Var& name, Var* exception); + + // The default implementation returns false. + virtual bool HasMethod(const Var& name, Var* exception); + + // The default implementation sets an exception that the property doesn't + // exist. + virtual Var GetProperty(const Var& name, Var* exception); + + // The default implementation returns no properties. + virtual void GetAllPropertyNames(std::vector<Var>* properties, + Var* exception); + + // The default implementation sets an exception that the property can not be + // set. + virtual void SetProperty(const Var& name, + const Var& value, + Var* exception); + + // The default implementation sets an exception that the method does not + // exist. + virtual void RemoveProperty(const Var& name, + Var* exception); + + // TODO(brettw) need native array access here. + + // method_name is guaranteed to be either a string or an integer. + // + // The default implementation sets an exception that the method does not + // exist. + virtual Var Call(const Var& method_name, + const std::vector<Var>& args, + Var* exception); + + // The default implementation sets an exception that the method does not + // exist. + virtual Var Construct(const std::vector<Var>& args, + Var* exception); + + private: + friend class ::pp::Var; + friend class ::pp::VarPrivate; + static const PPP_Class_Deprecated* GetClass(); + + // Unimplemented, copy and assignment is not allowed. + ScriptableObject(const ScriptableObject& other); + ScriptableObject& operator=(const ScriptableObject& other); +}; + +} // namespace deprecated + +} // namespace pp + +#endif // PPAPI_CPP_SCRIPTABLE_OBJECT_DEPRECATED_H_ + diff --git a/chromium/ppapi/cpp/dev/scrollbar_dev.cc b/chromium/ppapi/cpp/dev/scrollbar_dev.cc new file mode 100644 index 00000000000..26eb9ef0b84 --- /dev/null +++ b/chromium/ppapi/cpp/dev/scrollbar_dev.cc @@ -0,0 +1,87 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <vector> + +#include "ppapi/cpp/dev/scrollbar_dev.h" + +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/rect.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Scrollbar_Dev>() { + return PPB_SCROLLBAR_DEV_INTERFACE; +} + +} // namespace + +Scrollbar_Dev::Scrollbar_Dev(PP_Resource resource) : Widget_Dev(resource) { +} + +Scrollbar_Dev::Scrollbar_Dev(const InstanceHandle& instance, bool vertical) { + if (!has_interface<PPB_Scrollbar_Dev>()) + return; + PassRefFromConstructor(get_interface<PPB_Scrollbar_Dev>()->Create( + instance.pp_instance(), PP_FromBool(vertical))); +} + +Scrollbar_Dev::Scrollbar_Dev(const Scrollbar_Dev& other) + : Widget_Dev(other) { +} + +uint32_t Scrollbar_Dev::GetThickness() { + if (!has_interface<PPB_Scrollbar_Dev>()) + return 0; + return get_interface<PPB_Scrollbar_Dev>()->GetThickness(pp_resource()); +} + +bool Scrollbar_Dev::IsOverlay() { + if (!has_interface<PPB_Scrollbar_Dev>()) + return false; + return + PP_ToBool(get_interface<PPB_Scrollbar_Dev>()->IsOverlay(pp_resource())); +} + +uint32_t Scrollbar_Dev::GetValue() { + if (!has_interface<PPB_Scrollbar_Dev>()) + return 0; + return get_interface<PPB_Scrollbar_Dev>()->GetValue(pp_resource()); +} + +void Scrollbar_Dev::SetValue(uint32_t value) { + if (has_interface<PPB_Scrollbar_Dev>()) + get_interface<PPB_Scrollbar_Dev>()->SetValue(pp_resource(), value); +} + +void Scrollbar_Dev::SetDocumentSize(uint32_t size) { + if (has_interface<PPB_Scrollbar_Dev>()) + get_interface<PPB_Scrollbar_Dev>()->SetDocumentSize(pp_resource(), size); +} + +void Scrollbar_Dev::SetTickMarks(const Rect* tick_marks, uint32_t count) { + if (!has_interface<PPB_Scrollbar_Dev>()) + return; + + std::vector<PP_Rect> temp; + temp.resize(count); + for (uint32_t i = 0; i < count; ++i) + temp[i] = tick_marks[i]; + + get_interface<PPB_Scrollbar_Dev>()->SetTickMarks( + pp_resource(), count ? &temp[0] : NULL, count); +} + +void Scrollbar_Dev::ScrollBy(PP_ScrollBy_Dev unit, int32_t multiplier) { + if (has_interface<PPB_Scrollbar_Dev>()) + get_interface<PPB_Scrollbar_Dev>()->ScrollBy(pp_resource(), + unit, + multiplier); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/scrollbar_dev.h b/chromium/ppapi/cpp/dev/scrollbar_dev.h new file mode 100644 index 00000000000..fabbbd7f471 --- /dev/null +++ b/chromium/ppapi/cpp/dev/scrollbar_dev.h @@ -0,0 +1,39 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_SCROLLBAR_DEV_H_ +#define PPAPI_CPP_DEV_SCROLLBAR_DEV_H_ + +#include "ppapi/c/dev/ppb_scrollbar_dev.h" +#include "ppapi/cpp/dev/widget_dev.h" + +namespace pp { + +class InstanceHandle; + +// This class allows a plugin to use the browser's scrollbar widget. +class Scrollbar_Dev : public Widget_Dev { + public: + // Creates an is_null() Scrollbar object. + Scrollbar_Dev() {} + + explicit Scrollbar_Dev(PP_Resource resource); + Scrollbar_Dev(const InstanceHandle& instance, bool vertical); + Scrollbar_Dev(const Scrollbar_Dev& other); + + Scrollbar_Dev& operator=(const Scrollbar_Dev& other); + + // PPB_Scrollbar methods: + uint32_t GetThickness(); + bool IsOverlay(); + uint32_t GetValue(); + void SetValue(uint32_t value); + void SetDocumentSize(uint32_t size); + void SetTickMarks(const Rect* tick_marks, uint32_t count); + void ScrollBy(PP_ScrollBy_Dev unit, int32_t multiplier); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_SCROLLBAR_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/selection_dev.cc b/chromium/ppapi/cpp/dev/selection_dev.cc new file mode 100644 index 00000000000..7e1284bb66f --- /dev/null +++ b/chromium/ppapi/cpp/dev/selection_dev.cc @@ -0,0 +1,44 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/selection_dev.h" + +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +static const char kPPPSelectionInterface[] = PPP_SELECTION_DEV_INTERFACE; + +PP_Var GetSelectedText(PP_Instance instance, PP_Bool html) { + void* object = + pp::Instance::GetPerInstanceObject(instance, kPPPSelectionInterface); + if (!object) + return Var().Detach(); + return static_cast<Selection_Dev*>(object)-> + GetSelectedText(PP_ToBool(html)).Detach(); +} + +const PPP_Selection_Dev ppp_selection = { + &GetSelectedText +}; + +} // namespace + +Selection_Dev::Selection_Dev(Instance* instance) + : associated_instance_(instance) { + Module::Get()->AddPluginInterface(kPPPSelectionInterface, &ppp_selection); + instance->AddPerInstanceObject(kPPPSelectionInterface, this); +} + +Selection_Dev::~Selection_Dev() { + Instance::RemovePerInstanceObject(associated_instance_, + kPPPSelectionInterface, this); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/selection_dev.h b/chromium/ppapi/cpp/dev/selection_dev.h new file mode 100644 index 00000000000..629d3610974 --- /dev/null +++ b/chromium/ppapi/cpp/dev/selection_dev.h @@ -0,0 +1,52 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_SELECTION_DEV_H_ +#define PPAPI_CPP_DEV_SELECTION_DEV_H_ + +#include "ppapi/c/dev/ppp_selection_dev.h" +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +class Var; + +// This class allows you to associate the PPP_Selection_Dev C-based interface +// with an object. It registers as the global handler for handling the +// PPP_Selection_Dev interface that the browser calls. +// +// You would typically use this either via inheritance on your instance: +// class MyInstance : public pp::Instance, public pp::Selection_Dev { +// class MyInstance() : pp::Selection_Dev(this) { +// } +// ... +// }; +// +// or by composition: +// class MySelection : public pp::Selection_Dev { +// ... +// }; +// +// class MyInstance : public pp::Instance { +// MyInstance() : selection_(this) { +// } +// +// MySelection selection_; +// }; +class Selection_Dev { + public: + explicit Selection_Dev(Instance* instance); + virtual ~Selection_Dev(); + + // PPP_Selection_Dev functions exposed as virtual functions for you to + // override. + virtual Var GetSelectedText(bool html) = 0; + + private: + InstanceHandle associated_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_SELECTION_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/text_input_dev.cc b/chromium/ppapi/cpp/dev/text_input_dev.cc new file mode 100644 index 00000000000..b0fff8a413f --- /dev/null +++ b/chromium/ppapi/cpp/dev/text_input_dev.cc @@ -0,0 +1,108 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/text_input_dev.h" + +#include "ppapi/c/dev/ppp_text_input_dev.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/rect.h" + +namespace pp { + +namespace { + +static const char kPPPTextInputInterface[] = PPP_TEXTINPUT_DEV_INTERFACE; + +void RequestSurroundingText(PP_Instance instance, + uint32_t desired_number_of_characters) { + void* object = Instance::GetPerInstanceObject(instance, + kPPPTextInputInterface); + if (!object) + return; + static_cast<TextInput_Dev*>(object)->RequestSurroundingText( + desired_number_of_characters); +} + +const PPP_TextInput_Dev ppp_text_input = { + &RequestSurroundingText +}; + +template <> const char* interface_name<PPB_TextInput_Dev_0_2>() { + return PPB_TEXTINPUT_DEV_INTERFACE_0_2; +} + +template <> const char* interface_name<PPB_TextInput_Dev_0_1>() { + return PPB_TEXTINPUT_DEV_INTERFACE_0_1; +} + +} // namespace + + +TextInput_Dev::TextInput_Dev(Instance* instance) + : instance_(instance) { + Module::Get()->AddPluginInterface(kPPPTextInputInterface, + &ppp_text_input); + instance->AddPerInstanceObject(kPPPTextInputInterface, this); +} + +TextInput_Dev::~TextInput_Dev() { + Instance::RemovePerInstanceObject(instance_, kPPPTextInputInterface, this); +} + +void TextInput_Dev::RequestSurroundingText(uint32_t) { + // Default implementation. Send a null range. + UpdateSurroundingText(std::string(), 0, 0); +} + +void TextInput_Dev::SetTextInputType(PP_TextInput_Type_Dev type) { + if (has_interface<PPB_TextInput_Dev_0_2>()) { + get_interface<PPB_TextInput_Dev_0_2>()->SetTextInputType( + instance_.pp_instance(), type); + } else if (has_interface<PPB_TextInput_Dev_0_1>()) { + get_interface<PPB_TextInput_Dev_0_1>()->SetTextInputType( + instance_.pp_instance(), type); + } +} + +void TextInput_Dev::UpdateCaretPosition(const Rect& caret, + const Rect& bounding_box) { + if (has_interface<PPB_TextInput_Dev_0_2>()) { + get_interface<PPB_TextInput_Dev_0_2>()->UpdateCaretPosition( + instance_.pp_instance(), &caret.pp_rect(), &bounding_box.pp_rect()); + } else if (has_interface<PPB_TextInput_Dev_0_1>()) { + get_interface<PPB_TextInput_Dev_0_1>()->UpdateCaretPosition( + instance_.pp_instance(), &caret.pp_rect(), &bounding_box.pp_rect()); + } +} + +void TextInput_Dev::CancelCompositionText() { + if (has_interface<PPB_TextInput_Dev_0_2>()) { + get_interface<PPB_TextInput_Dev_0_2>()->CancelCompositionText( + instance_.pp_instance()); + } else if (has_interface<PPB_TextInput_Dev_0_1>()) { + get_interface<PPB_TextInput_Dev_0_1>()->CancelCompositionText( + instance_.pp_instance()); + } +} + +void TextInput_Dev::SelectionChanged() { + if (has_interface<PPB_TextInput_Dev_0_2>()) { + get_interface<PPB_TextInput_Dev_0_2>()->SelectionChanged( + instance_.pp_instance()); + } +} + +void TextInput_Dev::UpdateSurroundingText(const std::string& text, + uint32_t caret, + uint32_t anchor) { + if (has_interface<PPB_TextInput_Dev_0_2>()) { + get_interface<PPB_TextInput_Dev_0_2>()->UpdateSurroundingText( + instance_.pp_instance(), text.c_str(), caret, anchor); + } +} + + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/text_input_dev.h b/chromium/ppapi/cpp/dev/text_input_dev.h new file mode 100644 index 00000000000..fca87280467 --- /dev/null +++ b/chromium/ppapi/cpp/dev/text_input_dev.h @@ -0,0 +1,61 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_TEXT_INPUT_DEV_H_ +#define PPAPI_CPP_DEV_TEXT_INPUT_DEV_H_ + +#include <string> + +#include "ppapi/c/dev/ppb_text_input_dev.h" +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +class Rect; +class Instance; + +// This class allows you to associate the PPP_TextInput_Dev and +// PPB_TextInput_Dev C-based interfaces with an object. It associates itself +// with the given instance, and registers as the global handler for handling the +// PPP_TextInput_Dev interface that the browser calls. +// +// You would typically use this either via inheritance on your instance: +// class MyInstance : public pp::Instance, public pp::TextInput_Dev { +// MyInstance() : pp::TextInput_Dev(this) { +// } +// ... +// }; +// +// or by composition: +// class MyTextInput : public pp::TextInput_Dev { +// ... +// }; +// +// class MyInstance : public pp::Instance { +// MyInstance() : text_input_(this) { +// } +// +// MyTextInput text_input_; +// }; +class TextInput_Dev { + public: + explicit TextInput_Dev(Instance* instance); + virtual ~TextInput_Dev(); + + virtual void RequestSurroundingText(uint32_t desired_number_of_characters); + + void SetTextInputType(PP_TextInput_Type_Dev type); + void UpdateCaretPosition(const Rect& caret, const Rect& bounding_box); + void CancelCompositionText(); + void SelectionChanged(); + void UpdateSurroundingText(const std::string& text, + uint32_t caret, uint32_t anchor); + + private: + InstanceHandle instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_TEXT_INPUT_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/truetype_font_dev.cc b/chromium/ppapi/cpp/dev/truetype_font_dev.cc new file mode 100644 index 00000000000..b10348a0c73 --- /dev/null +++ b/chromium/ppapi/cpp/dev/truetype_font_dev.cc @@ -0,0 +1,156 @@ +// Copyright (c) 2013 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 "ppapi/cpp/dev/truetype_font_dev.h" + +#include <string.h> // memcpy + +#include "ppapi/c/dev/ppb_truetype_font_dev.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/ppb_var.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_TrueTypeFont_Dev_0_1>() { + return PPB_TRUETYPEFONT_DEV_INTERFACE_0_1; +} + +} // namespace + +// TrueTypeFontDesc_Dev -------------------------------------------------------- + +TrueTypeFontDesc_Dev::TrueTypeFontDesc_Dev() { + desc_.family = family_.pp_var(); + set_generic_family(PP_TRUETYPEFONTFAMILY_SERIF); + set_style(PP_TRUETYPEFONTSTYLE_NORMAL); + set_weight(PP_TRUETYPEFONTWEIGHT_NORMAL); + set_width(PP_TRUETYPEFONTWIDTH_NORMAL); + set_charset(PP_TRUETYPEFONTCHARSET_DEFAULT); +} + +TrueTypeFontDesc_Dev::TrueTypeFontDesc_Dev( + PassRef, + const PP_TrueTypeFontDesc_Dev& pp_desc) { + desc_ = pp_desc; + set_family(Var(PASS_REF, pp_desc.family)); +} + +TrueTypeFontDesc_Dev::TrueTypeFontDesc_Dev(const TrueTypeFontDesc_Dev& other) { + set_family(other.family()); + set_generic_family(other.generic_family()); + set_style(other.style()); + set_weight(other.weight()); + set_width(other.width()); + set_charset(other.charset()); +} + +TrueTypeFontDesc_Dev::~TrueTypeFontDesc_Dev() { +} + +TrueTypeFontDesc_Dev& TrueTypeFontDesc_Dev::operator=( + const TrueTypeFontDesc_Dev& other) { + if (this == &other) + return *this; + + set_family(other.family()); + set_generic_family(other.generic_family()); + set_style(other.style()); + set_weight(other.weight()); + set_width(other.width()); + set_charset(other.charset()); + + return *this; +} + +// TrueTypeFont_Dev ------------------------------------------------------------ + +TrueTypeFont_Dev::TrueTypeFont_Dev() { +} + +TrueTypeFont_Dev::TrueTypeFont_Dev(const InstanceHandle& instance, + const TrueTypeFontDesc_Dev& desc) { + if (!has_interface<PPB_TrueTypeFont_Dev_0_1>()) + return; + PassRefFromConstructor(get_interface<PPB_TrueTypeFont_Dev_0_1>()->Create( + instance.pp_instance(), &desc.pp_desc())); +} + +TrueTypeFont_Dev::TrueTypeFont_Dev(const TrueTypeFont_Dev& other) + : Resource(other) { +} + +TrueTypeFont_Dev::TrueTypeFont_Dev(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +// static +int32_t TrueTypeFont_Dev::GetFontFamilies( + const InstanceHandle& instance, + const CompletionCallbackWithOutput<std::vector<Var> >& cc) { + if (has_interface<PPB_TrueTypeFont_Dev_0_1>()) { + return get_interface<PPB_TrueTypeFont_Dev_0_1>()->GetFontFamilies( + instance.pp_instance(), + cc.output(), cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +// static +int32_t TrueTypeFont_Dev::GetFontsInFamily( + const InstanceHandle& instance, + const Var& family, + const CompletionCallbackWithOutput<std::vector<TrueTypeFontDesc_Dev> >& cc) + { + if (has_interface<PPB_TrueTypeFont_Dev_0_1>()) { + return get_interface<PPB_TrueTypeFont_Dev_0_1>()->GetFontsInFamily( + instance.pp_instance(), + family.pp_var(), + cc.output(), cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t TrueTypeFont_Dev::Describe( + const CompletionCallbackWithOutput<TrueTypeFontDesc_Dev>& cc) { + if (has_interface<PPB_TrueTypeFont_Dev_0_1>()) { + int32_t result = + get_interface<PPB_TrueTypeFont_Dev_0_1>()->Describe( + pp_resource(), cc.output(), cc.pp_completion_callback()); + return result; + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t TrueTypeFont_Dev::GetTableTags( + const CompletionCallbackWithOutput<std::vector<uint32_t> >& cc) { + if (has_interface<PPB_TrueTypeFont_Dev_0_1>()) { + return get_interface<PPB_TrueTypeFont_Dev_0_1>()->GetTableTags( + pp_resource(), + cc.output(), cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t TrueTypeFont_Dev::GetTable( + uint32_t table, + int32_t offset, + int32_t max_data_length, + const CompletionCallbackWithOutput<std::vector<char> >& cc) { + if (has_interface<PPB_TrueTypeFont_Dev_0_1>()) { + return get_interface<PPB_TrueTypeFont_Dev_0_1>()->GetTable( + pp_resource(), + table, offset, max_data_length, + cc.output(), cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/truetype_font_dev.h b/chromium/ppapi/cpp/dev/truetype_font_dev.h new file mode 100644 index 00000000000..bd554f7cfaa --- /dev/null +++ b/chromium/ppapi/cpp/dev/truetype_font_dev.h @@ -0,0 +1,272 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_TRUETYPE_FONT_H_ +#define PPAPI_CPP_TRUETYPE_FONT_H_ + +#include "ppapi/c/dev/ppb_truetype_font_dev.h" +#include "ppapi/c/pp_time.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the API to create a TrueType font object. + +namespace pp { + +class InstanceHandle; + +// TrueTypeFontDesc_Dev -------------------------------------------------------- + +/// The <code>TrueTypeFontDesc_Dev</code> class represents a TrueType font +/// descriptor, used to Create and Describe fonts. +class TrueTypeFontDesc_Dev { + public: + /// Default constructor for creating a <code>TrueTypeFontDesc_Dev</code> + /// object. + TrueTypeFontDesc_Dev(); + + /// Constructor that takes an existing <code>PP_TrueTypeFontDesc_Dev</code> + /// structure. The 'family' PP_Var field in the structure will be managed by + /// this instance. + TrueTypeFontDesc_Dev(PassRef, const PP_TrueTypeFontDesc_Dev& pp_desc); + + /// The copy constructor for <code>TrueTypeFontDesc_Dev</code>. + /// + /// @param[in] other A reference to a <code>TrueTypeFontDesc_Dev</code>. + TrueTypeFontDesc_Dev(const TrueTypeFontDesc_Dev& other); + + ~TrueTypeFontDesc_Dev(); + + TrueTypeFontDesc_Dev& operator=(const TrueTypeFontDesc_Dev& other); + + const PP_TrueTypeFontDesc_Dev& pp_desc() const { + return desc_; + } + + Var family() const { + return family_; + } + void set_family(const Var& family) { + family_ = family; + // The assignment above manages the underlying PP_Vars. Copy the new one + // into the wrapped desc struct. + desc_.family = family_.pp_var(); + } + + PP_TrueTypeFontFamily_Dev generic_family() const { + return desc_.generic_family; + } + void set_generic_family(PP_TrueTypeFontFamily_Dev family) { + desc_.generic_family = family; + } + + PP_TrueTypeFontStyle_Dev style() const { return desc_.style; } + void set_style(PP_TrueTypeFontStyle_Dev style) { + desc_.style = style; + } + + PP_TrueTypeFontWeight_Dev weight() const { return desc_.weight; } + void set_weight(PP_TrueTypeFontWeight_Dev weight) { + desc_.weight = weight; + } + + PP_TrueTypeFontWidth_Dev width() const { return desc_.width; } + void set_width(PP_TrueTypeFontWidth_Dev width) { + desc_.width = width; + } + + PP_TrueTypeFontCharset_Dev charset() const { return desc_.charset; } + void set_charset(PP_TrueTypeFontCharset_Dev charset) { + desc_.charset = charset; + } + + private: + pp::Var family_; // This manages the PP_Var embedded in desc_. + PP_TrueTypeFontDesc_Dev desc_; +}; + +// TrueTypeFont_Dev ------------------------------------------------------------ + +/// The <code>TrueTypeFont_Dev</code> class represents a TrueType font resource. +class TrueTypeFont_Dev : public Resource { + public: + /// Default constructor for creating a <code>TrueTypeFont_Dev</code> object. + TrueTypeFont_Dev(); + + /// A constructor used to create a <code>TrueTypeFont_Dev</code> and associate + /// it with the provided <code>Instance</code>. + /// + /// @param[in] instance The instance that owns this resource. + TrueTypeFont_Dev(const InstanceHandle& instance, + const TrueTypeFontDesc_Dev& desc); + + /// The copy constructor for <code>TrueTypeFont_Dev</code>. + /// + /// @param[in] other A reference to a <code>TrueTypeFont_Dev</code>. + TrueTypeFont_Dev(const TrueTypeFont_Dev& other); + + /// A constructor used when you have received a PP_Resource as a return + /// value that has had its reference count incremented for you. + /// + /// @param[in] resource A PP_Resource corresponding to a TrueType font. + TrueTypeFont_Dev(PassRef, PP_Resource resource); + + /// Gets an array of TrueType font family names available on the host. + /// These names can be used to create a font from a specific family. + /// + /// @param[in] instance A <code>InstanceHandle</code> requesting the family + /// names. + /// @param[in] callback A <code>CompletionCallbackWithOutput</code> to be + /// called upon completion of GetFontFamilies. + /// + /// @return If >= 0, the number of family names returned, otherwise an error + /// code from <code>pp_errors.h</code>. + static int32_t GetFontFamilies( + const InstanceHandle& instance, + const CompletionCallbackWithOutput<std::vector<Var> >& callback); + + /// Gets an array of TrueType font descriptors for a given font family. These + /// descriptors can be used to create a font in that family and matching the + /// descriptor attributes. + /// + /// @param[in] instance A <code>PP_Instance</code> requesting the font + /// descriptors. + /// @param[in] family A <code>Var</code> holding a string specifying the font + /// family. + /// @param[in] callback A <code>CompletionCallbackWithOutput</code> to be + /// called upon completion of GetFontsInFamily. + /// + /// @return If >= 0, the number of font descriptors returned, otherwise an + /// error code from <code>pp_errors.h</code>. + static int32_t GetFontsInFamily( + const InstanceHandle& instance, + const Var& family, + const CompletionCallbackWithOutput<std::vector<TrueTypeFontDesc_Dev> >& + callback); + + /// Returns a description of the given font resource. This description may + /// differ from the description passed to Create, reflecting the host's font + /// matching and fallback algorithm. + /// + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion of Describe. + /// + /// @return A return code from <code>pp_errors.h</code>. If an error code is + /// returned, the descriptor will be left unchanged. + int32_t Describe( + const CompletionCallbackWithOutput<TrueTypeFontDesc_Dev>& callback); + + /// Gets an array of identifying tags for each table in the font. + /// These tags can be used to request specific tables using GetTable. + /// + /// @param[in] callback A <code>CompletionCallbackWithOutput</code> to be + /// called upon completion of GetTableTags. + /// + /// @return If >= 0, the number of table tags returned, otherwise an error + /// code from <code>pp_errors.h</code>. + int32_t GetTableTags( + const CompletionCallbackWithOutput<std::vector<uint32_t> >& callback); + + /// Copies the given font table into client memory. + /// + /// @param[in] table A 4 byte value indicating which table to copy. + /// For example, 'glyf' will cause the outline table to be copied into the + /// output array. A zero tag value will cause the entire font to be copied. + /// @param[in] offset The offset into the font table. + /// @param[in] max_data_length The maximum number of bytes to transfer from + /// <code>offset</code>. + /// @param[in] callback A <code>CompletionCallbackWithOutput</code> to be + /// called upon completion of GetTable. + /// + /// @return If >= 0, the table size in bytes, otherwise an error code from + /// <code>pp_errors.h</code>. + int32_t GetTable( + uint32_t table, + int32_t offset, + int32_t max_data_length, + const CompletionCallbackWithOutput<std::vector<char> >& callback); +}; + +namespace internal { + +// A specialization of CallbackOutputTraits to provide the callback system the + // information on how to handle pp::TrueTypeFontDesc_Dev. This converts +// PP_TrueTypeFontDesc_Dev to pp::TrueTypeFontDesc_Dev when passing to the +// plugin, and specifically manages the PP_Var embedded in the desc_ field. +template<> +struct CallbackOutputTraits<TrueTypeFontDesc_Dev> { + typedef PP_TrueTypeFontDesc_Dev* APIArgType; + typedef PP_TrueTypeFontDesc_Dev StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return &t; + } + + static inline TrueTypeFontDesc_Dev StorageToPluginArg(StorageType& t) { + return TrueTypeFontDesc_Dev(PASS_REF, t); + } + + static inline void Initialize(StorageType* t) { + // Use the same defaults as TrueTypeFontDesc_Dev does. + TrueTypeFontDesc_Dev dummy; + *t = dummy.pp_desc(); + } +}; + +class TrueTypeFontDescArrayOutputAdapterWithStorage + : public ArrayOutputAdapter<PP_TrueTypeFontDesc_Dev> { + public: + TrueTypeFontDescArrayOutputAdapterWithStorage() { + set_output(&temp_storage_); + }; + + virtual ~TrueTypeFontDescArrayOutputAdapterWithStorage() { + if (!temp_storage_.empty()) { + // An easy way to release the resource references held by |temp_storage_|. + output(); + } + }; + + std::vector<TrueTypeFontDesc_Dev>& output() { + PP_DCHECK(output_storage_.empty()); + typedef std::vector<PP_TrueTypeFontDesc_Dev> Entries; + for (Entries::iterator it = temp_storage_.begin(); + it != temp_storage_.end(); ++it) + output_storage_.push_back(TrueTypeFontDesc_Dev(PASS_REF, *it)); + temp_storage_.clear(); + return output_storage_; + } + + private: + std::vector<PP_TrueTypeFontDesc_Dev> temp_storage_; + std::vector<TrueTypeFontDesc_Dev> output_storage_; +}; + +// A specialization of CallbackOutputTraits to provide the callback system the +// information on how to handle vectors of TrueTypeFontDesc_Dev. This converts +// PP_TrueTypeFontDesc_Dev to TrueTypeFontDesc_Dev when passing to the plugin. +template<> +struct CallbackOutputTraits< std::vector<TrueTypeFontDesc_Dev> > { + typedef PP_ArrayOutput APIArgType; + typedef TrueTypeFontDescArrayOutputAdapterWithStorage StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return t.pp_array_output(); + } + + static inline std::vector<TrueTypeFontDesc_Dev>& StorageToPluginArg( + StorageType& t) { + return t.output(); + } + + static inline void Initialize(StorageType* /* t */) {} +}; + +} // namespace internal + +} // namespace pp + +#endif // PPAPI_CPP_TRUETYPE_FONT_H_ diff --git a/chromium/ppapi/cpp/dev/url_util_dev.cc b/chromium/ppapi/cpp/dev/url_util_dev.cc new file mode 100644 index 00000000000..0353883265f --- /dev/null +++ b/chromium/ppapi/cpp/dev/url_util_dev.cc @@ -0,0 +1,85 @@ +// Copyright (c) 2011 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 "ppapi/cpp/dev/url_util_dev.h" + +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" + +namespace pp { + +// static +const URLUtil_Dev* URLUtil_Dev::Get() { + static bool tried_to_init = false; + static URLUtil_Dev util; + + if (!tried_to_init) { + tried_to_init = true; + util.interface_ = static_cast<const PPB_URLUtil_Dev*>( + Module::Get()->GetBrowserInterface(PPB_URLUTIL_DEV_INTERFACE)); + } + + if (!util.interface_) + return NULL; + return &util; +} + +Var URLUtil_Dev::Canonicalize(const Var& url, + PP_URLComponents_Dev* components) const { + return Var(PASS_REF, interface_->Canonicalize(url.pp_var(), components)); +} + +Var URLUtil_Dev::ResolveRelativeToURL(const Var& base_url, + const Var& relative_string, + PP_URLComponents_Dev* components) const { + return Var(PASS_REF, + interface_->ResolveRelativeToURL(base_url.pp_var(), + relative_string.pp_var(), + components)); +} + +Var URLUtil_Dev::ResolveRelativeToDocument( + const InstanceHandle& instance, + const Var& relative_string, + PP_URLComponents_Dev* components) const { + return Var(PASS_REF, + interface_->ResolveRelativeToDocument(instance.pp_instance(), + relative_string.pp_var(), + components)); +} + +bool URLUtil_Dev::IsSameSecurityOrigin(const Var& url_a, + const Var& url_b) const { + return PP_ToBool(interface_->IsSameSecurityOrigin(url_a.pp_var(), + url_b.pp_var())); +} + +bool URLUtil_Dev::DocumentCanRequest(const InstanceHandle& instance, + const Var& url) const { + return PP_ToBool(interface_->DocumentCanRequest(instance.pp_instance(), + url.pp_var())); +} + +bool URLUtil_Dev::DocumentCanAccessDocument( + const InstanceHandle& active, + const InstanceHandle& target) const { + return PP_ToBool( + interface_->DocumentCanAccessDocument(active.pp_instance(), + target.pp_instance())); +} + +Var URLUtil_Dev::GetDocumentURL(const InstanceHandle& instance, + PP_URLComponents_Dev* components) const { + return Var(PASS_REF, + interface_->GetDocumentURL(instance.pp_instance(), components)); +} + +Var URLUtil_Dev::GetPluginInstanceURL(const InstanceHandle& instance, + PP_URLComponents_Dev* components) const { + return Var(PASS_REF, + interface_->GetPluginInstanceURL(instance.pp_instance(), + components)); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/url_util_dev.h b/chromium/ppapi/cpp/dev/url_util_dev.h new file mode 100644 index 00000000000..6c0ecf56b12 --- /dev/null +++ b/chromium/ppapi/cpp/dev/url_util_dev.h @@ -0,0 +1,57 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_DEV_URL_UTIL_DEV_H_ +#define PPAPI_CPP_DEV_URL_UTIL_DEV_H_ + +#include "ppapi/c/dev/ppb_url_util_dev.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +class InstanceHandle; + +// Simple wrapper around the PPB_URLUtil interface. +class URLUtil_Dev { + public: + // This class is just a collection of random functions that aren't + // particularly attached to anything. So this getter returns a cached + // instance of this interface. This may return NULL if the browser doesn't + // support the URLUtil interface. Since this is a singleton, don't delete the + // pointer. + static const URLUtil_Dev* Get(); + + Var Canonicalize(const Var& url, + PP_URLComponents_Dev* components = NULL) const; + + Var ResolveRelativeToURL(const Var& base_url, + const Var& relative_string, + PP_URLComponents_Dev* components = NULL) const; + Var ResolveRelativeToDocument(const InstanceHandle& instance, + const Var& relative_string, + PP_URLComponents_Dev* components = NULL) const; + + bool IsSameSecurityOrigin(const Var& url_a, const Var& url_b) const; + bool DocumentCanRequest(const InstanceHandle& instance, const Var& url) const; + bool DocumentCanAccessDocument(const InstanceHandle& active, + const InstanceHandle& target) const; + Var GetDocumentURL(const InstanceHandle& instance, + PP_URLComponents_Dev* components = NULL) const; + + Var GetPluginInstanceURL(const InstanceHandle& instance, + PP_URLComponents_Dev* components = NULL) const; + + private: + URLUtil_Dev() : interface_(NULL) {} + + // Copy and assignment are disallowed. + URLUtil_Dev(const URLUtil_Dev& other); + URLUtil_Dev& operator=(const URLUtil_Dev& other); + + const PPB_URLUtil_Dev* interface_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_URL_UTIL_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/video_capture_client_dev.cc b/chromium/ppapi/cpp/dev/video_capture_client_dev.cc new file mode 100644 index 00000000000..439c0afb0dc --- /dev/null +++ b/chromium/ppapi/cpp/dev/video_capture_client_dev.cc @@ -0,0 +1,80 @@ +// Copyright (c) 2011 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 "ppapi/cpp/dev/video_capture_client_dev.h" + +#include "ppapi/c/dev/ppp_video_capture_dev.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" + +namespace pp { + +namespace { + +const char kPPPVideoCaptureInterface[] = PPP_VIDEO_CAPTURE_DEV_INTERFACE; + +void OnDeviceInfo(PP_Instance instance, + PP_Resource resource, + const struct PP_VideoCaptureDeviceInfo_Dev* info, + uint32_t buffer_count, + const PP_Resource buffers[]) { + VideoCaptureClient_Dev* client = static_cast<VideoCaptureClient_Dev*>( + Instance::GetPerInstanceObject(instance, kPPPVideoCaptureInterface)); + if (!client) + return; + + std::vector<Buffer_Dev> buffer_list; + buffer_list.reserve(buffer_count); + for (uint32_t i = 0; i < buffer_count; ++i) + buffer_list.push_back(Buffer_Dev(buffers[i])); + + client->OnDeviceInfo(resource, *info, buffer_list); +} + +void OnStatus(PP_Instance instance, PP_Resource resource, uint32_t status) { + VideoCaptureClient_Dev* client = static_cast<VideoCaptureClient_Dev*>( + Instance::GetPerInstanceObject(instance, kPPPVideoCaptureInterface)); + if (client) + client->OnStatus(resource, status); +} + +void OnError(PP_Instance instance, PP_Resource resource, uint32_t error_code) { + VideoCaptureClient_Dev* client = static_cast<VideoCaptureClient_Dev*>( + Instance::GetPerInstanceObject(instance, kPPPVideoCaptureInterface)); + if (client) + client->OnError(resource, error_code); +} + +void OnBufferReady(PP_Instance instance, + PP_Resource resource, + uint32_t buffer) { + VideoCaptureClient_Dev* client = static_cast<VideoCaptureClient_Dev*>( + Instance::GetPerInstanceObject(instance, kPPPVideoCaptureInterface)); + if (client) + client->OnBufferReady(resource, buffer); +} + +PPP_VideoCapture_Dev ppp_video_capture = { + OnDeviceInfo, + OnStatus, + OnError, + OnBufferReady +}; + +} // namespace + +VideoCaptureClient_Dev::VideoCaptureClient_Dev(Instance* instance) + : instance_(instance) { + Module::Get()->AddPluginInterface(kPPPVideoCaptureInterface, + &ppp_video_capture); + instance->AddPerInstanceObject(kPPPVideoCaptureInterface, this); +} + +VideoCaptureClient_Dev::~VideoCaptureClient_Dev() { + Instance::RemovePerInstanceObject(instance_, + kPPPVideoCaptureInterface, this); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/video_capture_client_dev.h b/chromium/ppapi/cpp/dev/video_capture_client_dev.h new file mode 100644 index 00000000000..85b766e1665 --- /dev/null +++ b/chromium/ppapi/cpp/dev/video_capture_client_dev.h @@ -0,0 +1,37 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_DEV_VIDEO_CAPTURE_CLIENT_DEV_H_ +#define PPAPI_CPP_DEV_VIDEO_CAPTURE_CLIENT_DEV_H_ + +#include <vector> + +#include "ppapi/c/dev/pp_video_capture_dev.h" +#include "ppapi/cpp/dev/buffer_dev.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class Instance; + +class VideoCaptureClient_Dev { + public: + explicit VideoCaptureClient_Dev(Instance* instance); + virtual ~VideoCaptureClient_Dev(); + + virtual void OnDeviceInfo(PP_Resource video_capture, + const PP_VideoCaptureDeviceInfo_Dev& info, + const std::vector<Buffer_Dev>& buffers) = 0; + virtual void OnStatus(PP_Resource video_capture, uint32_t status) = 0; + virtual void OnError(PP_Resource video_capture, uint32_t error) = 0; + virtual void OnBufferReady(PP_Resource video_capture, uint32_t buffer) = 0; + + private: + InstanceHandle instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_VIDEO_CAPTURE_CLIENT_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/video_capture_dev.cc b/chromium/ppapi/cpp/dev/video_capture_dev.cc new file mode 100644 index 00000000000..46fdb5973ca --- /dev/null +++ b/chromium/ppapi/cpp/dev/video_capture_dev.cc @@ -0,0 +1,151 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/video_capture_dev.h" + +#include "ppapi/c/dev/ppb_video_capture_dev.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/dev/resource_array_dev.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_VideoCapture_Dev_0_2>() { + return PPB_VIDEOCAPTURE_DEV_INTERFACE_0_2; +} + +template <> const char* interface_name<PPB_VideoCapture_Dev_0_3>() { + return PPB_VIDEOCAPTURE_DEV_INTERFACE_0_3; +} + +} // namespace + +VideoCapture_Dev::VideoCapture_Dev(const InstanceHandle& instance) { + if (has_interface<PPB_VideoCapture_Dev_0_3>()) { + PassRefFromConstructor(get_interface<PPB_VideoCapture_Dev_0_3>()->Create( + instance.pp_instance())); + } else if (has_interface<PPB_VideoCapture_Dev_0_2>()) { + PassRefFromConstructor(get_interface<PPB_VideoCapture_Dev_0_2>()->Create( + instance.pp_instance())); + } +} + +VideoCapture_Dev::VideoCapture_Dev(PP_Resource resource) + : Resource(resource) { +} + +VideoCapture_Dev::~VideoCapture_Dev() { +} + +// static +bool VideoCapture_Dev::IsAvailable() { + return has_interface<PPB_VideoCapture_Dev_0_3>() || + has_interface<PPB_VideoCapture_Dev_0_2>(); +} + +int32_t VideoCapture_Dev::EnumerateDevices( + const CompletionCallbackWithOutput<std::vector<DeviceRef_Dev> >& callback) { + if (has_interface<PPB_VideoCapture_Dev_0_3>()) { + return get_interface<PPB_VideoCapture_Dev_0_3>()->EnumerateDevices( + pp_resource(), callback.output(), callback.pp_completion_callback()); + } + + if (has_interface<PPB_VideoCapture_Dev_0_2>()) { + if (!callback.pp_completion_callback().func) + return callback.MayForce(PP_ERROR_BLOCKS_MAIN_THREAD); + + // ArrayOutputCallbackConverter is responsible to delete it. + ResourceArray_Dev::ArrayOutputCallbackData* data = + new ResourceArray_Dev::ArrayOutputCallbackData( + callback.output(), callback.pp_completion_callback()); + return get_interface<PPB_VideoCapture_Dev_0_2>()->EnumerateDevices( + pp_resource(), &data->resource_array_output, + PP_MakeCompletionCallback( + &ResourceArray_Dev::ArrayOutputCallbackConverter, data)); + } + + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t VideoCapture_Dev::MonitorDeviceChange( + PP_MonitorDeviceChangeCallback callback, + void* user_data) { + if (has_interface<PPB_VideoCapture_Dev_0_3>()) { + return get_interface<PPB_VideoCapture_Dev_0_3>()->MonitorDeviceChange( + pp_resource(), callback, user_data); + } + + return PP_ERROR_NOINTERFACE; +} + +int32_t VideoCapture_Dev::Open( + const DeviceRef_Dev& device_ref, + const PP_VideoCaptureDeviceInfo_Dev& requested_info, + uint32_t buffer_count, + const CompletionCallback& callback) { + if (has_interface<PPB_VideoCapture_Dev_0_3>()) { + return get_interface<PPB_VideoCapture_Dev_0_3>()->Open( + pp_resource(), device_ref.pp_resource(), &requested_info, buffer_count, + callback.pp_completion_callback()); + } + if (has_interface<PPB_VideoCapture_Dev_0_2>()) { + return get_interface<PPB_VideoCapture_Dev_0_2>()->Open( + pp_resource(), device_ref.pp_resource(), &requested_info, buffer_count, + callback.pp_completion_callback()); + } + + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t VideoCapture_Dev::StartCapture() { + if (has_interface<PPB_VideoCapture_Dev_0_3>()) { + return get_interface<PPB_VideoCapture_Dev_0_3>()->StartCapture( + pp_resource()); + } + if (has_interface<PPB_VideoCapture_Dev_0_2>()) { + return get_interface<PPB_VideoCapture_Dev_0_2>()->StartCapture( + pp_resource()); + } + + return PP_ERROR_NOINTERFACE; +} + +int32_t VideoCapture_Dev::ReuseBuffer(uint32_t buffer) { + if (has_interface<PPB_VideoCapture_Dev_0_3>()) { + return get_interface<PPB_VideoCapture_Dev_0_3>()->ReuseBuffer(pp_resource(), + buffer); + } + if (has_interface<PPB_VideoCapture_Dev_0_2>()) { + return get_interface<PPB_VideoCapture_Dev_0_2>()->ReuseBuffer(pp_resource(), + buffer); + } + + return PP_ERROR_NOINTERFACE; +} + +int32_t VideoCapture_Dev::StopCapture() { + if (has_interface<PPB_VideoCapture_Dev_0_3>()) { + return get_interface<PPB_VideoCapture_Dev_0_3>()->StopCapture( + pp_resource()); + } + if (has_interface<PPB_VideoCapture_Dev_0_2>()) { + return get_interface<PPB_VideoCapture_Dev_0_2>()->StopCapture( + pp_resource()); + } + + return PP_ERROR_NOINTERFACE; +} + +void VideoCapture_Dev::Close() { + if (has_interface<PPB_VideoCapture_Dev_0_3>()) { + get_interface<PPB_VideoCapture_Dev_0_3>()->Close(pp_resource()); + } else if (has_interface<PPB_VideoCapture_Dev_0_2>()) { + get_interface<PPB_VideoCapture_Dev_0_2>()->Close(pp_resource()); + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/video_capture_dev.h b/chromium/ppapi/cpp/dev/video_capture_dev.h new file mode 100644 index 00000000000..649254e5b6f --- /dev/null +++ b/chromium/ppapi/cpp/dev/video_capture_dev.h @@ -0,0 +1,46 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_VIDEO_CAPTURE_DEV_H_ +#define PPAPI_CPP_DEV_VIDEO_CAPTURE_DEV_H_ + +#include <vector> + +#include "ppapi/c/dev/pp_video_capture_dev.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/dev/device_ref_dev.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class InstanceHandle; + +class VideoCapture_Dev : public Resource { + public: + explicit VideoCapture_Dev(const InstanceHandle& instance); + VideoCapture_Dev(PP_Resource resource); + + virtual ~VideoCapture_Dev(); + + // Returns true if the required interface is available. + static bool IsAvailable(); + + int32_t EnumerateDevices( + const CompletionCallbackWithOutput<std::vector<DeviceRef_Dev> >& + callback); + int32_t MonitorDeviceChange(PP_MonitorDeviceChangeCallback callback, + void* user_data); + int32_t Open(const DeviceRef_Dev& device_ref, + const PP_VideoCaptureDeviceInfo_Dev& requested_info, + uint32_t buffer_count, + const CompletionCallback& callback); + int32_t StartCapture(); + int32_t ReuseBuffer(uint32_t buffer); + int32_t StopCapture(); + void Close(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_VIDEO_CAPTURE_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/video_decoder_client_dev.cc b/chromium/ppapi/cpp/dev/video_decoder_client_dev.cc new file mode 100644 index 00000000000..10c2619d9c6 --- /dev/null +++ b/chromium/ppapi/cpp/dev/video_decoder_client_dev.cc @@ -0,0 +1,86 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/video_decoder_client_dev.h" + +#include "ppapi/c/dev/ppp_video_decoder_dev.h" +#include "ppapi/cpp/dev/video_decoder_dev.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +const char kPPPVideoDecoderInterface[] = PPP_VIDEODECODER_DEV_INTERFACE; + +// Callback to provide buffers for the decoded output pictures. +void ProvidePictureBuffers(PP_Instance instance, + PP_Resource decoder, + uint32_t req_num_of_bufs, + const PP_Size* dimensions, + uint32_t texture_target) { + void* object = Instance::GetPerInstanceObject(instance, + kPPPVideoDecoderInterface); + if (!object) + return; + static_cast<VideoDecoderClient_Dev*>(object)->ProvidePictureBuffers( + decoder, req_num_of_bufs, *dimensions, texture_target); +} + +void DismissPictureBuffer(PP_Instance instance, + PP_Resource decoder, + int32_t picture_buffer_id) { + void* object = Instance::GetPerInstanceObject(instance, + kPPPVideoDecoderInterface); + if (!object) + return; + static_cast<VideoDecoderClient_Dev*>(object)->DismissPictureBuffer( + decoder, picture_buffer_id); +} + +void PictureReady(PP_Instance instance, + PP_Resource decoder, + const PP_Picture_Dev* picture) { + void* object = Instance::GetPerInstanceObject(instance, + kPPPVideoDecoderInterface); + if (!object) + return; + static_cast<VideoDecoderClient_Dev*>(object)->PictureReady(decoder, *picture); +} + +void NotifyError(PP_Instance instance, + PP_Resource decoder, + PP_VideoDecodeError_Dev error) { + void* object = Instance::GetPerInstanceObject(instance, + kPPPVideoDecoderInterface); + if (!object) + return; + static_cast<VideoDecoderClient_Dev*>(object)->NotifyError(decoder, error); +} + +static PPP_VideoDecoder_Dev videodecoder_interface = { + &ProvidePictureBuffers, + &DismissPictureBuffer, + &PictureReady, + &NotifyError, +}; + +} // namespace + +VideoDecoderClient_Dev::VideoDecoderClient_Dev(Instance* instance) + : associated_instance_(instance) { + Module::Get()->AddPluginInterface(kPPPVideoDecoderInterface, + &videodecoder_interface); + instance->AddPerInstanceObject(kPPPVideoDecoderInterface, this); +} + +VideoDecoderClient_Dev::~VideoDecoderClient_Dev() { + Instance::RemovePerInstanceObject(associated_instance_, + kPPPVideoDecoderInterface, this); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/video_decoder_client_dev.h b/chromium/ppapi/cpp/dev/video_decoder_client_dev.h new file mode 100644 index 00000000000..a6e2bb53fc3 --- /dev/null +++ b/chromium/ppapi/cpp/dev/video_decoder_client_dev.h @@ -0,0 +1,51 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_VIDEO_DECODER_CLIENT_DEV_H_ +#define PPAPI_CPP_DEV_VIDEO_DECODER_CLIENT_DEV_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/dev/pp_video_dev.h" +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +class Instance; +class VideoDecoder_Dev; + +// This class provides a C++ interface for callbacks related to video decoding. +// It is the C++ counterpart to PPP_VideoDecoder_Dev. +// You would normally use multiple inheritance to derive from this class in your +// instance. +class VideoDecoderClient_Dev { + public: + VideoDecoderClient_Dev(Instance* instance); + virtual ~VideoDecoderClient_Dev(); + + // Callback to provide buffers for the decoded output pictures. + virtual void ProvidePictureBuffers(PP_Resource decoder, + uint32_t req_num_of_bufs, + const PP_Size& dimensions, + uint32_t texture_target) = 0; + + // Callback for decoder to deliver unneeded picture buffers back to the + // plugin. + virtual void DismissPictureBuffer(PP_Resource decoder, + int32_t picture_buffer_id) = 0; + + // Callback to deliver decoded pictures ready to be displayed. + virtual void PictureReady(PP_Resource decoder, + const PP_Picture_Dev& picture) = 0; + + // Callback to notify about decoding errors. + virtual void NotifyError(PP_Resource decoder, + PP_VideoDecodeError_Dev error) = 0; + + private: + InstanceHandle associated_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_VIDEO_DECODER_CLIENT_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/video_decoder_dev.cc b/chromium/ppapi/cpp/dev/video_decoder_dev.cc new file mode 100644 index 00000000000..dcc3b5d44a4 --- /dev/null +++ b/chromium/ppapi/cpp/dev/video_decoder_dev.cc @@ -0,0 +1,78 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/video_decoder_dev.h" + +#include "ppapi/c/dev/ppb_video_decoder_dev.h" +#include "ppapi/c/dev/ppp_video_decoder_dev.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/graphics_3d.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_VideoDecoder_Dev>() { + return PPB_VIDEODECODER_DEV_INTERFACE; +} + +} // namespace + +VideoDecoder_Dev::VideoDecoder_Dev(const InstanceHandle& instance, + const Graphics3D& context, + PP_VideoDecoder_Profile profile) { + if (!has_interface<PPB_VideoDecoder_Dev>()) + return; + PassRefFromConstructor(get_interface<PPB_VideoDecoder_Dev>()->Create( + instance.pp_instance(), context.pp_resource(), profile)); +} + +VideoDecoder_Dev::VideoDecoder_Dev(PP_Resource resource) : Resource(resource) { +} + +VideoDecoder_Dev::~VideoDecoder_Dev() { +} + +void VideoDecoder_Dev::AssignPictureBuffers( + const std::vector<PP_PictureBuffer_Dev>& buffers) { + if (!has_interface<PPB_VideoDecoder_Dev>() || !pp_resource()) + return; + get_interface<PPB_VideoDecoder_Dev>()->AssignPictureBuffers( + pp_resource(), buffers.size(), &buffers[0]); +} + +int32_t VideoDecoder_Dev::Decode( + const PP_VideoBitstreamBuffer_Dev& bitstream_buffer, + const CompletionCallback& callback) { + if (!has_interface<PPB_VideoDecoder_Dev>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_VideoDecoder_Dev>()->Decode( + pp_resource(), &bitstream_buffer, callback.pp_completion_callback()); +} + +void VideoDecoder_Dev::ReusePictureBuffer(int32_t picture_buffer_id) { + if (!has_interface<PPB_VideoDecoder_Dev>() || !pp_resource()) + return; + get_interface<PPB_VideoDecoder_Dev>()->ReusePictureBuffer( + pp_resource(), picture_buffer_id); +} + +int32_t VideoDecoder_Dev::Flush(const CompletionCallback& callback) { + if (!has_interface<PPB_VideoDecoder_Dev>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_VideoDecoder_Dev>()->Flush( + pp_resource(), callback.pp_completion_callback()); +} + +int32_t VideoDecoder_Dev::Reset(const CompletionCallback& callback) { + if (!has_interface<PPB_VideoDecoder_Dev>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_VideoDecoder_Dev>()->Reset( + pp_resource(), callback.pp_completion_callback()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/video_decoder_dev.h b/chromium/ppapi/cpp/dev/video_decoder_dev.h new file mode 100644 index 00000000000..fab4fb517d8 --- /dev/null +++ b/chromium/ppapi/cpp/dev/video_decoder_dev.h @@ -0,0 +1,45 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_VIDEO_DECODER_DEV_H_ +#define PPAPI_CPP_DEV_VIDEO_DECODER_DEV_H_ + +#include <vector> + +#include "ppapi/c/dev/pp_video_dev.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/dev/buffer_dev.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class Graphics3D; +class InstanceHandle; + +// C++ wrapper for the Pepper Video Decoder interface. For more detailed +// documentation refer to the C interfaces. +// +// C++ version of the PPB_VideoDecoder_Dev interface. +class VideoDecoder_Dev : public Resource { + public: + // See PPB_VideoDecoder_Dev::Create. + VideoDecoder_Dev(const InstanceHandle& instance, + const Graphics3D& context, + PP_VideoDecoder_Profile profile); + explicit VideoDecoder_Dev(PP_Resource resource); + + virtual ~VideoDecoder_Dev(); + + // PPB_VideoDecoder_Dev implementation. + void AssignPictureBuffers(const std::vector<PP_PictureBuffer_Dev>& buffers); + int32_t Decode(const PP_VideoBitstreamBuffer_Dev& bitstream_buffer, + const CompletionCallback& callback); + void ReusePictureBuffer(int32_t picture_buffer_id); + int32_t Flush(const CompletionCallback& callback); + int32_t Reset(const CompletionCallback& callback); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_VIDEO_DECODER_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/view_dev.cc b/chromium/ppapi/cpp/dev/view_dev.cc new file mode 100644 index 00000000000..473e9b465c2 --- /dev/null +++ b/chromium/ppapi/cpp/dev/view_dev.cc @@ -0,0 +1,32 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/view_dev.h" + +#include "ppapi/c/dev/ppb_view_dev.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_View_Dev>() { + return PPB_VIEW_DEV_INTERFACE; +} + +} // namespace + +float ViewDev::GetDeviceScale() const { + if (!has_interface<PPB_View_Dev>()) + return 1.0f; + return get_interface<PPB_View_Dev>()->GetDeviceScale(pp_resource()); +} + +float ViewDev::GetCSSScale() const { + if (!has_interface<PPB_View_Dev>()) + return 1.0f; + return get_interface<PPB_View_Dev>()->GetCSSScale(pp_resource()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/view_dev.h b/chromium/ppapi/cpp/dev/view_dev.h new file mode 100644 index 00000000000..2c99e48366c --- /dev/null +++ b/chromium/ppapi/cpp/dev/view_dev.h @@ -0,0 +1,44 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_VIEW_DEV_H_ +#define PPAPI_CPP_DEV_VIEW_DEV_H_ + +#include "ppapi/cpp/view.h" + +namespace pp { + +// ViewDev is a version of View that exposes under-development APIs related to +// HiDPI +class ViewDev : public View { + public: + ViewDev() : View() {} + ViewDev(const View& other) : View(other) {} + + virtual ~ViewDev() {} + + /// GetDeviceScale returns the scale factor between device pixels and DIPs + /// (also known as logical pixels or UI pixels on some platforms). This allows + /// the developer to render their contents at device resolution, even as + /// coordinates / sizes are given in DIPs through the API. + /// + /// Note that the coordinate system for Pepper APIs is DIPs. Also note that + /// one DIP might not equal one CSS pixel - when page scale/zoom is in effect. + /// + /// @return A <code>float</code> value representing the number of device + /// pixels per DIP. + float GetDeviceScale() const; + + /// GetCSSScale returns the scale factor between DIPs and CSS pixels. This + /// allows proper scaling between DIPs - as sent via the Pepper API - and CSS + /// pixel coordinates used for Web content. + /// + /// @return A <code>float</code> value representing the number of DIPs per CSS + /// pixel. + float GetCSSScale() const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_VIEW_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/widget_client_dev.cc b/chromium/ppapi/cpp/dev/widget_client_dev.cc new file mode 100644 index 00000000000..731f2922778 --- /dev/null +++ b/chromium/ppapi/cpp/dev/widget_client_dev.cc @@ -0,0 +1,88 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/widget_client_dev.h" + +#include "ppapi/c/dev/ppp_scrollbar_dev.h" +#include "ppapi/c/dev/ppp_widget_dev.h" +#include "ppapi/cpp/dev/scrollbar_dev.h" +#include "ppapi/cpp/dev/widget_dev.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/rect.h" + +namespace pp { + +namespace { + +// PPP_Widget_Dev -------------------------------------------------------------- + +const char kPPPWidgetInterface[] = PPP_WIDGET_DEV_INTERFACE; + +void Widget_Invalidate(PP_Instance instance, + PP_Resource widget_id, + const PP_Rect* dirty_rect) { + void* object = Instance::GetPerInstanceObject(instance, kPPPWidgetInterface); + if (!object) + return; + return static_cast<WidgetClient_Dev*>(object)->InvalidateWidget( + Widget_Dev(widget_id), *dirty_rect); +} + +static PPP_Widget_Dev widget_interface = { + &Widget_Invalidate, +}; + +// PPP_Scrollbar_Dev ----------------------------------------------------------- + +const char kPPPScrollbarInterface[] = PPP_SCROLLBAR_DEV_INTERFACE; + +void Scrollbar_ValueChanged(PP_Instance instance, + PP_Resource scrollbar_id, + uint32_t value) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPScrollbarInterface); + if (!object) + return; + return static_cast<WidgetClient_Dev*>(object)->ScrollbarValueChanged( + Scrollbar_Dev(scrollbar_id), value); +} + +void Scrollbar_OverlayChanged(PP_Instance instance, + PP_Resource scrollbar_id, + PP_Bool overlay) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPScrollbarInterface); + if (!object) + return; + return static_cast<WidgetClient_Dev*>(object)->ScrollbarOverlayChanged( + Scrollbar_Dev(scrollbar_id), PP_ToBool(overlay)); +} + +static PPP_Scrollbar_Dev scrollbar_interface = { + &Scrollbar_ValueChanged, + &Scrollbar_OverlayChanged, +}; + +} // namespace + +WidgetClient_Dev::WidgetClient_Dev(Instance* instance) + : associated_instance_(instance) { + Module::Get()->AddPluginInterface(kPPPWidgetInterface, &widget_interface); + instance->AddPerInstanceObject(kPPPWidgetInterface, this); + Module::Get()->AddPluginInterface(kPPPScrollbarInterface, + &scrollbar_interface); + instance->AddPerInstanceObject(kPPPScrollbarInterface, this); +} + +WidgetClient_Dev::~WidgetClient_Dev() { + Instance::RemovePerInstanceObject(associated_instance_, + kPPPScrollbarInterface, this); + Instance::RemovePerInstanceObject(associated_instance_, + kPPPWidgetInterface, this); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/widget_client_dev.h b/chromium/ppapi/cpp/dev/widget_client_dev.h new file mode 100644 index 00000000000..c638cef66ae --- /dev/null +++ b/chromium/ppapi/cpp/dev/widget_client_dev.h @@ -0,0 +1,52 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_WIDGET_CLIENT_DEV_H_ +#define PPAPI_CPP_DEV_WIDGET_CLIENT_DEV_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +class Instance; +class Rect; +class Scrollbar_Dev; +class Widget_Dev; + +// This class provides a C++ interface for callbacks related to widgets. You +// would normally use multiple inheritance to derive from this class in your +// instance. +class WidgetClient_Dev { + public: + explicit WidgetClient_Dev(Instance* instance); + virtual ~WidgetClient_Dev(); + + /** + * Notification that the given widget should be repainted. This is the + * implementation for PPP_Widget_Dev. + */ + virtual void InvalidateWidget(Widget_Dev widget, const Rect& dirty_rect) = 0; + + /** + * Notification that the given scrollbar should change value. This is the + * implementation for PPP_Scrollbar_Dev. + */ + virtual void ScrollbarValueChanged(Scrollbar_Dev scrollbar, + uint32_t value) = 0; + + /** + * Notification that the given scrollbar's overlay type has changed. This is + * the implementation for PPP_Scrollbar_Dev. + */ + virtual void ScrollbarOverlayChanged(Scrollbar_Dev scrollbar, + bool type) = 0; + + private: + InstanceHandle associated_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_WIDGET_CLIENT_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/widget_dev.cc b/chromium/ppapi/cpp/dev/widget_dev.cc new file mode 100644 index 00000000000..14efe1d6879 --- /dev/null +++ b/chromium/ppapi/cpp/dev/widget_dev.cc @@ -0,0 +1,83 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/widget_dev.h" + +#include "ppapi/c/dev/ppb_widget_dev.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/input_event.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/rect.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Widget_Dev_0_3>() { + return PPB_WIDGET_DEV_INTERFACE_0_3; +} + +template <> const char* interface_name<PPB_Widget_Dev_0_4>() { + return PPB_WIDGET_DEV_INTERFACE_0_4; +} + +} // namespace + +Widget_Dev::Widget_Dev(PP_Resource resource) : Resource(resource) { +} + +Widget_Dev::Widget_Dev(const Widget_Dev& other) : Resource(other) { +} + +bool Widget_Dev::Paint(const Rect& rect, ImageData* image) { + if (has_interface<PPB_Widget_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_Widget_Dev_0_4>()->Paint( + pp_resource(), &rect.pp_rect(), image->pp_resource())); + } else if (has_interface<PPB_Widget_Dev_0_3>()) { + return PP_ToBool(get_interface<PPB_Widget_Dev_0_3>()->Paint( + pp_resource(), &rect.pp_rect(), image->pp_resource())); + } + return false; +} + +bool Widget_Dev::HandleEvent(const InputEvent& event) { + if (has_interface<PPB_Widget_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_Widget_Dev_0_4>()->HandleEvent( + pp_resource(), event.pp_resource())); + } else if (has_interface<PPB_Widget_Dev_0_3>()) { + return PP_ToBool(get_interface<PPB_Widget_Dev_0_3>()->HandleEvent( + pp_resource(), event.pp_resource())); + } + return false; +} + +bool Widget_Dev::GetLocation(Rect* location) { + if (has_interface<PPB_Widget_Dev_0_4>()) { + return PP_ToBool(get_interface<PPB_Widget_Dev_0_4>()->GetLocation( + pp_resource(), &location->pp_rect())); + } else if (has_interface<PPB_Widget_Dev_0_3>()) { + return PP_ToBool(get_interface<PPB_Widget_Dev_0_3>()->GetLocation( + pp_resource(), &location->pp_rect())); + } + return false; +} + +void Widget_Dev::SetLocation(const Rect& location) { + if (has_interface<PPB_Widget_Dev_0_4>()) { + get_interface<PPB_Widget_Dev_0_4>()->SetLocation(pp_resource(), + &location.pp_rect()); + } else if (has_interface<PPB_Widget_Dev_0_3>()) { + get_interface<PPB_Widget_Dev_0_3>()->SetLocation(pp_resource(), + &location.pp_rect()); + } +} + +void Widget_Dev::SetScale(float scale) { + if (has_interface<PPB_Widget_Dev_0_4>()) + get_interface<PPB_Widget_Dev_0_4>()->SetScale(pp_resource(), scale); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/widget_dev.h b/chromium/ppapi/cpp/dev/widget_dev.h new file mode 100644 index 00000000000..ef14c3cf7de --- /dev/null +++ b/chromium/ppapi/cpp/dev/widget_dev.h @@ -0,0 +1,37 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_DEV_WIDGET_DEV_H_ +#define PPAPI_CPP_DEV_WIDGET_DEV_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class ImageData; +class InputEvent; +class Rect; + +// This is the base class for widget elements. As such, it can't be created +// directly. +class Widget_Dev : public Resource { + public: + // Creates an is_null() Widget object. + Widget_Dev() {} + + explicit Widget_Dev(PP_Resource resource); + Widget_Dev(const Widget_Dev& other); + + // PPB_Widget methods: + bool Paint(const Rect& rect, ImageData* image); + bool HandleEvent(const InputEvent& event); + bool GetLocation(Rect* location); + void SetLocation(const Rect& location); + void SetScale(float scale); +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_WIDGET_DEV_H_ diff --git a/chromium/ppapi/cpp/dev/zoom_dev.cc b/chromium/ppapi/cpp/dev/zoom_dev.cc new file mode 100644 index 00000000000..0b19c09935a --- /dev/null +++ b/chromium/ppapi/cpp/dev/zoom_dev.cc @@ -0,0 +1,62 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/dev/zoom_dev.h" + +#include "ppapi/c/dev/ppb_zoom_dev.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +static const char kPPPZoomInterface[] = PPP_ZOOM_DEV_INTERFACE; + +void Zoom(PP_Instance instance, + double factor, + PP_Bool text_only) { + void* object = Instance::GetPerInstanceObject(instance, kPPPZoomInterface); + if (!object) + return; + static_cast<Zoom_Dev*>(object)->Zoom(factor, PP_ToBool(text_only)); +} + +const PPP_Zoom_Dev ppp_zoom = { + &Zoom +}; + +template <> const char* interface_name<PPB_Zoom_Dev>() { + return PPB_ZOOM_DEV_INTERFACE; +} + +} // namespace + +Zoom_Dev::Zoom_Dev(Instance* instance) : associated_instance_(instance) { + Module::Get()->AddPluginInterface(kPPPZoomInterface, &ppp_zoom); + instance->AddPerInstanceObject(kPPPZoomInterface, this); +} + +Zoom_Dev::~Zoom_Dev() { + Instance::RemovePerInstanceObject(associated_instance_, + kPPPZoomInterface, this); +} + +void Zoom_Dev::ZoomChanged(double factor) { + if (has_interface<PPB_Zoom_Dev>()) + get_interface<PPB_Zoom_Dev>()->ZoomChanged( + associated_instance_.pp_instance(), factor); +} + +void Zoom_Dev::ZoomLimitsChanged(double minimum_factor, + double maximium_factor) { + if (!has_interface<PPB_Zoom_Dev>()) + return; + get_interface<PPB_Zoom_Dev>()->ZoomLimitsChanged( + associated_instance_.pp_instance(), minimum_factor, maximium_factor); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/dev/zoom_dev.h b/chromium/ppapi/cpp/dev/zoom_dev.h new file mode 100644 index 00000000000..b63c0195da7 --- /dev/null +++ b/chromium/ppapi/cpp/dev/zoom_dev.h @@ -0,0 +1,59 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_DEV_ZOOM_DEV_H_ +#define PPAPI_CPP_DEV_ZOOM_DEV_H_ + +#include <string> + +#include "ppapi/c/dev/ppp_zoom_dev.h" +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +class Instance; + +// This class allows you to associate the PPP_Zoom_Dev and PPB_Zoom_Dev C-based +// interfaces with an object. It associates itself with the given instance, and +// registers as the global handler for handling the PPP_Zoom_Dev interface that +// the browser calls. +// +// You would typically use this either via inheritance on your instance: +// class MyInstance : public pp::Instance, public pp::Zoom_Dev { +// class MyInstance() : pp::Zoom_Dev(this) { +// } +// ... +// }; +// +// or by composition: +// class MyZoom : public pp::Zoom_Dev { +// ... +// }; +// +// class MyInstance : public pp::Instance { +// MyInstance() : zoom_(this) { +// } +// +// MyZoom zoom_; +// }; +class Zoom_Dev { + public: + explicit Zoom_Dev(Instance* instance); + virtual ~Zoom_Dev(); + + // PPP_Zoom_Dev functions exposed as virtual functions for you to + // override. + virtual void Zoom(double factor, bool text_only) = 0; + + // PPB_Zoom_Def functions for you to call to report new zoom factor. + void ZoomChanged(double factor); + void ZoomLimitsChanged(double minimum_factor, double maximium_factor); + + private: + InstanceHandle associated_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_DEV_ZOOM_DEV_H_ diff --git a/chromium/ppapi/cpp/directory_entry.cc b/chromium/ppapi/cpp/directory_entry.cc new file mode 100644 index 00000000000..c8e2b9db380 --- /dev/null +++ b/chromium/ppapi/cpp/directory_entry.cc @@ -0,0 +1,76 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/directory_entry.h" + +#include <string.h> + +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module.h" + +namespace pp { + +DirectoryEntry::DirectoryEntry() { + memset(&data_, 0, sizeof(data_)); +} + +DirectoryEntry::DirectoryEntry( + PassRef, const PP_DirectoryEntry& data) { + data_.file_ref = data.file_ref; + data_.file_type = data.file_type; +} + +DirectoryEntry::DirectoryEntry(const DirectoryEntry& other) { + data_.file_ref = other.data_.file_ref; + data_.file_type = other.data_.file_type; + if (data_.file_ref) + Module::Get()->core()->AddRefResource(data_.file_ref); +} + +DirectoryEntry::~DirectoryEntry() { + if (data_.file_ref) + Module::Get()->core()->ReleaseResource(data_.file_ref); +} + +DirectoryEntry& DirectoryEntry::operator=( + const DirectoryEntry& other) { + if (data_.file_ref) + Module::Get()->core()->ReleaseResource(data_.file_ref); + data_ = other.data_; + if (data_.file_ref) + Module::Get()->core()->AddRefResource(data_.file_ref); + return *this; +} + +namespace internal { + +DirectoryEntryArrayOutputAdapterWithStorage:: + DirectoryEntryArrayOutputAdapterWithStorage() { + set_output(&temp_storage_); +} + +DirectoryEntryArrayOutputAdapterWithStorage:: + ~DirectoryEntryArrayOutputAdapterWithStorage() { + if (!temp_storage_.empty()) { + // An easy way to release the resource references held by |temp_storage_|. + // A destructor for PP_DirectoryEntry will release them. + output(); + } +} + +std::vector<DirectoryEntry>& + DirectoryEntryArrayOutputAdapterWithStorage::output() { + PP_DCHECK(output_storage_.empty()); + typedef std::vector<PP_DirectoryEntry> Entries; + for (Entries::iterator it = temp_storage_.begin(); + it != temp_storage_.end(); + ++it) { + output_storage_.push_back(DirectoryEntry(PASS_REF, *it)); + } + temp_storage_.clear(); + return output_storage_; +} + +} // namespace internal +} // namespace pp diff --git a/chromium/ppapi/cpp/directory_entry.h b/chromium/ppapi/cpp/directory_entry.h new file mode 100644 index 00000000000..bf3d845411d --- /dev/null +++ b/chromium/ppapi/cpp/directory_entry.h @@ -0,0 +1,129 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_DIRECTORY_ENTRY_H_ +#define PPAPI_CPP_DIRECTORY_ENTRY_H_ + +#include <vector> + +#include "ppapi/c/pp_array_output.h" +#include "ppapi/c/pp_directory_entry.h" +#include "ppapi/cpp/array_output.h" +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/output_traits.h" +#include "ppapi/cpp/pass_ref.h" + +/// @file +/// This file defines the API used to handle a directory entry. + +namespace pp { + +/// The <code>DirectoryEntry</code> class represents information about +/// a directory entry. +class DirectoryEntry { + public: + /// Default constructor for creating an is_null() <code>DirectoryEntry</code> + /// object. + DirectoryEntry(); + + /// A constructor used when you have a <code>PP_DirectoryEntry</code> which + /// contains a <code>FileRef</code> that has already been reference counted + /// as a return value. + /// + /// @param[in] data A <code>PP_DirectoryEntry</code> to be copied. + DirectoryEntry(PassRef, const PP_DirectoryEntry& data); + + /// A copy constructor for <code>DirectoryEntry</code>. This constructor + /// increments a reference count of the <code>FileRef</code> held by this + /// DirectoryEntry. + /// + /// @param[in] other A pointer to a <code>DirectoryEntry</code>. + DirectoryEntry(const DirectoryEntry& other); + + /// A destructor that decrements a reference count of the <code>FileRef</code> + /// held by this <code>DirectoryEntry</code>. + ~DirectoryEntry(); + + /// This function assigns one <code>DirectoryEntry</code> object to this + /// <code>DirectoryEntry</code> object. This function increases the reference + /// count of the <code>FileRef</code> of the other DirectoryEntry while + /// decrementing the reference count of the FileRef of this DirectoryEntry. + /// + /// @param[in] other A pointer to a <code>DirectoryEntry</code>. + /// + /// @return A new <code>DirectoryEntry</code> object. + DirectoryEntry& operator=(const DirectoryEntry& other); + + /// This function determines if this <code>DirectoryEntry</code> is a null + /// value. + /// + /// @return true if this <code>DirectoryEntry</code> is null, otherwise false. + bool is_null() const { return !data_.file_ref; } + + /// This function returns the <code>FileRef</code> held by this + /// <code>DirectoryEntry</code>. + /// + /// @return A <code>FileRef</code> of the file. + FileRef file_ref() const { return FileRef(data_.file_ref); } + + /// This function returns the <code>PP_FileType</code> of the file referenced + /// by this <code>DirectoryEntry</code>. + /// + /// @return A <code>PP_FileType</code> of the file. + PP_FileType file_type() const { return data_.file_type; } + + private: + PP_DirectoryEntry data_; +}; + +namespace internal { + +class DirectoryEntryArrayOutputAdapterWithStorage + : public ArrayOutputAdapter<PP_DirectoryEntry> { + public: + DirectoryEntryArrayOutputAdapterWithStorage(); + virtual ~DirectoryEntryArrayOutputAdapterWithStorage(); + + // Returns the final array of resource objects, converting the + // PP_DirectoryEntry written by the browser to pp::DirectoryEntry + // objects. + // + // This function should only be called once or we would end up converting + // the array more than once, which would mess up the refcounting. + std::vector<DirectoryEntry>& output(); + + private: + // The browser will write the PP_DirectoryEntrys into this array. + std::vector<PP_DirectoryEntry> temp_storage_; + + // When asked for the output, the PP_DirectoryEntrys above will be + // converted to the pp::DirectoryEntrys in this array for passing to the + // calling code. + std::vector<DirectoryEntry> output_storage_; +}; + +// A specialization of CallbackOutputTraits to provide the callback system the +// information on how to handle vectors of pp::DirectoryEntry. This converts +// PP_DirectoryEntry to pp::DirectoryEntry when passing to the plugin. +template <> +struct CallbackOutputTraits< std::vector<DirectoryEntry> > { + typedef PP_ArrayOutput APIArgType; + typedef DirectoryEntryArrayOutputAdapterWithStorage StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return t.pp_array_output(); + } + + static inline std::vector<DirectoryEntry>& StorageToPluginArg( + StorageType& t) { + return t.output(); + } + + static inline void Initialize(StorageType* /* t */) {} +}; + +} // namespace internal +} // namespace pp + +#endif // PPAPI_CPP_DIRECTORY_ENTRY_H_ diff --git a/chromium/ppapi/cpp/documentation/Doxyfile b/chromium/ppapi/cpp/documentation/Doxyfile new file mode 100644 index 00000000000..ac862da1792 --- /dev/null +++ b/chromium/ppapi/cpp/documentation/Doxyfile @@ -0,0 +1,1732 @@ +# Copyright (c) 2012 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# Doxyfile 1.7.4 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer +# a quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify an logo or icon that is +# included in the documentation. The maximum height of the logo should not +# exceed 55 pixels and the maximum width should not exceed 200 pixels. +# Doxygen will copy the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = PepperCPPRefDocs + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = NO + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful if your file system +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given extension. +# Doxygen has a built-in mapping, but you can override or extend it using this +# tag. The format is ext=language, where ext is a file extension, and language +# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, +# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make +# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C +# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions +# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also makes the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate getter +# and setter methods for a property. Setting this option to YES (the default) +# will make doxygen replace the get and set methods by a property in the +# documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and +# unions are shown inside the group in which they are included (e.g. using +# @ingroup) instead of on a separate page (for HTML and Man pages) or +# section (for LaTeX and RTF). + +INLINE_GROUPED_CLASSES = NO + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penalty. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will roughly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols + +SYMBOL_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespaces are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen +# will list include files with double quotes in the documentation +# rather than with sharp brackets. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen +# will sort the (brief and detailed) documentation of class members so that +# constructors and destructors are listed first. If set to NO (the default) +# the constructors will appear in the respective orders defined by +# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. +# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO +# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to +# do proper type resolution of all parameters of a function it will reject a +# match between the prototype and the implementation of a member function even +# if there is only one candidate or it is obvious which candidate to choose +# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen +# will still accept a match between prototype and implementation in such cases. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or macro consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and macros in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 27 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command <command> <input-file>, where <command> is the value of +# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. The create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. +# You can optionally specify a file name after the option, if omitted +# DoxygenLayout.xml will be used as the name of the layout file. + +LAYOUT_FILE = ./documentation/DoxygenLayout.xml + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# The WARN_NO_PARAMDOC option can be enabled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = . \ + ./documentation + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh +# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py +# *.f90 *.f *.for *.vhd *.vhdl + +FILE_PATTERNS = *.h \ + *.dox + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = _*.h + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = ./documentation/images-dox + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command <filter> <input-file>, where <filter> +# is the value of the INPUT_FILTER tag, and <input-file> is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty or if +# non of the patterns match the file name, INPUT_FILTER is applied. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) +# and it is also possible to disable source filtering for a specific pattern +# using *.ext= (so without naming a filter). This option only has effect when +# FILTER_SOURCE_FILES is enabled. + +FILTER_SOURCE_PATTERNS = + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. Note that when using a custom header you are responsible +# for the proper inclusion of any scripts and style sheets that doxygen +# needs, which is dependent on the configuration options used. +# It is adviced to generate a default header using "doxygen -w html +# header.html footer.html stylesheet.css YourConfigFile" and then modify +# that header. Note that the header is subject to change so you typically +# have to redo this when upgrading to a newer version of doxygen or when +# changing the value of configuration settings such as GENERATE_TREEVIEW! + +HTML_HEADER = documentation/header.html + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = documentation/footer.html + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = documentation/stylesheet.css + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that +# the files will be copied as-is; there are no commands or markers available. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. +# Doxygen will adjust the colors in the stylesheet and background images +# according to this color. Hue is specified as an angle on a colorwheel, +# see http://en.wikipedia.org/wiki/Hue for more information. +# For instance the value 0 represents red, 60 is yellow, 120 is green, +# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. +# The allowed range is 0 to 359. + +HTML_COLORSTYLE_HUE = 217 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of +# the colors in the HTML output. For a value of 0 the output will use +# grayscales only. A value of 255 will produce the most vivid colors. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to +# the luminance component of the colors in the HTML output. Values below +# 100 gradually make the output lighter, whereas values above 100 make +# the output darker. The value divided by 100 is the actual gamma applied, +# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, +# and 100 does not change the gamma. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting +# this to NO can help when comparing the output of multiple runs. + +HTML_TIMESTAMP = YES + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = NO + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated +# that can be used as input for Qt's qhelpgenerator to generate a +# Qt Compressed Help (.qch) of the generated HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to +# add. For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see +# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters"> +# Qt Help Project / Custom Filters</a>. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's +# filter section matches. +# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes"> +# Qt Help Project / Filter Attributes</a>. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files +# will be generated, which together with the HTML files, form an Eclipse help +# plugin. To install this plugin and make it available under the help contents +# menu in Eclipse, the contents of the directory containing the HTML and XML +# files needs to be copied into the plugins directory of eclipse. The name of +# the directory within the plugins directory should be the same as +# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before +# the help appears. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have +# this name. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values +# (range [0,1..20]) that doxygen will group on one line in the generated HTML +# documentation. Note that a value of 0 will completely suppress the enum +# values from appearing in the overview section. + +ENUM_VALUES_PER_LINE = 0 + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, +# and Class Hierarchy pages using a tree view instead of an ordered list. + +USE_INLINE_TREES = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 251 + +# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open +# links to external symbols imported via tag files in a separate window. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are +# not supported properly for IE 6.0, but are supported on all modern browsers. +# Note that when changing this option you need to delete any form_*.png files +# in the HTML output before the changes have effect. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax +# (see http://www.mathjax.org) which uses client side Javascript for the +# rendering instead of using prerendered bitmaps. Use this if you do not +# have LaTeX installed or if you want to formulas look prettier in the HTML +# output. When enabled you also need to install MathJax separately and +# configure the path to it using the MATHJAX_RELPATH option. + +USE_MATHJAX = NO + +# When MathJax is enabled you need to specify the location relative to the +# HTML output directory using the MATHJAX_RELPATH option. The destination +# directory should contain the MathJax.js script. For instance, if the mathjax +# directory is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the +# mathjax.org site, so you can quickly see the result without installing +# MathJax, but it is strongly recommended to install a local copy of MathJax +# before deployment. + +MATHJAX_RELPATH = http://www.mathjax.org/mathjax + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box +# for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using +# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets +# (GENERATE_DOCSET) there is already a search function so this one should +# typically be disabled. For large projects the javascript based search engine +# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. + +SEARCHENGINE = NO + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be +# implemented using a PHP enabled web server instead of at the web client +# using Javascript. Doxygen will generate the search PHP script and index +# file to put on the web server. The advantage of the server +# based approach is that it scales better to large projects and allows +# full text search. The disadvantages are that it is more difficult to setup +# and does not have live searching capabilities. + +SERVER_BASED_SEARCH = NO + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. +# Note that when enabling USE_PDFLATEX this option is only used for +# generating bitmaps for formulas in the HTML output, but not in the +# Makefile that is written to the output directory. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for +# the generated latex document. The footer should contain everything after +# the last chapter. If it is left blank doxygen will generate a +# standard footer. Notice: only use this tag if you know what you are doing! + +LATEX_FOOTER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include +# source code with syntax highlighting in the LaTeX output. +# Note that which sources are shown also depends on other settings +# such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = YES + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# pointed to by INCLUDE_PATH will be searched when a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = __native_client__ \ + DOXYGEN_SHOULD_SKIP_THIS \ + __attribute__(x)= \ + EXTERN_C_BEGIN= \ + EXTERN_C_END= \ + PP_COMPILE_ASSERT_SIZE_IN_BYTES= \ + PP_COMPILE_ASSERT_STRUCT_SIZE_IN_BYTES= \ + PP_INLINE= \ + PP_EXPORT + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition that +# overrules the definition found in the source code. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all references to function-like macros +# that are alone on a line, have an all uppercase name, and do not end with a +# semicolon, because these will confuse the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option also works with HAVE_DOT disabled, but it is recommended to +# install and use dot, since it yields more powerful graphs. + +CLASS_DIAGRAMS = NO + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = YES + +# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is +# allowed to run in parallel. When set to 0 (the default) doxygen will +# base this on the number of processors available in the system. You can set it +# explicitly to a value larger than 0 to get control over the balance +# between CPU load and processing speed. + +DOT_NUM_THREADS = 4 + +# By default doxygen will write a font called Helvetica to the output +# directory and reference it in all dot files that doxygen generates. +# When you want a differently looking font you can specify the font name +# using DOT_FONTNAME. You need to make sure dot is able to find the font, +# which can be done by putting it in a standard location or by setting the +# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory +# containing the font. + +DOT_FONTNAME = FreeSans.ttf + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the output directory to look for the +# FreeSans.ttf font (which doxygen will put there itself). If you specify a +# different font using DOT_FONTNAME you can set the path where dot +# can find it using this tag. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = NO + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = NO + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will generate a graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are svg, png, jpg, or gif. +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = /usr/local/graphviz-2.14/bin + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MSCFILE_DIRS tag can be used to specify one or more directories that +# contain msc files that are included in the documentation (see the +# \mscfile command). + +MSCFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 57 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 1000 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = YES + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/chromium/ppapi/cpp/documentation/DoxygenLayout.xml b/chromium/ppapi/cpp/documentation/DoxygenLayout.xml new file mode 100644 index 00000000000..a5be8a1fa8f --- /dev/null +++ b/chromium/ppapi/cpp/documentation/DoxygenLayout.xml @@ -0,0 +1,184 @@ +<doxygenlayout version="1.0"> + <!-- Navigation index tabs for HTML output --> + <navindex> + <tab type="mainpage" visible="no" title=""/> + <tab type="pages" visible="no" title=""/> + <tab type="modules" visible="yes" title=""/> + <tab type="namespaces" visible="no" title=""> + <tab type="namespaces" visible="no" title=""/> + <tab type="namespacemembers" visible="no" title=""/> + </tab> + <tab type="classes" visible="no" title=""> + <tab type="classes" visible="no" title=""/> + <tab type="classindex" visible="no" title=""/> + <tab type="hierarchy" visible="no" title=""/> + <tab type="classmembers" visible="no" title=""/> + </tab> + <tab type="files" visible="no" title=""> + <tab type="files" visible="no" title=""/> + <tab type="globals" visible="no" title=""/> + </tab> + <tab type="dirs" visible="no" title=""/> + <tab type="examples" visible="no" title=""/> + </navindex> + + <!-- Layout definition for a class page --> + <class> + <briefdescription visible="yes"/> + <includes visible="$SHOW_INCLUDE_FILES"/> + <inheritancegraph visible="$CLASS_GRAPH"/> + <collaborationgraph visible="$COLLABORATION_GRAPH"/> + <allmemberslink visible="yes"/> + <memberdecl> + <nestedclasses visible="yes" title=""/> + <publictypes title=""/> + <publicslots title=""/> + <signals title=""/> + <publicmethods title="Public Functions"/> + <publicstaticmethods title="Static Public Member Functions"/> + <publicattributes title=""/> + <publicstaticattributes title=""/> + <protectedtypes title=""/> + <protectedslots title=""/> + <protectedmethods title="Protected Functions"/> + <protectedstaticmethods title=""/> + <protectedattributes title="Protected Attributes"/> + <protectedstaticattributes title=""/> + <packagetypes title=""/> + <packagemethods title=""/> + <packagestaticmethods title=""/> + <packageattributes title=""/> + <packagestaticattributes title=""/> + <properties title=""/> + <events title=""/> + <privatetypes title=""/> + <privateslots title=""/> + <privatemethods title=""/> + <privatestaticmethods title=""/> + <privateattributes title=""/> + <privatestaticattributes title=""/> + <friends title="Friends List"/> + <related title="" subtitle=""/> + <membergroups visible="yes"/> + </memberdecl> + <detaileddescription title=""/> + <memberdef> + <typedefs title=""/> + <enums title=""/> + <constructors title="Constructor and Destructor Details"/> + <functions title="Function Details"/> + <related title="Friends and Related Functions Details"/> + <variables title="Member Data Details"/> + <properties title=""/> + <events title=""/> + </memberdef> + <usedfiles visible="$SHOW_USED_FILES"/> + <authorsection visible="yes"/> + </class> + + <!-- Layout definition for a namespace page --> + <namespace> + <briefdescription visible="yes"/> + <memberdecl> + <nestednamespaces visible="yes" title=""/> + <classes visible="yes" title=""/> + <typedefs title=""/> + <enums title=""/> + <functions title=""/> + <variables title=""/> + <membergroups visible="yes"/> + </memberdecl> + <detaileddescription title=""/> + <memberdef> + <typedefs title=""/> + <enums title=""/> + <functions title=""/> + <variables title=""/> + </memberdef> + <authorsection visible="yes"/> + </namespace> + + <!-- Layout definition for a file page --> + <file> + <briefdescription visible="yes"/> + <includes visible="$SHOW_INCLUDE_FILES"/> + <includegraph visible="$INCLUDE_GRAPH"/> + <includedbygraph visible="$INCLUDED_BY_GRAPH"/> + <sourcelink visible="yes"/> + <memberdecl> + <classes visible="yes" title=""/> + <namespaces visible="yes" title=""/> + <defines title=""/> + <typedefs title=""/> + <enums title=""/> + <functions title=""/> + <variables title=""/> + <membergroups visible="yes"/> + </memberdecl> + <detaileddescription title=""/> + <memberdef> + <defines title=""/> + <typedefs title=""/> + <enums title=""/> + <functions title="Function Details"/> + <variables title=""/> + </memberdef> + <authorsection/> + </file> + + <!-- Layout definition for a group page --> + <group> + <briefdescription visible="yes"/> + <groupgraph visible="$GROUP_GRAPHS"/> + <memberdecl> + <classes visible="yes" title=""/> + <namespaces visible="yes" title=""/> + <dirs visible="yes" title=""/> + <nestedgroups visible="yes" title=""/> + <files visible="yes" title=""/> + <defines title=""/> + <typedefs title=""/> + <enums title=""/> + <enumvalues title=""/> + <functions title=""/> + <variables title=""/> + <signals title=""/> + <publicslots title=""/> + <protectedslots title=""/> + <privateslots title=""/> + <events title=""/> + <properties title=""/> + <friends title=""/> + <membergroups visible="yes"/> + </memberdecl> + <detaileddescription title=""/> + <memberdef> + <pagedocs/> + <defines title=""/> + <typedefs title=""/> + <enums title=""/> + <enumvalues title=""/> + <functions title=""/> + <variables title=""/> + <signals title=""/> + <publicslots title=""/> + <protectedslots title=""/> + <privateslots title=""/> + <events title=""/> + <properties title=""/> + <friends title=""/> + </memberdef> + <authorsection visible="yes"/> + </group> + + <!-- Layout definition for a directory page --> + <directory> + <briefdescription visible="yes"/> + <directorygraph visible="yes"/> + <memberdecl> + <dirs visible="yes"/> + <files visible="yes"/> + </memberdecl> + <detaileddescription title=""/> + </directory> +</doxygenlayout> diff --git a/chromium/ppapi/cpp/documentation/check.sh b/chromium/ppapi/cpp/documentation/check.sh new file mode 100755 index 00000000000..793f408b419 --- /dev/null +++ b/chromium/ppapi/cpp/documentation/check.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# Copyright (c) 2013 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. + +# simple script to check html via tidy. Either specify html files on +# command line or rely on default which checks all html files in +# current directory +set -o nounset +set -o errexit + + +CheckFile () { + echo "========================================" + echo "checking $1" + echo "========================================" + tidy -e -q $1 +} + + +if [ $# -eq 0 ] ; then + for file in *.html ; do + CheckFile ${file} + done +else + for file in $* ; do + CheckFile ${file} + done +fi diff --git a/chromium/ppapi/cpp/documentation/doxy_cleanup.py b/chromium/ppapi/cpp/documentation/doxy_cleanup.py new file mode 100755 index 00000000000..24ddb3c306c --- /dev/null +++ b/chromium/ppapi/cpp/documentation/doxy_cleanup.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python +# Copyright (c) 2012 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +'''This utility cleans up the html files as emitted by doxygen so +that they are suitable for publication on a Google documentation site. +''' + +import optparse +import os +import re +import shutil +import string +import sys +try: + from BeautifulSoup import BeautifulSoup, Tag +except (ImportError, NotImplementedError): + print ("This tool requires the BeautifulSoup package " + "(see http://www.crummy.com/software/BeautifulSoup/).\n" + "Make sure that the file BeautifulSoup.py is either in this directory " + "or is available in your PYTHON_PATH") + raise + + +class HTMLFixer(object): + '''This class cleans up the html strings as produced by Doxygen + ''' + + def __init__(self, html): + self.soup = BeautifulSoup(html) + + def FixTableHeadings(self): + '''Fixes the doxygen table headings. + + This includes: + - Using bare <h2> title row instead of row embedded in <tr><td> in table + - Putting the "name" attribute into the "id" attribute of the <tr> tag. + - Splitting up tables into multiple separate tables if a table + heading appears in the middle of a table. + + For example, this html: + <table> + <tr><td colspan="2"><h2><a name="pub-attribs"></a> + Data Fields List</h2></td></tr> + ... + </table> + + would be converted to this: + <h2>Data Fields List</h2> + <table> + ... + </table> + ''' + + table_headers = [] + for tag in self.soup.findAll('tr'): + if tag.td and tag.td.h2 and tag.td.h2.a and tag.td.h2.a['name']: + #tag['id'] = tag.td.h2.a['name'] + tag.string = tag.td.h2.a.next + tag.name = 'h2' + table_headers.append(tag) + + # reverse the list so that earlier tags don't delete later tags + table_headers.reverse() + # Split up tables that have multiple table header (th) rows + for tag in table_headers: + print "Header tag: %s is %s" % (tag.name, tag.string.strip()) + # Is this a heading in the middle of a table? + if tag.findPreviousSibling('tr') and tag.parent.name == 'table': + print "Splitting Table named %s" % tag.string.strip() + table = tag.parent + table_parent = table.parent + table_index = table_parent.contents.index(table) + new_table = Tag(self.soup, name='table', attrs=table.attrs) + table_parent.insert(table_index + 1, new_table) + tag_index = table.contents.index(tag) + for index, row in enumerate(table.contents[tag_index:]): + new_table.insert(index, row) + # Now move the <h2> tag to be in front of the <table> tag + assert tag.parent.name == 'table' + table = tag.parent + table_parent = table.parent + table_index = table_parent.contents.index(table) + table_parent.insert(table_index, tag) + + def RemoveTopHeadings(self): + '''Removes <div> sections with a header, tabs, or navpath class attribute''' + header_tags = self.soup.findAll( + name='div', + attrs={'class' : re.compile('^(header|tabs[0-9]*|navpath)$')}) + [tag.extract() for tag in header_tags] + + def FixAll(self): + self.FixTableHeadings() + self.RemoveTopHeadings() + + def __str__(self): + return str(self.soup) + + +def main(): + '''Main entry for the doxy_cleanup utility + + doxy_cleanup takes a list of html files and modifies them in place.''' + + parser = optparse.OptionParser(usage='Usage: %prog [options] files...') + + parser.add_option('-m', '--move', dest='move', action='store_true', + default=False, help='move html files to "original_html"') + + options, files = parser.parse_args() + + if not files: + parser.print_usage() + return 1 + + for filename in files: + try: + with open(filename, 'r') as file: + html = file.read() + + print "Processing %s" % filename + fixer = HTMLFixer(html) + fixer.FixAll() + with open(filename, 'w') as file: + file.write(str(fixer)) + if options.move: + new_directory = os.path.join( + os.path.dirname(os.path.dirname(filename)), 'original_html') + if not os.path.exists(new_directory): + os.mkdir(new_directory) + shutil.move(filename, new_directory) + except: + print "Error while processing %s" % filename + raise + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/chromium/ppapi/cpp/documentation/footer.html b/chromium/ppapi/cpp/documentation/footer.html new file mode 100644 index 00000000000..454a1016168 --- /dev/null +++ b/chromium/ppapi/cpp/documentation/footer.html @@ -0,0 +1,5 @@ +</div> <!-- id="doxygen-ref" --> + + </body> +</html> + diff --git a/chromium/ppapi/cpp/documentation/header.html b/chromium/ppapi/cpp/documentation/header.html new file mode 100644 index 00000000000..89b99a9390d --- /dev/null +++ b/chromium/ppapi/cpp/documentation/header.html @@ -0,0 +1,13 @@ +{% include "native-client/_local_variables.html" %} +<html devsite> + <head> + <link href="/native-client/css/local_extensions.css" rel="stylesheet" type="text/css" /> + <title>$title</title> + <meta name="project_path" value="/native-client/_project.yaml" /> + <meta name="book_path" value="/native-client/_book.yaml" /> + + </head> + <body> + +<div id="doxygen-ref"> +<div>
\ No newline at end of file diff --git a/chromium/ppapi/cpp/documentation/images-dox/README.txt b/chromium/ppapi/cpp/documentation/images-dox/README.txt new file mode 100644 index 00000000000..9a9e18c7255 --- /dev/null +++ b/chromium/ppapi/cpp/documentation/images-dox/README.txt @@ -0,0 +1,9 @@ +This directory holds all images that go into the doxygen-generated +API reference doc. To include an image, use code like the following: + +@image html figure.jpg + +If you want a caption, specify it like this: + +@image html figure.jpg "Test image" + diff --git a/chromium/ppapi/cpp/documentation/index.dox b/chromium/ppapi/cpp/documentation/index.dox new file mode 100644 index 00000000000..5b516c37b01 --- /dev/null +++ b/chromium/ppapi/cpp/documentation/index.dox @@ -0,0 +1,50 @@ +<!DOCTYPE html> +[include "/chrome/nativeclient/_local_variables.ezt"] [# this file should be at root of your document hierarchy ] +[define section]docs[end] [# this should be "docs" if the file lives in the "Docs" section (top nav)] + [# Otherwise, it's "home," "articles," "download," or "terms" ] +[define page_title]Pepper C API[end] [# this is the title for only this page ] + +[include "/_boilerplate_header.ezt"] +[verbatim] + +<p>This reference documentation describes the C version of the Pepper API, a cross-platform, open-source API for creating Native Client modules. Some interfaces are already implemented in any Native Client-aware browser and certain portions of the API will be implemented by you in the Native Client module. This page has the following contents: +</p> + +<ol class="toc"> +<li><a href="#reading">Before you start</a></li> +<li><a href="#pepperc">Pepper C reference</a></li> +<li><a href="#navigate">Navigating the Pepper C reference</a></li> +</ol> + +<h2 id="reading">Before you start</h2> + +<p>We recommend that you read the following documents prior to reading the API documentation:</p> + +<ul class="nolist"> +<li><a href="/chrome/nativeclient/docs/technical_overview.html">Technical Overview</a></li> +<li><a href="/chrome/nativeclient/docs/tutorial.html">Tutorial: Getting Started</a></li> +<li><a href="/chrome/nativeclient/docs/developers_guide.html">Developer's Guide</a></li> +</ul> + +<h2 id="pepperc">Pepper C reference</h2> + +<p>The lowest level of the Pepper API is the C API, declared in the header files in ppapi/c. The C API represents the lowest level binary interface between a Native Client module and the browser.</p> + +<h3>C API Groupings</h3> + +<p>The C API is divided into three sub-groupings, indicated by the prefixes PP, PPB, and PPP.</p> + +<p>The prefix "PP," used to help prevent naming collisions, stands for "Pepper Plugin" also known as the "Native Client module." Common structs have a PP_ prefix, such as PP_Var for representing a JavaScript variable or PP_Rect for describing a rectangle. There are also several PP_ utility functions in the PP_ grouping.</p> + +<p>Interfaces in the C API are named according to whether they are implemented by the browser or by you, the web app developer, in the Native Client module. Interfaces implemented by the browser are prefixed by "PPB" where "B" stands for browser. For example, the PPB_Core interface is a collection of core interfaces implemented by the browser and accessed by the Native Client module. As a web app developer, you need only know how to invoke PPB_ interfaces in your Native Client module.</p> + +<p>Interfaces implemented by the Native Client module (Plugin) are prefixed by "PPP" where "P" stands for plugin. For example, the PPP_Class interface provides an object accessible to JavaScript in the browser. You will implement these interfaces in your Native Client module.</p> + +<p>In some cases, there might be both a browser and a Native Client module interface for the same concept. For example, the PPP_Instance interface represents the Native Client module functions that the browser calls related to a certain instance. This interface is used to deliver mouse click events to the Native Client module. The Native Client module will call PPB_Instance in the browser to allow the Native Client module to manipulate its instance.</p> + +<h2 id="navigate">Navigating the Pepper C reference</h2> + +<p>Click on any of the links below "Pepper C API" on the left to view the API by construct (all interfaces, structures, functions, and so on), functional area (all APIs pertaining to audio, 2D graphics, 3D graphics, and so on), or file (all APIs in <code>pp_bool.h</code>, <code>ppp.h</code>, <code>ppb_var.h</code>, and so on).</p> + +[endverbatim] +[include "/_boilerplate_footer.ezt"] diff --git a/chromium/ppapi/cpp/documentation/removefilesCPP.sh b/chromium/ppapi/cpp/documentation/removefilesCPP.sh new file mode 100755 index 00000000000..26e445ecb00 --- /dev/null +++ b/chromium/ppapi/cpp/documentation/removefilesCPP.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +# Copyright (c) 2012 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +rm annotated.html +rm bc_s.png +rm classes.html +rm closed.png +rm doxygen.png +rm functions*.* +rm globals*.* +rm index_8dox.html +rm namespacemembers.html +rm namespacemembers_func.html +rm namespaces.html +rm nav_f.png +rm nav_h.png +rm open.png +rm tab_a.png +rm tab_b.png +rm tab_h.png +rm tab_s.png +# all .map and all .md5 files +rm *.md5 +rm *.map +rm *.css +rm index.html +rm jquery.js +rm hierarchy.html + + + + diff --git a/chromium/ppapi/cpp/documentation/stylesheet-dox.css b/chromium/ppapi/cpp/documentation/stylesheet-dox.css new file mode 100644 index 00000000000..81d1a4251ca --- /dev/null +++ b/chromium/ppapi/cpp/documentation/stylesheet-dox.css @@ -0,0 +1,478 @@ +body, table, div, p, dl { + font-family: Lucida Grande, Verdana, Geneva, Arial, sans-serif; + font-size: 12px; +} + +/* @group Heading Levels */ + +h1 { + text-align: center; + font-size: 150%; +} + +h1 a, h2 a, h3 a, h4 a { + font-weight:bold; +} + +h2 { + font-size: 120%; + margin-top: 2.0em; + margin-bottom: 0.5em; +} + +h3 { + font-size: 100%; +} + +div.contents { + margin-top: 2.0em; +} + +/* @end */ + +caption { + font-weight: bold; + font-size: 9px; +} + +div.qindex, div.navpath, div.navtab{ + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + padding: 2px; +} + +div.qindex, div.navpath { + width: 100%; + line-height: 140%; +} + +div.navtab { + margin-right: 15px; +} + +/* @group Link Styling */ + +a { + color: #153788; + font-weight: normal; + text-decoration: none; +} + +.contents a:visited { + color: #1b77c5; +} + +a:hover { + text-decoration: underline; +} + +a.qindex { + font-weight: bold; +} + +a.qindexHL { + font-weight: bold; + background-color: #6666cc; + color: #ffffff; + border: 1px double #9295C2; +} + +a.el { + font-weight: bold; +} + +a.elRef { +} + +a.code { +} + +a.codeRef { +} + +/* @end */ + +dl.el { + margin-left: -1cm; +} + +.fragment { + font-family: monospace, fixed; + font-size: 105%; +} + +pre.fragment { + border: 1px solid #CCCCCC; + background-color: #f5f5f5; + padding: 4px 6px; + margin: 4px 8px 4px 2px; +} + +div.ah { + background-color: black; + font-weight: bold; + color: #ffffff; + margin-bottom: 3px; + margin-top: 3px +} + +div.groupHeader { + margin-left: 16px; + margin-top: 12px; + margin-bottom: 6px; + font-weight: bold; +} + +div.groupText { + margin-left: 16px; + font-style: italic; +} + +body { + background: white; + color: black; + margin-right: 20px; + margin-left: 20px; +} + +td.indexkey { + background-color: #e8eef2; + font-weight: bold; + border: 1px solid #CCCCCC; + margin: 2px 0px 2px 0; + padding: 2px 10px; +} + +td.indexvalue { + background-color: #e8eef2; + border: 1px solid #CCCCCC; + padding: 2px 10px; + margin: 2px 0px; +} + +tr.memlist { + background-color: #f0f0f0; +} + +p.formulaDsp { + text-align: center; +} + +img.formulaDsp { +} + +img.formulaInl { + vertical-align: middle; +} + +/* @group Code Colorization */ + +span.keyword { + color: #008000 +} + +span.keywordtype { + color: #604020 +} + +span.keywordflow { + color: #e08000 +} + +span.comment { + color: #800000 +} + +span.preprocessor { + color: #806020 +} + +span.stringliteral { + color: #002080 +} + +span.charliteral { + color: #008080 +} + +span.vhdldigit { + color: #ff00ff +} + +span.vhdlchar { + color: #000000 +} + +span.vhdlkeyword { + color: #700070 +} + +span.vhdllogic { + color: #ff0000 +} + +/* @end */ + +.search { + color: #003399; + font-weight: bold; +} + +form.search { + margin-bottom: 0px; + margin-top: 0px; +} + +input.search { + font-size: 75%; + color: #000080; + font-weight: normal; + background-color: #e8eef2; +} + +td.tiny { + font-size: 75%; +} + +.dirtab { + padding: 4px; + border-collapse: collapse; + border: 1px solid #84b0c7; +} + +th.dirtab { + background: #e8eef2; + font-weight: bold; +} + +hr { + height: 0; + border: none; + border-top: 1px solid #666; +} + +/* @group Member Descriptions */ + +.mdescLeft, .mdescRight, +.memItemLeft, .memItemRight, +.memTemplItemLeft, .memTemplItemRight, .memTemplParams { + background-color: #FAFAFA; + border: none; + margin: 4px; + padding: 1px 0 0 8px; +} + +.mdescLeft, .mdescRight { + padding: 0px 8px 4px 8px; + color: #555; +} + +.memItemLeft, .memItemRight, .memTemplParams { + border-top: 1px solid #ccc; +} + +.memTemplParams { + color: #606060; +} + +/* @end */ + +/* @group Member Details */ + +/* Styles for detailed member documentation */ + +.memtemplate { + font-size: 80%; + color: #606060; + font-weight: normal; + margin-left: 3px; +} + +.memnav { + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + margin-right: 15px; + padding: 2px; +} + +.memitem { + padding: 0; +} + +.memname { + white-space: nowrap; + font-weight: bold; +} + +.memproto, .memdoc { + border: 1px solid #84b0c7; +} + +.memproto { + padding: 0; + background-color: #d5e1e8; + font-weight: bold; + -webkit-border-top-left-radius: 8px; + -webkit-border-top-right-radius: 8px; + -moz-border-radius-topleft: 8px; + -moz-border-radius-topright: 8px; +} + +.memdoc { + padding: 2px 5px; + background-color: #eef3f5; + border-top-width: 0; + -webkit-border-bottom-left-radius: 8px; + -webkit-border-bottom-right-radius: 8px; + -moz-border-radius-bottomleft: 8px; + -moz-border-radius-bottomright: 8px; +} + +.memdoc p, .memdoc dl, .memdoc ul { + margin: 6px 0; +} + +.paramkey { + text-align: right; +} + +.paramtype { + white-space: nowrap; +} + +.paramname { + color: #602020; + white-space: nowrap; +} +.paramname em { + font-style: normal; +} + +/* @end */ + +/* @group Directory (tree) */ + +/* for the tree view */ + +.ftvtree { + font-family: sans-serif; + margin: 0.5em; +} + +/* these are for tree view when used as main index */ + +.directory { + font-size: 9pt; + font-weight: bold; +} + +.directory h3 { + margin: 0px; + margin-top: 1em; + font-size: 11pt; +} + +/* +The following two styles can be used to replace the root node title +with an image of your choice. Simply uncomment the next two styles, +specify the name of your image and be sure to set 'height' to the +proper pixel height of your image. +*/ + +/* +.directory h3.swap { + height: 61px; + background-repeat: no-repeat; + background-image: url("yourimage.gif"); +} +.directory h3.swap span { + display: none; +} +*/ + +.directory > h3 { + margin-top: 0; +} + +.directory p { + margin: 0px; + white-space: nowrap; +} + +.directory div { + display: none; + margin: 0px; +} + +.directory img { + vertical-align: -30%; +} + +/* these are for tree view when not used as main index */ + +.directory-alt { + font-size: 100%; + font-weight: bold; +} + +.directory-alt h3 { + margin: 0px; + margin-top: 1em; + font-size: 11pt; +} + +.directory-alt > h3 { + margin-top: 0; +} + +.directory-alt p { + margin: 0px; + white-space: nowrap; +} + +.directory-alt div { + display: none; + margin: 0px; +} + +.directory-alt img { + vertical-align: -30%; +} + +/* @end */ + +address { + font-style: normal; + text-align: center; + font-size: 90%; + color: gray; +} + +DIV.tabs A, #toplinks +{ + font-size : 9px; +} + +#toplinks { + text-align: right; + margin-bottom: -1.9em; +} + +.pending { + /* display:none; */ + color:red; font-weight:bold; +} + +#license { + color:gray; + font-size:90%; + border-top:1px solid; + border-color:gray; + padding-top:1em; + margin-top:3em; + text-align:center; +} diff --git a/chromium/ppapi/cpp/documentation/stylesheet.css b/chromium/ppapi/cpp/documentation/stylesheet.css new file mode 100644 index 00000000000..9ed8e38bc41 --- /dev/null +++ b/chromium/ppapi/cpp/documentation/stylesheet.css @@ -0,0 +1,246 @@ +/* + * Based off the Doxygen generated template stylesheet and trimmed/edited to + * remove items that would conflict with codesite or other overlying + * stylesheets while maintaining the desired look and feel. + * + * The #doxygen-ref is an id tag which encompasses code generated by doxygen + * and allows override of standard html tags while not affecting the rest + * of the page such as sidebars. + */ + +A.qindex { + text-decoration: none; + font-weight: bold; + color: #1A419D; +} +A.qindex:visited { + text-decoration: none; + font-weight: bold; + color: #1A419D +} +A.qindex:hover { + text-decoration: none; + background-color: #ddf; +} +A.qindexHL { + text-decoration: none; + font-weight: bold; + background-color: #66c; + color: #fff; + border: 1px double #9295C2; +} +A.qindexHL:hover, +A.qindexHL:visited { + text-decoration: none; + background-color: #66c; + color: #fff; +} +A.el { + text-decoration: none; + font-weight: bold; +} +A.elRef { + font-weight: bold; +} +A.code:link, +A.code:visited { + text-decoration: none; + font-weight: normal; + color: #00F; +} +A.codeRef:link, +A.codeRef:visited { + font-weight: normal; + color: #00F; +} +A:hover { + text-decoration: none; + background-color: #f2f2ff; +} +DL.el { + margin-left: -1cm; +} +.fragment { + font-family: Fixed, monospace; + font-size: 95%; +} +PRE.fragment { + border: 1px solid #CCC; + background-color: #f5f5f5; + margin: 4px 8px 4px 2px + padding: 4px 6px; +} +DIV.ah { + background-color: black; + font-weight: bold; + color: #fff; + margin-bottom: 3px; + margin-top: 3px +} +TD.md { + background-color: #e1e1e4; + font-weight: bold; + border: none; +} +TD.mdPrefix { + background-color: #e1e1e4; + color: #606060; + font-size: 80%; + border: none; +} +TD.mdname1 { + background-color: #e1e1e4; + font-weight: bold; + color: #602020; + border: none; +} +.memitem { + padding: 4px; + background-color: #ffff; +} +.memname { + background-color: #e1e1e4; + white-space: nowrap; + font-weight: bold; +} +.memdoc{ + padding-left: 10px; +} +#doxygen-ref div.memproto td { + background-color: #e1e1e4; +} +.memproto { + background-color: #e1e1e4; + width: 100%; + border-width: 1px; + border-style: solid; + border-color: #e1e1f4; + font-weight: bold; + -moz-border-radius: 8px 8px 8px 8px; +} +.memproto .deprecated, +.memname .deprecated, +.summary .deprecated { + color: red; +} +.paramkey { + text-align: right; +} +.paramtype { + white-space: nowrap; +} +.paramname { + color: #602020; + font-style: italic; + white-space: nowrap; +} +DIV.groupHeader { + margin: 12px 16px 6px auto; + font-weight: bold; +} +DIV.groupText { + margin-left: 16px; + font-style: italic; + font-size: 90%; +} +TR.memlist { + background-color: #f0f0f0; +} +P.formulaDsp { + text-align: center; +} +IMG.formulaInl { + vertical-align: middle; +} +SPAN.keyword, +SPAN.keywordflow { + color: #008000; +} +SPAN.keywordtyp { + color: #604020; +} +SPAN.comment { + color: #800000; +} +SPAN.preprocessor { + color: #806020; +} +SPAN.stringliteral { + color: #002080; +} +SPAN.charliteral { + color: #008080; +} +.mdTable { + background-color: #e1e1e4; + border: none; + padding: 0; +} +.mdRow { + padding: 8px 10px; + border: none; +} +.mdescLeft, +.mdescRight { + padding: 0 8px 4px 8px; + font-size: 80%; + font-style: italic; + background-color: #FAFAFA; + border: 1px none #E0E0E0; + margin: 0; +} +.search { + color: #039; + font-weight: bold; +} +FORM.search { + margin: 0 auto; +} +INPUT.search { + font-size: 75%; + color: #000080; + font-weight: normal; + background-color: #e8eef2; +} +TD.tiny{ + font-size: 75%; +} +#doxygen-ref HR { + height: 1px; + border: none; + border-top: 1px solid black; +} +#doxygen-ref table, +#doxygen-ref td, +#doxygen-ref tr { + border:none; +} +#doxygen-ref .contents H1 { + text-align: center; + background-color: #ffffff; + border: 0; +} +#doxygen-ref H2 { + margin-left: 0; + margin-bottom: 5px; +} +#doxygen-ref CAPTION { + font-weight: bold; +} +#doxygen-ref .contents .summary { + line-height: 1em; +} +#doxygen-ref .contents .summary TD { +} +#doxygen-ref .contents .summary .type { + text-align: right; +} +.memdoc { + padding-left: 30px; +} +.memitem { + border-top:1px solid #E5ECF9; +} +.doxygen-global { + background-color: #ffcc66; +}
\ No newline at end of file diff --git a/chromium/ppapi/cpp/documentation/tabs.css b/chromium/ppapi/cpp/documentation/tabs.css new file mode 100644 index 00000000000..132fb6e71e1 --- /dev/null +++ b/chromium/ppapi/cpp/documentation/tabs.css @@ -0,0 +1,59 @@ +.tabs, .tabs2, .tabs3 { + background-image: url('tab_b.png'); + width: 100%; + z-index: 101; + font-size: 13px; +} + +.tabs2 { + font-size: 10px; +} +.tabs3 { + font-size: 9px; +} + +.tablist { + margin: 0; + padding: 0; + display: table; +} + +.tablist li { + float: left; + display: table-cell; + background-image: url('tab_b.png'); + line-height: 36px; + list-style: none; +} + +.tablist a { + display: block; + padding: 0 20px; + font-weight: bold; + background-image:url('tab_s.png'); + background-repeat:no-repeat; + background-position:right; + color: #283C5D; + text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9); + text-decoration: none; + outline: none; +} + +.tabs3 .tablist a { + padding: 0 10px; +} + +.tablist a:hover { + background-image: url('tab_h.png'); + background-repeat:repeat-x; + color: #fff; + text-shadow: 0px 1px 1px rgba(0, 0, 0, 1.0); + text-decoration: none; +} + +.tablist li.current a { + background-image: url('tab_a.png'); + background-repeat:repeat-x; + color: #fff; + text-shadow: 0px 1px 1px rgba(0, 0, 0, 1.0); +} diff --git a/chromium/ppapi/cpp/extensions/dev/alarms_dev.cc b/chromium/ppapi/cpp/extensions/dev/alarms_dev.cc new file mode 100644 index 00000000000..1cf84646350 --- /dev/null +++ b/chromium/ppapi/cpp/extensions/dev/alarms_dev.cc @@ -0,0 +1,179 @@ +// Copyright (c) 2013 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 "ppapi/cpp/extensions/dev/alarms_dev.h" + +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/extensions/optional.h" +#include "ppapi/cpp/extensions/to_var_converter.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var_dictionary.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Ext_Alarms_Dev_0_1>() { + return PPB_EXT_ALARMS_DEV_INTERFACE_0_1; +} + +} // namespace + +namespace ext { +namespace alarms { + +const char* const Alarm_Dev::kName = "name"; +const char* const Alarm_Dev::kScheduledTime = "scheduledTime"; +const char* const Alarm_Dev::kPeriodInMinutes = "periodInMinutes"; + +Alarm_Dev::Alarm_Dev() + : name(kName), + scheduled_time(kScheduledTime), + period_in_minutes(kPeriodInMinutes) { +} + +Alarm_Dev::~Alarm_Dev() { +} + +bool Alarm_Dev::Populate(const PP_Ext_Alarms_Alarm_Dev& value) { + if (value.type != PP_VARTYPE_DICTIONARY) + return false; + + VarDictionary dict(value); + bool result = name.Populate(dict); + result = scheduled_time.Populate(dict) && result; + result = period_in_minutes.Populate(dict) && result; + + return result; +} + +Var Alarm_Dev::CreateVar() const { + VarDictionary dict; + + bool result = name.AddTo(&dict); + result = scheduled_time.AddTo(&dict) && result; + result = period_in_minutes.MayAddTo(&dict) && result; + PP_DCHECK(result); + + return dict; +} + +const char* const AlarmCreateInfo_Dev::kWhen = "when"; +const char* const AlarmCreateInfo_Dev::kDelayInMinutes = "delayInMinutes"; +const char* const AlarmCreateInfo_Dev::kPeriodInMinutes = "periodInMinutes"; + +AlarmCreateInfo_Dev::AlarmCreateInfo_Dev() + : when(kWhen), + delay_in_minutes(kDelayInMinutes), + period_in_minutes(kPeriodInMinutes) { +} + +AlarmCreateInfo_Dev::~AlarmCreateInfo_Dev() { +} + +bool AlarmCreateInfo_Dev::Populate( + const PP_Ext_Alarms_AlarmCreateInfo_Dev& value) { + if (value.type != PP_VARTYPE_DICTIONARY) + return false; + + VarDictionary dict(value); + bool result = when.Populate(dict); + result = delay_in_minutes.Populate(dict) && result; + result = period_in_minutes.Populate(dict) && result; + + return result; +} + +Var AlarmCreateInfo_Dev::CreateVar() const { + VarDictionary dict; + + bool result = when.MayAddTo(&dict); + result = delay_in_minutes.MayAddTo(&dict) && result; + result = period_in_minutes.MayAddTo(&dict) && result; + PP_DCHECK(result); + + return dict; +} + +Alarms_Dev::Alarms_Dev(const InstanceHandle& instance) : instance_(instance) { +} + +Alarms_Dev::~Alarms_Dev() { +} + +void Alarms_Dev::Create(const Optional<std::string>& name, + const AlarmCreateInfo_Dev& alarm_info) { + if (!has_interface<PPB_Ext_Alarms_Dev_0_1>()) + return; + + internal::ToVarConverter<Optional<std::string> > name_var(name); + internal::ToVarConverter<AlarmCreateInfo_Dev> alarm_info_var(alarm_info); + + return get_interface<PPB_Ext_Alarms_Dev_0_1>()->Create( + instance_.pp_instance(), + name_var.pp_var(), + alarm_info_var.pp_var()); +} + +int32_t Alarms_Dev::Get(const Optional<std::string>& name, + const GetCallback& callback) { + if (!has_interface<PPB_Ext_Alarms_Dev_0_1>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<Optional<std::string> > name_var(name); + + return get_interface<PPB_Ext_Alarms_Dev_0_1>()->Get( + instance_.pp_instance(), + name_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Alarms_Dev::GetAll(const GetAllCallback& callback) { + if (!has_interface<PPB_Ext_Alarms_Dev_0_1>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + return get_interface<PPB_Ext_Alarms_Dev_0_1>()->GetAll( + instance_.pp_instance(), + callback.output(), + callback.pp_completion_callback()); +} + +void Alarms_Dev::Clear(const Optional<std::string>& name) { + if (!has_interface<PPB_Ext_Alarms_Dev_0_1>()) + return; + + internal::ToVarConverter<Optional<std::string> > name_var(name); + + return get_interface<PPB_Ext_Alarms_Dev_0_1>()->Clear( + instance_.pp_instance(), + name_var.pp_var()); +} + +void Alarms_Dev::ClearAll() { + if (!has_interface<PPB_Ext_Alarms_Dev_0_1>()) + return; + + return get_interface<PPB_Ext_Alarms_Dev_0_1>()->ClearAll( + instance_.pp_instance()); +} + +OnAlarmEvent_Dev::OnAlarmEvent_Dev( + const InstanceHandle& instance, + Listener* listener) + : internal::EventBase1<PP_Ext_Alarms_OnAlarm_Dev, Alarm_Dev>(instance), + listener_(listener) { +} + +OnAlarmEvent_Dev::~OnAlarmEvent_Dev() { +} + +void OnAlarmEvent_Dev::Callback(Alarm_Dev& alarm) { + listener_->OnAlarm(alarm); +} + +} // namespace alarms +} // namespace ext +} // namespace pp diff --git a/chromium/ppapi/cpp/extensions/dev/alarms_dev.h b/chromium/ppapi/cpp/extensions/dev/alarms_dev.h new file mode 100644 index 00000000000..57d82d0bf8f --- /dev/null +++ b/chromium/ppapi/cpp/extensions/dev/alarms_dev.h @@ -0,0 +1,117 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_EXTENSIONS_DEV_ALARMS_DEV_H_ +#define PPAPI_CPP_EXTENSIONS_DEV_ALARMS_DEV_H_ + +#include <string> +#include <vector> + +#include "ppapi/c/extensions/dev/ppb_ext_alarms_dev.h" +#include "ppapi/cpp/extensions/dict_field.h" +#include "ppapi/cpp/extensions/event_base.h" +#include "ppapi/cpp/extensions/ext_output_traits.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/var.h" + +namespace pp { +namespace ext { + +template <class T> +class ExtCompletionCallbackWithOutput; + +template <class T> +class Optional; + +namespace alarms { + +// Data types ------------------------------------------------------------------ +class Alarm_Dev { + public: + Alarm_Dev(); + ~Alarm_Dev(); + + bool Populate(const PP_Ext_Alarms_Alarm_Dev& value); + + Var CreateVar() const; + + static const char* const kName; + static const char* const kScheduledTime; + static const char* const kPeriodInMinutes; + + DictField<std::string> name; + DictField<double> scheduled_time; + OptionalDictField<double> period_in_minutes; +}; + +class AlarmCreateInfo_Dev { + public: + AlarmCreateInfo_Dev(); + ~AlarmCreateInfo_Dev(); + + bool Populate(const PP_Ext_Alarms_AlarmCreateInfo_Dev& value); + + Var CreateVar() const; + + static const char* const kWhen; + static const char* const kDelayInMinutes; + static const char* const kPeriodInMinutes; + + OptionalDictField<double> when; + OptionalDictField<double> delay_in_minutes; + OptionalDictField<double> period_in_minutes; +}; + +// Functions ------------------------------------------------------------------- +class Alarms_Dev { + public: + explicit Alarms_Dev(const InstanceHandle& instance); + ~Alarms_Dev(); + + void Create(const Optional<std::string>& name, + const AlarmCreateInfo_Dev& alarm_info); + + typedef ExtCompletionCallbackWithOutput<Alarm_Dev> GetCallback; + int32_t Get(const Optional<std::string>& name, const GetCallback& callback); + + typedef ExtCompletionCallbackWithOutput<std::vector<Alarm_Dev> > + GetAllCallback; + int32_t GetAll(const GetAllCallback& callback); + + void Clear(const Optional<std::string>& name); + + void ClearAll(); + + private: + InstanceHandle instance_; +}; + +// Events ---------------------------------------------------------------------- +// Please see ppapi/cpp/extensions/event_base.h for how to use an event class. + +class OnAlarmEvent_Dev + : public internal::EventBase1<PP_Ext_Alarms_OnAlarm_Dev, Alarm_Dev> { + public: + class Listener { + public: + virtual ~Listener() {} + + virtual void OnAlarm(Alarm_Dev& alarm) = 0; + }; + + // |listener| is not owned by this instance and must outlive it. + OnAlarmEvent_Dev(const InstanceHandle& instance, Listener* listener); + virtual ~OnAlarmEvent_Dev(); + + private: + virtual void Callback(Alarm_Dev& alarm); + + Listener* listener_; +}; + +} // namespace alarms +} // namespace ext +} // namespace pp + +#endif // PPAPI_CPP_EXTENSIONS_DEV_ALARMS_DEV_H_ diff --git a/chromium/ppapi/cpp/extensions/dev/events_dev.cc b/chromium/ppapi/cpp/extensions/dev/events_dev.cc new file mode 100644 index 00000000000..d80008f2dc5 --- /dev/null +++ b/chromium/ppapi/cpp/extensions/dev/events_dev.cc @@ -0,0 +1,43 @@ +// Copyright (c) 2013 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 "ppapi/cpp/extensions/dev/events_dev.h" + +#include "ppapi/c/extensions/dev/ppb_ext_events_dev.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Ext_Events_Dev_0_1>() { + return PPB_EXT_EVENTS_DEV_INTERFACE_0_1; +} + +} // namespace + +namespace ext { +namespace events { + +// static +uint32_t Events_Dev::AddListener(PP_Instance instance, + const PP_Ext_EventListener& listener) { + if (!has_interface<PPB_Ext_Events_Dev_0_1>()) + return 0; + return get_interface<PPB_Ext_Events_Dev_0_1>()->AddListener(instance, + listener); +} + +// static +void Events_Dev::RemoveListener(PP_Instance instance, + uint32_t listener_id) { + if (has_interface<PPB_Ext_Events_Dev_0_1>()) { + get_interface<PPB_Ext_Events_Dev_0_1>()->RemoveListener(instance, + listener_id); + } +} + +} // namespace events +} // namespace ext +} // namespace pp diff --git a/chromium/ppapi/cpp/extensions/dev/events_dev.h b/chromium/ppapi/cpp/extensions/dev/events_dev.h new file mode 100644 index 00000000000..e816ca5fb8a --- /dev/null +++ b/chromium/ppapi/cpp/extensions/dev/events_dev.h @@ -0,0 +1,34 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_EXTENSIONS_DEV_EVENTS_DEV_H_ +#define PPAPI_CPP_EXTENSIONS_DEV_EVENTS_DEV_H_ + +#include "ppapi/c/pp_instance.h" +#include "ppapi/c/pp_stdint.h" + +struct PP_Ext_EventListener; + +namespace pp { +namespace ext { +namespace events { + +// This is a simple wrapper of the PPB_Ext_Events_Dev interface. +// +// Usually you don't have to directly use this interface. Instead, you could +// use those more object-oriented event classes. Please see +// ppapi/cpp/extensions/event_base.h for more details. +class Events_Dev { + public: + static uint32_t AddListener(PP_Instance instance, + const PP_Ext_EventListener& listener); + + static void RemoveListener(PP_Instance instance, uint32_t listener_id); +}; + +} // namespace events +} // namespace ext +} // namespace pp + +#endif // PPAPI_CPP_EXTENSIONS_DEV_EVENTS_DEV_H_ diff --git a/chromium/ppapi/cpp/extensions/dev/socket_dev.cc b/chromium/ppapi/cpp/extensions/dev/socket_dev.cc new file mode 100644 index 00000000000..a2c9e7f5ec1 --- /dev/null +++ b/chromium/ppapi/cpp/extensions/dev/socket_dev.cc @@ -0,0 +1,654 @@ +// Copyright (c) 2013 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 "ppapi/cpp/extensions/dev/socket_dev.h" + +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/extensions/optional.h" +#include "ppapi/cpp/extensions/to_var_converter.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Ext_Socket_Dev_0_2>() { + return PPB_EXT_SOCKET_DEV_INTERFACE_0_2; +} + +} // namespace + +namespace ext { +namespace socket { + +const char* const SocketType_Dev::kTcp = "tcp"; +const char* const SocketType_Dev::kUdp = "udp"; + +SocketType_Dev::SocketType_Dev() : value(NONE) { +} + +SocketType_Dev::SocketType_Dev(ValueType in_value) : value(in_value) { +} + +SocketType_Dev::~SocketType_Dev() { +} + +bool SocketType_Dev::Populate(const PP_Var& var_value) { + if (var_value.type != PP_VARTYPE_STRING) + return false; + + std::string string_value = Var(var_value).AsString(); + if (string_value == kTcp) { + value = TCP; + } else if (string_value == kUdp) { + value = UDP; + } else { + value = NONE; + return false; + } + return true; +} + +Var SocketType_Dev::CreateVar() const { + switch (value) { + case TCP: + return Var(kTcp); + case UDP: + return Var(kUdp); + default: + PP_NOTREACHED(); + return Var(std::string()); + } +} + +const char* const CreateInfo_Dev::kSocketId = "socketId"; + +CreateInfo_Dev::CreateInfo_Dev() + : socket_id(kSocketId) { +} + +CreateInfo_Dev::~CreateInfo_Dev() { +} + +bool CreateInfo_Dev::Populate(const PP_Ext_Socket_CreateInfo_Dev& value) { + if (value.type != PP_VARTYPE_DICTIONARY) + return false; + + VarDictionary dict(value); + bool result = socket_id.Populate(dict); + + return result; +} + +Var CreateInfo_Dev::CreateVar() const { + VarDictionary dict; + + bool result = socket_id.AddTo(&dict); + // Suppress unused variable warnings. + static_cast<void>(result); + PP_DCHECK(result); + + return dict; +} + +const char* const AcceptInfo_Dev::kResultCode = "resultCode"; +const char* const AcceptInfo_Dev::kSocketId = "socketId"; + +AcceptInfo_Dev::AcceptInfo_Dev() + : result_code(kResultCode), + socket_id(kSocketId) { +} + +AcceptInfo_Dev::~AcceptInfo_Dev() { +} + +bool AcceptInfo_Dev::Populate(const PP_Ext_Socket_AcceptInfo_Dev& value) { + if (value.type != PP_VARTYPE_DICTIONARY) + return false; + + VarDictionary dict(value); + bool result = result_code.Populate(dict); + result = socket_id.Populate(dict) && result; + + return result; +} + +Var AcceptInfo_Dev::CreateVar() const { + VarDictionary dict; + + bool result = result_code.AddTo(&dict); + result = socket_id.MayAddTo(&dict) && result; + PP_DCHECK(result); + + return dict; +} + +const char* const ReadInfo_Dev::kResultCode = "resultCode"; +const char* const ReadInfo_Dev::kData = "data"; + +ReadInfo_Dev::ReadInfo_Dev() + : result_code(kResultCode), + data(kData) { +} + +ReadInfo_Dev::~ReadInfo_Dev() { +} + +bool ReadInfo_Dev::Populate(const PP_Ext_Socket_ReadInfo_Dev& value) { + if (value.type != PP_VARTYPE_DICTIONARY) + return false; + + VarDictionary dict(value); + bool result = result_code.Populate(dict); + result = data.Populate(dict) && result; + + return result; +} + +Var ReadInfo_Dev::CreateVar() const { + VarDictionary dict; + + bool result = result_code.AddTo(&dict); + result = data.AddTo(&dict) && result; + PP_DCHECK(result); + + return dict; +} + +const char* const WriteInfo_Dev::kBytesWritten = "bytesWritten"; + +WriteInfo_Dev::WriteInfo_Dev() + : bytes_written(kBytesWritten) { +} + +WriteInfo_Dev::~WriteInfo_Dev() { +} + +bool WriteInfo_Dev::Populate(const PP_Ext_Socket_WriteInfo_Dev& value) { + if (value.type != PP_VARTYPE_DICTIONARY) + return false; + + VarDictionary dict(value); + bool result = bytes_written.Populate(dict); + + return result; +} + +Var WriteInfo_Dev::CreateVar() const { + VarDictionary dict; + + bool result = bytes_written.AddTo(&dict); + // Suppress unused variable warnings. + static_cast<void>(result); + PP_DCHECK(result); + + return dict; +} + +const char* const RecvFromInfo_Dev::kResultCode = "resultCode"; +const char* const RecvFromInfo_Dev::kData = "data"; +const char* const RecvFromInfo_Dev::kAddress = "address"; +const char* const RecvFromInfo_Dev::kPort = "port"; + +RecvFromInfo_Dev::RecvFromInfo_Dev() + : result_code(kResultCode), + data(kData), + address(kAddress), + port(kPort) { +} + +RecvFromInfo_Dev::~RecvFromInfo_Dev() { +} + +bool RecvFromInfo_Dev::Populate(const PP_Ext_Socket_RecvFromInfo_Dev& value) { + if (value.type != PP_VARTYPE_DICTIONARY) + return false; + + VarDictionary dict(value); + bool result = result_code.Populate(dict); + result = data.Populate(dict) && result; + result = address.Populate(dict) && result; + result = port.Populate(dict) && result; + + return result; +} + +Var RecvFromInfo_Dev::CreateVar() const { + VarDictionary dict; + + bool result = result_code.AddTo(&dict); + result = data.AddTo(&dict) && result; + result = address.AddTo(&dict) && result; + result = port.AddTo(&dict) && result; + PP_DCHECK(result); + + return dict; +} + +const char* const SocketInfo_Dev::kSocketType = "socketType"; +const char* const SocketInfo_Dev::kConnected = "connected"; +const char* const SocketInfo_Dev::kPeerAddress = "peerAddress"; +const char* const SocketInfo_Dev::kPeerPort = "peerPort"; +const char* const SocketInfo_Dev::kLocalAddress = "localAddress"; +const char* const SocketInfo_Dev::kLocalPort = "localPort"; + +SocketInfo_Dev::SocketInfo_Dev() + : socket_type(kSocketType), + connected(kConnected), + peer_address(kPeerAddress), + peer_port(kPeerPort), + local_address(kLocalAddress), + local_port(kLocalPort) { +} + +SocketInfo_Dev::~SocketInfo_Dev() { +} + +bool SocketInfo_Dev::Populate(const PP_Ext_Socket_SocketInfo_Dev& value) { + if (value.type != PP_VARTYPE_DICTIONARY) + return false; + + VarDictionary dict(value); + bool result = socket_type.Populate(dict); + result = connected.Populate(dict) && result; + result = peer_address.Populate(dict) && result; + result = peer_port.Populate(dict) && result; + result = local_address.Populate(dict) && result; + result = local_port.Populate(dict) && result; + + return result; +} + +Var SocketInfo_Dev::CreateVar() const { + VarDictionary dict; + + bool result = socket_type.AddTo(&dict); + result = connected.AddTo(&dict) && result; + result = peer_address.MayAddTo(&dict) && result; + result = peer_port.MayAddTo(&dict) && result; + result = local_address.MayAddTo(&dict) && result; + result = local_port.MayAddTo(&dict) && result; + PP_DCHECK(result); + + return dict; +} + +const char* const NetworkInterface_Dev::kName = "name"; +const char* const NetworkInterface_Dev::kAddress = "address"; + +NetworkInterface_Dev::NetworkInterface_Dev() + : name(kName), + address(kAddress) { +} + +NetworkInterface_Dev::~NetworkInterface_Dev() { +} + +bool NetworkInterface_Dev::Populate( + const PP_Ext_Socket_NetworkInterface_Dev& value) { + if (value.type != PP_VARTYPE_DICTIONARY) + return false; + + VarDictionary dict(value); + bool result = name.Populate(dict); + result = address.Populate(dict) && result; + + return result; +} + +Var NetworkInterface_Dev::CreateVar() const { + VarDictionary dict; + + bool result = name.AddTo(&dict); + result = address.AddTo(&dict) && result; + PP_DCHECK(result); + + return dict; +} + +Socket_Dev::Socket_Dev(const InstanceHandle& instance) : instance_(instance) { +} + +Socket_Dev::~Socket_Dev() { +} + +int32_t Socket_Dev::Create(const SocketType_Dev& type, + const Optional<CreateOptions_Dev>& options, + const CreateCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<SocketType_Dev> type_var(type); + internal::ToVarConverter<Optional<CreateOptions_Dev> > options_var(options); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->Create( + instance_.pp_instance(), + type_var.pp_var(), + options_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +void Socket_Dev::Destroy(int32_t socket_id) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return; + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->Destroy( + instance_.pp_instance(), + socket_id_var.pp_var()); +} + +int32_t Socket_Dev::Connect(int32_t socket_id, + const std::string& hostname, + int32_t port, + const ConnectCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<std::string> hostname_var(hostname); + internal::ToVarConverter<int32_t> port_var(port); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->Connect( + instance_.pp_instance(), + socket_id_var.pp_var(), + hostname_var.pp_var(), + port_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::Bind(int32_t socket_id, + const std::string& address, + int32_t port, + const BindCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<std::string> address_var(address); + internal::ToVarConverter<int32_t> port_var(port); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->Bind( + instance_.pp_instance(), + socket_id_var.pp_var(), + address_var.pp_var(), + port_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +void Socket_Dev::Disconnect(int32_t socket_id) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return; + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->Disconnect( + instance_.pp_instance(), + socket_id_var.pp_var()); +} + +int32_t Socket_Dev::Read(int32_t socket_id, + const Optional<int32_t>& buffer_size, + const ReadCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<Optional<int32_t> > buffer_size_var(buffer_size); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->Read( + instance_.pp_instance(), + socket_id_var.pp_var(), + buffer_size_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::Write(int32_t socket_id, + const VarArrayBuffer& data, + const WriteCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<Var> data_var(data); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->Write( + instance_.pp_instance(), + socket_id_var.pp_var(), + data_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::RecvFrom(int32_t socket_id, + const Optional<int32_t>& buffer_size, + const RecvFromCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<Optional<int32_t> > buffer_size_var(buffer_size); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->RecvFrom( + instance_.pp_instance(), + socket_id_var.pp_var(), + buffer_size_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::SendTo(int32_t socket_id, + const VarArrayBuffer& data, + const std::string& address, + int32_t port, + const SendToCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<Var> data_var(data); + internal::ToVarConverter<std::string> address_var(address); + internal::ToVarConverter<int32_t> port_var(port); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->SendTo( + instance_.pp_instance(), + socket_id_var.pp_var(), + data_var.pp_var(), + address_var.pp_var(), + port_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::Listen(int32_t socket_id, + const std::string& address, + int32_t port, + const Optional<int32_t>& backlog, + const ListenCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<std::string> address_var(address); + internal::ToVarConverter<int32_t> port_var(port); + internal::ToVarConverter<Optional<int32_t> > backlog_var(backlog); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->Listen( + instance_.pp_instance(), + socket_id_var.pp_var(), + address_var.pp_var(), + port_var.pp_var(), + backlog_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::Accept(int32_t socket_id, + const AcceptCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->Accept( + instance_.pp_instance(), + socket_id_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::SetKeepAlive(int32_t socket_id, + bool enable, + const Optional<int32_t>& delay, + const SetKeepAliveCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<bool> enable_var(enable); + internal::ToVarConverter<Optional<int32_t> > delay_var(delay); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->SetKeepAlive( + instance_.pp_instance(), + socket_id_var.pp_var(), + enable_var.pp_var(), + delay_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::SetNoDelay(int32_t socket_id, + bool no_delay, + const SetNoDelayCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<bool> no_delay_var(no_delay); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->SetNoDelay( + instance_.pp_instance(), + socket_id_var.pp_var(), + no_delay_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::GetInfo(int32_t socket_id, + const GetInfoCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->GetInfo( + instance_.pp_instance(), + socket_id_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::GetNetworkList(const GetNetworkListCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->GetNetworkList( + instance_.pp_instance(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::JoinGroup(int32_t socket_id, + const std::string& address, + const JoinGroupCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<std::string> address_var(address); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->JoinGroup( + instance_.pp_instance(), + socket_id_var.pp_var(), + address_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::LeaveGroup(int32_t socket_id, + const std::string& address, + const LeaveGroupCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<std::string> address_var(address); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->LeaveGroup( + instance_.pp_instance(), + socket_id_var.pp_var(), + address_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::SetMulticastTimeToLive( + int32_t socket_id, + int32_t ttl, + const SetMulticastTimeToLiveCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<int32_t> ttl_var(ttl); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->SetMulticastTimeToLive( + instance_.pp_instance(), + socket_id_var.pp_var(), + ttl_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::SetMulticastLoopbackMode( + int32_t socket_id, + bool enabled, + const SetMulticastLoopbackModeCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + internal::ToVarConverter<bool> enabled_var(enabled); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->SetMulticastLoopbackMode( + instance_.pp_instance(), + socket_id_var.pp_var(), + enabled_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +int32_t Socket_Dev::GetJoinedGroups(int32_t socket_id, + const GetJoinedGroupsCallback& callback) { + if (!has_interface<PPB_Ext_Socket_Dev_0_2>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + internal::ToVarConverter<int32_t> socket_id_var(socket_id); + + return get_interface<PPB_Ext_Socket_Dev_0_2>()->GetJoinedGroups( + instance_.pp_instance(), + socket_id_var.pp_var(), + callback.output(), + callback.pp_completion_callback()); +} + +} // namespace socket +} // namespace ext +} // namespace pp diff --git a/chromium/ppapi/cpp/extensions/dev/socket_dev.h b/chromium/ppapi/cpp/extensions/dev/socket_dev.h new file mode 100644 index 00000000000..b6ac7b58ad2 --- /dev/null +++ b/chromium/ppapi/cpp/extensions/dev/socket_dev.h @@ -0,0 +1,290 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_EXTENSIONS_DEV_SOCKET_DEV_H_ +#define PPAPI_CPP_EXTENSIONS_DEV_SOCKET_DEV_H_ + +#include <string> +#include <vector> + +#include "ppapi/c/extensions/dev/ppb_ext_socket_dev.h" +#include "ppapi/cpp/extensions/dict_field.h" +#include "ppapi/cpp/extensions/ext_output_traits.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/var_array_buffer.h" +#include "ppapi/cpp/var_dictionary.h" + +namespace pp { +namespace ext { + +template <class T> +class ExtCompletionCallbackWithOutput; + +template <class T> +class Optional; + +namespace socket { + +// Data types ------------------------------------------------------------------ +class SocketType_Dev { + public: + enum ValueType { + NONE, + TCP, + UDP + }; + + SocketType_Dev(); + SocketType_Dev(ValueType in_value); + ~SocketType_Dev(); + + bool Populate(const PP_Var& var_value); + + Var CreateVar() const; + + ValueType value; + + static const char* const kTcp; + static const char* const kUdp; +}; + +typedef VarDictionary CreateOptions_Dev; + +class CreateInfo_Dev { + public: + CreateInfo_Dev(); + ~CreateInfo_Dev(); + + bool Populate(const PP_Ext_Socket_CreateInfo_Dev& value); + + Var CreateVar() const; + + static const char* const kSocketId; + + DictField<int32_t> socket_id; +}; + +class AcceptInfo_Dev { + public: + AcceptInfo_Dev(); + ~AcceptInfo_Dev(); + + bool Populate(const PP_Ext_Socket_AcceptInfo_Dev& value); + + Var CreateVar() const; + + static const char* const kResultCode; + static const char* const kSocketId; + + DictField<int32_t> result_code; + OptionalDictField<int32_t> socket_id; +}; + +class ReadInfo_Dev { + public: + ReadInfo_Dev(); + ~ReadInfo_Dev(); + + bool Populate(const PP_Ext_Socket_ReadInfo_Dev& value); + + Var CreateVar() const; + + static const char* const kResultCode; + static const char* const kData; + + DictField<int32_t> result_code; + DictField<VarArrayBuffer> data; +}; + +class WriteInfo_Dev { + public: + WriteInfo_Dev(); + ~WriteInfo_Dev(); + + bool Populate(const PP_Ext_Socket_WriteInfo_Dev& value); + + Var CreateVar() const; + + static const char* const kBytesWritten; + + DictField<int32_t> bytes_written; +}; + +class RecvFromInfo_Dev { + public: + RecvFromInfo_Dev(); + ~RecvFromInfo_Dev(); + + bool Populate(const PP_Ext_Socket_RecvFromInfo_Dev& value); + + Var CreateVar() const; + + static const char* const kResultCode; + static const char* const kData; + static const char* const kAddress; + static const char* const kPort; + + DictField<int32_t> result_code; + DictField<VarArrayBuffer> data; + DictField<std::string> address; + DictField<int32_t> port; +}; + +class SocketInfo_Dev { + public: + SocketInfo_Dev(); + ~SocketInfo_Dev(); + + bool Populate(const PP_Ext_Socket_SocketInfo_Dev& value); + + Var CreateVar() const; + + static const char* const kSocketType; + static const char* const kConnected; + static const char* const kPeerAddress; + static const char* const kPeerPort; + static const char* const kLocalAddress; + static const char* const kLocalPort; + + DictField<SocketType_Dev> socket_type; + DictField<bool> connected; + OptionalDictField<std::string> peer_address; + OptionalDictField<int32_t> peer_port; + OptionalDictField<std::string> local_address; + OptionalDictField<int32_t> local_port; +}; + +class NetworkInterface_Dev { + public: + NetworkInterface_Dev(); + ~NetworkInterface_Dev(); + + bool Populate(const PP_Ext_Socket_NetworkInterface_Dev& value); + + Var CreateVar() const; + + static const char* const kName; + static const char* const kAddress; + + DictField<std::string> name; + DictField<std::string> address; +}; + +// Functions ------------------------------------------------------------------- +class Socket_Dev { + public: + explicit Socket_Dev(const InstanceHandle& instance); + ~Socket_Dev(); + + typedef ExtCompletionCallbackWithOutput<CreateInfo_Dev> CreateCallback; + int32_t Create(const SocketType_Dev& type, + const Optional<CreateOptions_Dev>& options, + const CreateCallback& callback); + + void Destroy(int32_t socket_id); + + typedef ExtCompletionCallbackWithOutput<int32_t> ConnectCallback; + int32_t Connect(int32_t socket_id, + const std::string& hostname, + int32_t port, + const ConnectCallback& callback); + + typedef ExtCompletionCallbackWithOutput<int32_t> BindCallback; + int32_t Bind(int32_t socket_id, + const std::string& address, + int32_t port, + const BindCallback& callback); + + void Disconnect(int32_t socket_id); + + typedef ExtCompletionCallbackWithOutput<ReadInfo_Dev> ReadCallback; + int32_t Read(int32_t socket_id, + const Optional<int32_t>& buffer_size, + const ReadCallback& callback); + + typedef ExtCompletionCallbackWithOutput<WriteInfo_Dev> WriteCallback; + int32_t Write(int32_t socket_id, + const VarArrayBuffer& data, + const WriteCallback& callback); + + typedef ExtCompletionCallbackWithOutput<RecvFromInfo_Dev> RecvFromCallback; + int32_t RecvFrom(int32_t socket_id, + const Optional<int32_t>& buffer_size, + const RecvFromCallback& callback); + + typedef ExtCompletionCallbackWithOutput<WriteInfo_Dev> SendToCallback; + int32_t SendTo(int32_t socket_id, + const VarArrayBuffer& data, + const std::string& address, + int32_t port, + const SendToCallback& callback); + + typedef ExtCompletionCallbackWithOutput<int32_t> ListenCallback; + int32_t Listen(int32_t socket_id, + const std::string& address, + int32_t port, + const Optional<int32_t>& backlog, + const ListenCallback& callback); + + typedef ExtCompletionCallbackWithOutput<AcceptInfo_Dev> AcceptCallback; + int32_t Accept(int32_t socket_id, const AcceptCallback& callback); + + typedef ExtCompletionCallbackWithOutput<bool> SetKeepAliveCallback; + int32_t SetKeepAlive(int32_t socket_id, + bool enable, + const Optional<int32_t>& delay, + const SetKeepAliveCallback& callback); + + typedef ExtCompletionCallbackWithOutput<bool> SetNoDelayCallback; + int32_t SetNoDelay(int32_t socket_id, + bool no_delay, + const SetNoDelayCallback& callback); + + typedef ExtCompletionCallbackWithOutput<SocketInfo_Dev> GetInfoCallback; + int32_t GetInfo(int32_t socket_id, + const GetInfoCallback& callback); + + typedef ExtCompletionCallbackWithOutput<std::vector<NetworkInterface_Dev> > + GetNetworkListCallback; + int32_t GetNetworkList(const GetNetworkListCallback& callback); + + typedef ExtCompletionCallbackWithOutput<int32_t> JoinGroupCallback; + int32_t JoinGroup(int32_t socket_id, + const std::string& address, + const JoinGroupCallback& callback); + + typedef ExtCompletionCallbackWithOutput<int32_t> LeaveGroupCallback; + int32_t LeaveGroup(int32_t socket_id, + const std::string& address, + const LeaveGroupCallback& callback); + + typedef ExtCompletionCallbackWithOutput<int32_t> + SetMulticastTimeToLiveCallback; + int32_t SetMulticastTimeToLive( + int32_t socket_id, + int32_t ttl, + const SetMulticastTimeToLiveCallback& callback); + + typedef ExtCompletionCallbackWithOutput<int32_t> + SetMulticastLoopbackModeCallback; + int32_t SetMulticastLoopbackMode( + int32_t socket_id, + bool enabled, + const SetMulticastLoopbackModeCallback& callback); + + typedef ExtCompletionCallbackWithOutput<std::vector<std::string> > + GetJoinedGroupsCallback; + int32_t GetJoinedGroups(int32_t socket_id, + const GetJoinedGroupsCallback& callback); + + private: + InstanceHandle instance_; +}; + +} // namespace socket +} // namespace ext +} // namespace pp + +#endif // PPAPI_CPP_EXTENSIONS_DEV_SOCKET_DEV_H_ diff --git a/chromium/ppapi/cpp/extensions/dict_field.h b/chromium/ppapi/cpp/extensions/dict_field.h new file mode 100644 index 00000000000..f332014e897 --- /dev/null +++ b/chromium/ppapi/cpp/extensions/dict_field.h @@ -0,0 +1,100 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_EXTENSIONS_DICT_FIELD_H_ +#define PPAPI_CPP_EXTENSIONS_DICT_FIELD_H_ + +#include <string> + +#include "ppapi/c/pp_bool.h" +#include "ppapi/cpp/extensions/from_var_converter.h" +#include "ppapi/cpp/extensions/optional.h" +#include "ppapi/cpp/extensions/to_var_converter.h" +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/var_dictionary.h" + +namespace pp { +namespace ext { + +template <class T> +class DictField { + public: + explicit DictField(const std::string& key) : key_(key), value_() { + } + + ~DictField() { + } + + const std::string& key() const { return key_; } + + // Returns the value. + T& operator()() { return value_; } + const T& operator()() const { return value_; } + + // Adds this field to the dictionary var. + bool AddTo(VarDictionary* dict) const { + if (!dict) + return false; + + internal::ToVarConverter<T> converter(value_); + return dict->Set(Var(key_), converter.var()); + } + + bool Populate(const VarDictionary& dict) { + Var value_var = dict.Get(Var(key_)); + if (value_var.is_undefined()) + return false; + + internal::FromVarConverter<T> converter(value_var.pp_var()); + value_ = converter.value(); + return true; + } + + private: + std::string key_; + T value_; +}; + +template <class T> +class OptionalDictField { + public: + explicit OptionalDictField(const std::string& key) : key_(key) { + } + + ~OptionalDictField() { + } + + const std::string& key() const { return key_; } + + // Returns the value. + Optional<T>& operator()() { return value_; } + const Optional<T>& operator()() const { return value_; } + + // Adds this field to the dictionary var, if |value| has been set. + bool MayAddTo(VarDictionary* dict) const { + if (!dict) + return false; + if (!value_.IsSet()) + return true; + + internal::ToVarConverter<T> converter(*value_); + return dict->Set(Var(key_), converter.var()); + } + + bool Populate(const VarDictionary& dict) { + Var value_var = dict.Get(Var(key_)); + internal::FromVarConverter<Optional<T> > converter(value_var.pp_var()); + value_.Swap(&converter.value()); + return true; + } + + private: + std::string key_; + Optional<T> value_; +}; + +} // namespace ext +} // namespace pp + +#endif // PPAPI_CPP_EXTENSIONS_DICT_FIELD_H_ diff --git a/chromium/ppapi/cpp/extensions/event_base.cc b/chromium/ppapi/cpp/extensions/event_base.cc new file mode 100644 index 00000000000..210b213d0e3 --- /dev/null +++ b/chromium/ppapi/cpp/extensions/event_base.cc @@ -0,0 +1,44 @@ +// Copyright (c) 2013 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 "ppapi/cpp/extensions/event_base.h" + +#include "ppapi/cpp/extensions/dev/events_dev.h" + +namespace pp { +namespace ext { +namespace internal { + +GenericEventBase::GenericEventBase( + const InstanceHandle& instance, + const PP_Ext_EventListener& pp_listener) + : instance_(instance), + listener_id_(0), + pp_listener_(pp_listener) { +} + +GenericEventBase::~GenericEventBase() { + StopListening(); +} + +bool GenericEventBase::StartListening() { + if (IsListening()) + return true; + + listener_id_ = events::Events_Dev::AddListener(instance_.pp_instance(), + pp_listener_); + return IsListening(); +} + +void GenericEventBase::StopListening() { + if (!IsListening()) + return; + + events::Events_Dev::RemoveListener(instance_.pp_instance(), listener_id_); + listener_id_ = 0; +} + +} // namespace internal +} // namespace ext +} // namespace pp diff --git a/chromium/ppapi/cpp/extensions/event_base.h b/chromium/ppapi/cpp/extensions/event_base.h new file mode 100644 index 00000000000..75144c0d8b1 --- /dev/null +++ b/chromium/ppapi/cpp/extensions/event_base.h @@ -0,0 +1,232 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_EXTENSIONS_EVENT_BASE_H_ +#define PPAPI_CPP_EXTENSIONS_EVENT_BASE_H_ + +#include "ppapi/c/extensions/dev/ppb_ext_events_dev.h" +#include "ppapi/c/pp_macros.h" +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/pp_var.h" +#include "ppapi/cpp/extensions/from_var_converter.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/logging.h" + +namespace pp { +namespace ext { +namespace internal { + +// This file contains base classes for events. Usually you don't need to use +// them directly. +// +// For each event type, there is a corresponding event class derived from +// EventBase[0-3]. The event class defines a Listener interface and exposes the +// public methods of GenericEventBase. +// +// Take pp::ext::alarms::OnAlarmEvent_Dev as example, your code to listen to the +// event would look like this: +// +// class MyListener : public pp::ext::alarms::OnAlarmEvent_Dev { +// ... +// // The parameter is a non-const reference so you could directly modify it +// // if necessary. +// virtual void OnAlarm(Alarm_Dev& alarm) { +// ...handle the event... +// } +// }; +// +// MyListener on_alarm_listener; +// // The listener is not owned by the event and must outlive it. +// pp::ext::alarms::OnAlarmEvent_Dev on_alarm(instance, &on_alarm_listener); +// on_alarm.StartListening(); +// ... +// // It is guaranteed that |on_alarm_listener| won't get called after +// // |on_alarm| goes away. So this step is optional. +// on_alarm.StopListening(); + +class GenericEventBase { + public: + bool StartListening(); + void StopListening(); + + bool IsListening() const { return listener_id_ != 0; } + uint32_t listener_id() const { return listener_id_; } + + protected: + GenericEventBase(const InstanceHandle& instance, + const PP_Ext_EventListener& pp_listener); + ~GenericEventBase(); + + InstanceHandle instance_; + uint32_t listener_id_; + const PP_Ext_EventListener pp_listener_; + + private: + // Disallow copying and assignment. + GenericEventBase(const GenericEventBase&); + GenericEventBase& operator=(const GenericEventBase&); +}; + +// EventBase[0-3] are event base classes which can be instantiated with a +// pointer to a PP_Ext_EventListener creation function and the input parameter +// types of the listener callback. +// +// For example, EvenBase1<PP_Ext_Alarms_OnAlarm_Dev, Alarm_Dev> deals with +// the event type defined by the PP_Ext_Alarms_OnAlarm_Dev function pointer. And +// it defines a pure virtual method as the listener callback: +// virtual void Callback(Alarm_Dev&) = 0; + +typedef PP_Ext_EventListener (*CreatePPEventListener0)( + void (*)(uint32_t, void*), void*); +template <const CreatePPEventListener0 kCreatePPEventListener0> +class EventBase0 : public GenericEventBase { + public: + explicit EventBase0(const InstanceHandle& instance) + : PP_ALLOW_THIS_IN_INITIALIZER_LIST( + GenericEventBase(instance, + kCreatePPEventListener0(&CallbackThunk, this))) { + } + + virtual ~EventBase0() {} + + private: + virtual void Callback() = 0; + + static void CallbackThunk(uint32_t listener_id, void* user_data) { + EventBase0<kCreatePPEventListener0>* event_base = + static_cast<EventBase0<kCreatePPEventListener0>*>(user_data); + PP_DCHECK(listener_id == event_base->listener_id_); + // Suppress unused variable warnings. + static_cast<void>(listener_id); + + event_base->Callback(); + } + + // Disallow copying and assignment. + EventBase0(const EventBase0<kCreatePPEventListener0>&); + EventBase0<kCreatePPEventListener0>& operator=( + const EventBase0<kCreatePPEventListener0>&); +}; + +typedef PP_Ext_EventListener (*CreatePPEventListener1)( + void (*)(uint32_t, void*, PP_Var), void*); +template <const CreatePPEventListener1 kCreatePPEventListener1, class A> +class EventBase1 : public GenericEventBase { + public: + explicit EventBase1(const InstanceHandle& instance) + : PP_ALLOW_THIS_IN_INITIALIZER_LIST( + GenericEventBase(instance, + kCreatePPEventListener1(&CallbackThunk, this))) { + } + + virtual ~EventBase1() {} + + private: + virtual void Callback(A&) = 0; + + static void CallbackThunk(uint32_t listener_id, + void* user_data, + PP_Var var_a) { + EventBase1<kCreatePPEventListener1, A>* event_base = + static_cast<EventBase1<kCreatePPEventListener1, A>*>(user_data); + PP_DCHECK(listener_id == event_base->listener_id_); + // Suppress unused variable warnings. + static_cast<void>(listener_id); + + FromVarConverter<A> a(var_a); + event_base->Callback(a.value()); + } + + // Disallow copying and assignment. + EventBase1(const EventBase1<kCreatePPEventListener1, A>&); + EventBase1<kCreatePPEventListener1, A>& operator=( + const EventBase1<kCreatePPEventListener1, A>&); +}; + +typedef PP_Ext_EventListener (*CreatePPEventListener2)( + void (*)(uint32_t, void*, PP_Var, PP_Var), void*); +template <const CreatePPEventListener2 kCreatePPEventListener2, + class A, + class B> +class EventBase2 : public GenericEventBase { + public: + explicit EventBase2(const InstanceHandle& instance) + : PP_ALLOW_THIS_IN_INITIALIZER_LIST( + GenericEventBase(instance, + kCreatePPEventListener2(&CallbackThunk, this))) { + } + + virtual ~EventBase2() {} + + private: + virtual void Callback(A&, B&) = 0; + + static void CallbackThunk(uint32_t listener_id, + void* user_data, + PP_Var var_a, + PP_Var var_b) { + EventBase2<kCreatePPEventListener2, A, B>* event_base = + static_cast<EventBase2<kCreatePPEventListener2, A, B>*>(user_data); + PP_DCHECK(listener_id == event_base->listener_id_); + // Suppress unused variable warnings. + static_cast<void>(listener_id); + + FromVarConverter<A> a(var_a); + FromVarConverter<B> b(var_b); + event_base->Callback(a.value(), b.value()); + } + + // Disallow copying and assignment. + EventBase2(const EventBase2<kCreatePPEventListener2, A, B>&); + EventBase2<kCreatePPEventListener2, A, B>& operator=( + const EventBase2<kCreatePPEventListener2, A, B>&); +}; + +typedef PP_Ext_EventListener (*CreatePPEventListener3)( + void (*)(uint32_t, void*, PP_Var, PP_Var, PP_Var), void*); +template <const CreatePPEventListener3 kCreatePPEventListener3, + class A, + class B, + class C> +class EventBase3 : public GenericEventBase { + public: + explicit EventBase3(const InstanceHandle& instance) + : PP_ALLOW_THIS_IN_INITIALIZER_LIST( + GenericEventBase(instance, + kCreatePPEventListener3(&CallbackThunk, this))) { + } + + virtual ~EventBase3() {} + + private: + virtual void Callback(A&, B&, C&) = 0; + + static void CallbackThunk(uint32_t listener_id, + void* user_data, + PP_Var var_a, + PP_Var var_b, + PP_Var var_c) { + EventBase3<kCreatePPEventListener3, A, B, C>* event_base = + static_cast<EventBase3<kCreatePPEventListener3, A, B, C>*>(user_data); + PP_DCHECK(listener_id == event_base->listener_id_); + // Suppress unused variable warnings. + static_cast<void>(listener_id); + + FromVarConverter<A> a(var_a); + FromVarConverter<B> b(var_b); + FromVarConverter<C> c(var_c); + event_base->Callback(a.value(), b.value(), c.value()); + } + + // Disallow copying and assignment. + EventBase3(const EventBase3<kCreatePPEventListener3, A, B, C>&); + EventBase3<kCreatePPEventListener3, A, B, C>& operator=( + const EventBase3<kCreatePPEventListener3, A, B, C>&); +}; + +} // namespace internal +} // namespace ext +} // namespace pp + +#endif // PPAPI_CPP_EXTENSIONS_EVENT_BASE_H_ diff --git a/chromium/ppapi/cpp/extensions/ext_output_traits.h b/chromium/ppapi/cpp/extensions/ext_output_traits.h new file mode 100644 index 00000000000..ed57be10d98 --- /dev/null +++ b/chromium/ppapi/cpp/extensions/ext_output_traits.h @@ -0,0 +1,142 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_EXTENSIONS_OUTPUT_TRAITS_H_ +#define PPAPI_CPP_EXTENSIONS_OUTPUT_TRAITS_H_ + +#include <vector> + +#include "ppapi/c/pp_var.h" +#include "ppapi/cpp/extensions/from_var_converter.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/var_array.h" + +namespace pp { +namespace ext { +namespace internal { + +template <class T> +class VarOutputAdapterWithStorage { + public: + VarOutputAdapterWithStorage() : pp_var_(PP_MakeUndefined()) { + } + + ~VarOutputAdapterWithStorage() { + PP_DCHECK(pp_var_.type == PP_VARTYPE_UNDEFINED); + } + + PP_Var& pp_var() { return pp_var_; } + + T& output() { + Var auto_release(PASS_REF, pp_var_); + converter_.Set(pp_var_); + pp_var_ = PP_MakeUndefined(); + return converter_.value(); + } + + private: + PP_Var pp_var_; + FromVarConverter<T> converter_; + + // Disallow copying and assignment. + VarOutputAdapterWithStorage(const VarOutputAdapterWithStorage<T>&); + VarOutputAdapterWithStorage<T>& operator=( + const VarOutputAdapterWithStorage<T>&); +}; + +// ExtCallbackOutputTraits is used with ExtCompletionCallbackWithOutput. Unlike +// pp::internal::CallbackOutputTraits, it always uses PP_Var* as output +// parameter type to interact with the browser. +// +// For example, CompletionCallbackWithOutput<double> (using +// pp::internal::CallbackOutputTraits) uses double* as the output parameter +// type; while ExtCompletionCallbackWithOutput<double> uses PP_Var*. +template <class T> +struct ExtCallbackOutputTraits { + typedef PP_Var* APIArgType; + typedef VarOutputAdapterWithStorage<T> StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return &t.pp_var(); + } + + // This must be called exactly once to consume the one PP_Var reference + // assigned to us by the browser. + static inline T& StorageToPluginArg(StorageType& t) { + return t.output(); + } + + static inline void Initialize(StorageType* /* t */) {} +}; + +// This class provides storage for a PP_Var and a vector of objects which are +// of type T. The PP_Var is used as an output parameter to receive an array var +// from the browser. Each element in the array var is converted to a T object, +// using FromVarConverter, and stores in the vector. +template <class T> +class ArrayVarOutputAdapterWithStorage { + public: + ArrayVarOutputAdapterWithStorage() : pp_var_(PP_MakeUndefined()) { + } + + ~ArrayVarOutputAdapterWithStorage() { + PP_DCHECK(pp_var_.type == PP_VARTYPE_UNDEFINED); + } + + PP_Var& pp_var() { return pp_var_; } + + std::vector<T>& output() { + PP_DCHECK(output_storage_.empty()); + + Var var(PASS_REF, pp_var_); + pp_var_ = PP_MakeUndefined(); + if (var.is_array()) { + VarArray array(var); + + uint32_t length = array.GetLength(); + output_storage_.reserve(length); + for (uint32_t i = 0; i < length; ++i) { + FromVarConverter<T> converter(array.Get(i).pp_var()); + output_storage_.push_back(converter.value()); + } + } + + return output_storage_; + } + + private: + PP_Var pp_var_; + std::vector<T> output_storage_; + + // Disallow copying and assignment. + ArrayVarOutputAdapterWithStorage(const ArrayVarOutputAdapterWithStorage<T>&); + ArrayVarOutputAdapterWithStorage<T>& operator=( + const ArrayVarOutputAdapterWithStorage<T>&); +}; + +template <class T> +struct ExtCallbackOutputTraits< std::vector<T> > { + typedef PP_Var* APIArgType; + typedef ArrayVarOutputAdapterWithStorage<T> StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return &t.pp_var(); + } + + // This must be called exactly once to consume the one PP_Var reference + // assigned to us by the browser. + static inline std::vector<T>& StorageToPluginArg(StorageType& t) { + return t.output(); + } + + static inline void Initialize(StorageType* /* t */) {} +}; + +} // namespace internal +} // namespace ext +} // namespace pp + +#endif // PPAPI_CPP_EXTENSIONS_OUTPUT_TRAITS_H_ diff --git a/chromium/ppapi/cpp/extensions/from_var_converter.h b/chromium/ppapi/cpp/extensions/from_var_converter.h new file mode 100644 index 00000000000..06ae0df2501 --- /dev/null +++ b/chromium/ppapi/cpp/extensions/from_var_converter.h @@ -0,0 +1,236 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_EXTENSIONS_FROM_VAR_CONVERTOR_H_ +#define PPAPI_CPP_EXTENSIONS_FROM_VAR_CONVERTOR_H_ + +#include <string> + +#include "ppapi/c/pp_var.h" +#include "ppapi/cpp/extensions/optional.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/var_array.h" +#include "ppapi/cpp/var_array_buffer.h" +#include "ppapi/cpp/var_dictionary.h" + +namespace pp { +namespace ext { +namespace internal { + +template <class T> +class FromVarConverterBase { + public: + T& value() { return value_; } + + protected: + FromVarConverterBase() : value_() { + } + + explicit FromVarConverterBase(const T& value) : value_(value) { + } + + ~FromVarConverterBase() { + } + + T value_; +}; + +template <class T> +class FromVarConverter : public FromVarConverterBase<T> { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + bool succeeded = FromVarConverterBase<T>::value_.Populate(var); + // Suppress unused variable warnings. + static_cast<void>(succeeded); + PP_DCHECK(succeeded); + } +}; + +template <class T> +class FromVarConverter<Optional<T> > + : public FromVarConverterBase<Optional<T> > { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + if (var.type == PP_VARTYPE_UNDEFINED) { + FromVarConverterBase<Optional<T> >::value_.Reset(); + } else { + FromVarConverter<T> converter(var); + FromVarConverterBase<Optional<T> >::value_ = converter.value(); + } + } +}; + +template <> +class FromVarConverter<bool> : public FromVarConverterBase<bool> { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + FromVarConverterBase<bool>::value_ = Var(var).AsBool(); + } +}; + +template <> +class FromVarConverter<int32_t> : public FromVarConverterBase<int32_t> { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + FromVarConverterBase<int32_t>::value_ = Var(var).AsInt(); + } +}; + +template <> +class FromVarConverter<double> : public FromVarConverterBase<double> { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + FromVarConverterBase<double>::value_ = Var(var).AsDouble(); + } +}; + +template <> +class FromVarConverter<std::string> : public FromVarConverterBase<std::string> { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + FromVarConverterBase<std::string>::value_ = Var(var).AsString(); + } +}; + +template <> +class FromVarConverter<Var> : public FromVarConverterBase<Var> { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + FromVarConverterBase<Var>::value_ = Var(var); + } +}; + +template <> +class FromVarConverter<VarArray> + : public FromVarConverterBase<VarArray> { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + FromVarConverterBase<VarArray>::value_ = Var(var); + } +}; + +template <> +class FromVarConverter<VarDictionary> + : public FromVarConverterBase<VarDictionary> { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + FromVarConverterBase<VarDictionary>::value_ = Var(var); + } +}; + +template <> +class FromVarConverter<VarArrayBuffer> + : public FromVarConverterBase<VarArrayBuffer> { + public: + FromVarConverter() { + } + + explicit FromVarConverter(const PP_Var& var) { + Set(var); + } + + ~FromVarConverter() { + } + + void Set(const PP_Var& var) { + FromVarConverterBase<VarArrayBuffer>::value_ = Var(var); + } +}; + +} // namespace internal +} // namespace ext +} // namespace pp + +#endif // PPAPI_CPP_EXTENSIONS_FROM_VAR_CONVERTOR_H_ diff --git a/chromium/ppapi/cpp/extensions/optional.h b/chromium/ppapi/cpp/extensions/optional.h new file mode 100644 index 00000000000..fdef839aa1c --- /dev/null +++ b/chromium/ppapi/cpp/extensions/optional.h @@ -0,0 +1,97 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_EXTENSIONS_OPTIONAL_H_ +#define PPAPI_CPP_EXTENSIONS_OPTIONAL_H_ + +namespace pp { +namespace ext { + +template <class T> +class Optional { + public: + Optional() : value_(NULL) { + } + // Takes ownership of |value|. + explicit Optional(T* value) : value_(value) { + } + Optional(const T& value) : value_(new T(value)) { + } + Optional(const Optional<T>& other) + : value_(other.value_ ? new T(*other.value_) : NULL) { + } + + ~Optional() { + Reset(); + } + + Optional<T>& operator=(const T& other) { + if (value_ == &other) + return *this; + + Reset(); + value_ = new T(other); + + return *this; + } + + Optional<T>& operator=(const Optional<T>& other) { + if (value_ == other.value_) + return *this; + + Reset(); + if (other.value_) + value_ = new T(*other.value_); + + return *this; + } + + bool IsSet() const { + return !!value_; + } + + T* Get() const { + return value_; + } + + // Should only be used when IsSet() is true. + T& operator*() const { + return *value_; + } + + // Should only be used when IsSet() is true. + T* operator->() const { + PP_DCHECK(value_); + return value_; + } + + // Takes ownership of |value|. + void Set(T* value) { + if (value == value_) + return; + + Reset(); + *value_ = value; + } + + void Reset() { + T* value = value_; + value_ = NULL; + delete value; + } + + void Swap(Optional<T>* other) { + T* temp = value_; + value_ = other->value_; + other->value_ = temp; + } + + private: + T* value_; +}; + +} // namespace ext +} // namespace pp + +#endif // PPAPI_CPP_EXTENSIONS_OPTIONAL_H_ diff --git a/chromium/ppapi/cpp/extensions/to_var_converter.h b/chromium/ppapi/cpp/extensions/to_var_converter.h new file mode 100644 index 00000000000..e38499977fb --- /dev/null +++ b/chromium/ppapi/cpp/extensions/to_var_converter.h @@ -0,0 +1,156 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_EXTENSIONS_TO_VAR_CONVERTOR_H_ +#define PPAPI_CPP_EXTENSIONS_TO_VAR_CONVERTOR_H_ + +#include <string> + +#include "ppapi/c/pp_var.h" +#include "ppapi/cpp/extensions/optional.h" +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/var_array.h" +#include "ppapi/cpp/var_array_buffer.h" +#include "ppapi/cpp/var_dictionary.h" + +namespace pp { +namespace ext { +namespace internal { + +class ToVarConverterBase { + public: + PP_Var pp_var() const { + return var_.pp_var(); + } + + const Var& var() const { + return var_; + } + + protected: + ToVarConverterBase() { + } + + explicit ToVarConverterBase(const PP_Var& var) : var_(var) { + } + + explicit ToVarConverterBase(const Var& var): var_(var) { + } + + ~ToVarConverterBase() { + } + + Var var_; +}; + +template <class T> +class ToVarConverter : public ToVarConverterBase { + public: + explicit ToVarConverter(const T& object) + : ToVarConverterBase(object.CreateVar()) { + } + + ~ToVarConverter() { + } +}; + +template <class T> +class ToVarConverter<Optional<T> > : public ToVarConverterBase { + public: + explicit ToVarConverter(const Optional<T>& object) + : ToVarConverterBase( + object.IsSet() ? ToVarConverter<T>(*object).pp_var() : + PP_MakeUndefined()) { + } + + ~ToVarConverter() { + } +}; + +template <> +class ToVarConverter<bool> : public ToVarConverterBase { + public: + explicit ToVarConverter(bool object) : ToVarConverterBase(Var(object)) { + } + + ~ToVarConverter() { + } +}; + +template <> +class ToVarConverter<int32_t> : public ToVarConverterBase { + public: + explicit ToVarConverter(int32_t object) : ToVarConverterBase(Var(object)) { + } + + ~ToVarConverter() { + } +}; + +template <> +class ToVarConverter<double> : public ToVarConverterBase { + public: + explicit ToVarConverter(double object) : ToVarConverterBase(Var(object)) { + } + + ~ToVarConverter() { + } +}; + +template <> +class ToVarConverter<std::string> : public ToVarConverterBase { + public: + explicit ToVarConverter(const std::string& object) + : ToVarConverterBase(Var(object)) { + } + + ~ToVarConverter() { + } +}; + +template <> +class ToVarConverter<Var> : public ToVarConverterBase { + public: + explicit ToVarConverter(const Var& object) : ToVarConverterBase(object) { + } + + ~ToVarConverter() { + } +}; + +template <> +class ToVarConverter<VarArray> : public ToVarConverterBase { + public: + explicit ToVarConverter(const Var& object) : ToVarConverterBase(object) { + } + + ~ToVarConverter() { + } +}; + +template <> +class ToVarConverter<VarDictionary> : public ToVarConverterBase { + public: + explicit ToVarConverter(const Var& object) : ToVarConverterBase(object) { + } + + ~ToVarConverter() { + } +}; + +template <> +class ToVarConverter<VarArrayBuffer> : public ToVarConverterBase { + public: + explicit ToVarConverter(const Var& object) : ToVarConverterBase(object) { + } + + ~ToVarConverter() { + } +}; + +} // namespace internal +} // namespace ext +} // namespace pp + +#endif // PPAPI_CPP_EXTENSIONS_TO_VAR_CONVERTOR_H_ diff --git a/chromium/ppapi/cpp/file_io.cc b/chromium/ppapi/cpp/file_io.cc new file mode 100644 index 00000000000..faaf2846f75 --- /dev/null +++ b/chromium/ppapi/cpp/file_io.cc @@ -0,0 +1,195 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/file_io.h" + +#include <string.h> // memcpy + +#include "ppapi/c/ppb_file_io.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/dev/resource_array_dev.h" +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_FileIO_1_0>() { + return PPB_FILEIO_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_FileIO_1_1>() { + return PPB_FILEIO_INTERFACE_1_1; +} + +} // namespace + +FileIO::FileIO() { +} + +FileIO::FileIO(const InstanceHandle& instance) { + if (has_interface<PPB_FileIO_1_1>()) { + PassRefFromConstructor(get_interface<PPB_FileIO_1_1>()->Create( + instance.pp_instance())); + } else if (has_interface<PPB_FileIO_1_0>()) { + PassRefFromConstructor(get_interface<PPB_FileIO_1_0>()->Create( + instance.pp_instance())); + } +} + +FileIO::FileIO(const FileIO& other) + : Resource(other) { +} + +int32_t FileIO::Open(const FileRef& file_ref, + int32_t open_flags, + const CompletionCallback& cc) { + if (has_interface<PPB_FileIO_1_1>()) { + return get_interface<PPB_FileIO_1_1>()->Open( + pp_resource(), file_ref.pp_resource(), open_flags, + cc.pp_completion_callback()); + } else if (has_interface<PPB_FileIO_1_0>()) { + return get_interface<PPB_FileIO_1_0>()->Open( + pp_resource(), file_ref.pp_resource(), open_flags, + cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileIO::Query(PP_FileInfo* result_buf, + const CompletionCallback& cc) { + if (has_interface<PPB_FileIO_1_1>()) { + return get_interface<PPB_FileIO_1_1>()->Query( + pp_resource(), result_buf, cc.pp_completion_callback()); + } else if (has_interface<PPB_FileIO_1_0>()) { + return get_interface<PPB_FileIO_1_0>()->Query( + pp_resource(), result_buf, cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileIO::Touch(PP_Time last_access_time, + PP_Time last_modified_time, + const CompletionCallback& cc) { + if (has_interface<PPB_FileIO_1_1>()) { + return get_interface<PPB_FileIO_1_1>()->Touch( + pp_resource(), last_access_time, last_modified_time, + cc.pp_completion_callback()); + } else if (has_interface<PPB_FileIO_1_0>()) { + return get_interface<PPB_FileIO_1_0>()->Touch( + pp_resource(), last_access_time, last_modified_time, + cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileIO::Read(int64_t offset, + char* buffer, + int32_t bytes_to_read, + const CompletionCallback& cc) { + if (has_interface<PPB_FileIO_1_1>()) { + return get_interface<PPB_FileIO_1_1>()->Read(pp_resource(), + offset, buffer, bytes_to_read, cc.pp_completion_callback()); + } else if (has_interface<PPB_FileIO_1_0>()) { + return get_interface<PPB_FileIO_1_0>()->Read(pp_resource(), + offset, buffer, bytes_to_read, cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileIO::Read( + int32_t offset, + int32_t max_read_length, + const CompletionCallbackWithOutput< std::vector<char> >& cc) { + if (has_interface<PPB_FileIO_1_1>()) { + PP_ArrayOutput array_output = cc.output(); + return get_interface<PPB_FileIO_1_1>()->ReadToArray(pp_resource(), + offset, max_read_length, &array_output, + cc.pp_completion_callback()); + } else if (has_interface<PPB_FileIO_1_0>()) { + // Data for our callback wrapper. The callback handler will delete it and + // temp_buffer. + CallbackData1_0* data = new CallbackData1_0; + data->output = cc.output(); + data->temp_buffer = max_read_length >= 0 ? new char[max_read_length] : NULL; + data->original_callback = cc.pp_completion_callback(); + + // Actual returned bytes might not equals to max_read_length. We need to + // read to a temporary buffer first and copy later to make sure the array + // buffer has correct size. + return get_interface<PPB_FileIO_1_0>()->Read( + pp_resource(), offset, data->temp_buffer, max_read_length, + PP_MakeCompletionCallback(&CallbackConverter, data)); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileIO::Write(int64_t offset, + const char* buffer, + int32_t bytes_to_write, + const CompletionCallback& cc) { + if (has_interface<PPB_FileIO_1_1>()) { + return get_interface<PPB_FileIO_1_1>()->Write( + pp_resource(), offset, buffer, bytes_to_write, + cc.pp_completion_callback()); + } else if (has_interface<PPB_FileIO_1_0>()) { + return get_interface<PPB_FileIO_1_0>()->Write( + pp_resource(), offset, buffer, bytes_to_write, + cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileIO::SetLength(int64_t length, + const CompletionCallback& cc) { + if (has_interface<PPB_FileIO_1_1>()) { + return get_interface<PPB_FileIO_1_1>()->SetLength( + pp_resource(), length, cc.pp_completion_callback()); + } else if (has_interface<PPB_FileIO_1_0>()) { + return get_interface<PPB_FileIO_1_0>()->SetLength( + pp_resource(), length, cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileIO::Flush(const CompletionCallback& cc) { + if (has_interface<PPB_FileIO_1_1>()) { + return get_interface<PPB_FileIO_1_1>()->Flush( + pp_resource(), cc.pp_completion_callback()); + } else if (has_interface<PPB_FileIO_1_0>()) { + return get_interface<PPB_FileIO_1_0>()->Flush( + pp_resource(), cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +void FileIO::Close() { + if (has_interface<PPB_FileIO_1_1>()) + get_interface<PPB_FileIO_1_1>()->Close(pp_resource()); + else if (has_interface<PPB_FileIO_1_0>()) + get_interface<PPB_FileIO_1_0>()->Close(pp_resource()); +} + +// static +void FileIO::CallbackConverter(void* user_data, int32_t result) { + CallbackData1_0* data = static_cast<CallbackData1_0*>(user_data); + + if (result >= 0) { + // Copy to the destination buffer owned by the callback. + char* buffer = static_cast<char*>(data->output.GetDataBuffer( + data->output.user_data, result, sizeof(char))); + memcpy(buffer, data->temp_buffer, result); + delete[] data->temp_buffer; + } + + // Now execute the original callback. + PP_RunCompletionCallback(&data->original_callback, result); + delete data; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/file_io.h b/chromium/ppapi/cpp/file_io.h new file mode 100644 index 00000000000..99d8ce74d90 --- /dev/null +++ b/chromium/ppapi/cpp/file_io.h @@ -0,0 +1,243 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_FILE_IO_H_ +#define PPAPI_CPP_FILE_IO_H_ + +#include "ppapi/c/pp_time.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the API to create a file i/o object. + +struct PP_FileInfo; + +namespace pp { + +class FileRef; +class InstanceHandle; + +/// The <code>FileIO</code> class represents a regular file. +class FileIO : public Resource { + public: + /// Default constructor for creating an is_null() <code>FileIO</code> + /// object. + FileIO(); + + /// A constructor used to create a <code>FileIO</code> and associate it with + /// the provided <code>Instance</code>. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit FileIO(const InstanceHandle& instance); + + /// The copy constructor for <code>FileIO</code>. + /// + /// @param[in] other A reference to a <code>FileIO</code>. + FileIO(const FileIO& other); + + /// Open() opens the specified regular file for I/O according to the given + /// open flags, which is a bit-mask of the PP_FileOpenFlags values. Upon + /// success, the corresponding file is classified as "in use" by this FileIO + /// object until such time as the FileIO object is closed or destroyed. + /// + /// @param[in] file_ref A <code>PP_Resource</code> corresponding to a file + /// reference. + /// + /// @param[in] open_flags A bit-mask of the <code>PP_FileOpenFlags</code> + /// values. Valid values are: + /// - PP_FILEOPENFLAG_READ + /// - PP_FILEOPENFLAG_WRITE + /// - PP_FILEOPENFLAG_CREATE + /// - PP_FILEOPENFLAG_TRUNCATE + /// - PP_FILEOPENFLAG_EXCLUSIVE + /// See <code>PP_FileOpenFlags</code> in <code>ppb_file_io.h</code> for more + /// details on these flags. + /// + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of Open(). + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + int32_t Open(const FileRef& file_ref, + int32_t open_flags, + const CompletionCallback& cc); + + /// Query() queries info about the file opened by this FileIO object. This + /// function will fail if the FileIO object has not been opened. + /// + /// @param[in] result_buf The <code>PP_FileInfo</code> structure representing + /// all information about the file. + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of Query(). + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + int32_t Query(PP_FileInfo* result_buf, + const CompletionCallback& cc); + + /// Touch() Updates time stamps for the file opened by this FileIO object. + /// This function will fail if the FileIO object has not been opened. + /// + /// @param[in] last_access_time The last time the FileIO was accessed. + /// @param[in] last_modified_time The last time the FileIO was modified. + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of Touch(). + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + int32_t Touch(PP_Time last_access_time, + PP_Time last_modified_time, + const CompletionCallback& cc); + + /// Reads from an offset in the file. + /// + /// The size of the buffer must be large enough to hold the specified number + /// of bytes to read. This function might perform a partial read, meaning + /// that all the requested bytes might not be returned, even if the end of the + /// file has not been reached. + /// + /// This function reads into a buffer that the caller supplies. This buffer + /// must remain valid as long as the FileIO resource is alive. If you use + /// a completion callback factory and it goes out of scope, it will not issue + /// the callback on your class, BUT the callback factory can NOT cancel + /// the request from the browser's perspective. This means that the browser + /// will still try to write to your buffer even if the callback factory is + /// destroyed! + /// + /// So you must ensure that your buffer outlives the FileIO resource. If you + /// have one class and use the FileIO resource exclusively from that class + /// and never make any copies, this will be fine: the resource will be + /// destroyed when your class is. But keep in mind that copying a pp::FileIO + /// object just creates a second reference to the original resource. For + /// example, if you have a function like this: + /// pp::FileIO MyClass::GetFileIO(); + /// where a copy of your FileIO resource could outlive your class, the + /// callback will still be pending when your class goes out of scope, creating + /// the possibility of writing into invalid memory. So it's recommended to + /// keep your FileIO resource and any output buffers tightly controlled in + /// the same scope. + /// + /// <strong>Caveat:</strong> This Read() is potentially unsafe if you're using + /// a CompletionCallbackFactory to scope callbacks to the lifetime of your + /// class. When your class goes out of scope, the callback factory will not + /// actually cancel the callback, but will rather just skip issuing the + /// callback on your class. This means that if the FileIO object outlives + /// your class (if you made a copy saved somewhere else, for example), then + /// the browser will still try to write into your buffer when the + /// asynchronous read completes, potentially causing a crash. + /// + /// See the other version of Read() which avoids this problem by writing into + /// CompletionCallbackWithOutput, where the output buffer is automatically + /// managed by the callback. + /// + /// @param[in] offset The offset into the file. + /// @param[in] buffer The buffer to hold the specified number of bytes read. + /// @param[in] bytes_to_read The number of bytes to read from + /// <code>offset</code>. + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of Read(). + /// + /// @return An The number of bytes read an error code from + /// <code>pp_errors.h</code>. If the return value is 0, then end-of-file was + /// reached. It is valid to call Read() multiple times with a completion + /// callback to queue up parallel reads from the file at different offsets. + int32_t Read(int64_t offset, + char* buffer, + int32_t bytes_to_read, + const CompletionCallback& cc); + + /// Read() reads from an offset in the file. A PP_ArrayOutput must be + /// provided so that output will be stored in its allocated buffer. This + /// function might perform a partial read. + /// + /// @param[in] file_io A <code>PP_Resource</code> corresponding to a file + /// FileIO. + /// @param[in] offset The offset into the file. + /// @param[in] max_read_length The maximum number of bytes to read from + /// <code>offset</code>. + /// @param[in] output A <code>PP_ArrayOutput</code> to hold the output data. + /// @param[in] callback A <code>PP_CompletionCallback</code> to be called upon + /// completion of Read(). + /// + /// @return The number of bytes read or an error code from + /// <code>pp_errors.h</code>. If the return value is 0, then end-of-file was + /// reached. It is valid to call Read() multiple times with a completion + /// callback to queue up parallel reads from the file, but pending reads + /// cannot be interleaved with other operations. + int32_t Read(int32_t offset, + int32_t max_read_length, + const CompletionCallbackWithOutput< std::vector<char> >& cc); + + /// Write() writes to an offset in the file. This function might perform a + /// partial write. The FileIO object must have been opened with write access. + /// + /// @param[in] offset The offset into the file. + /// @param[in] buffer The buffer to hold the specified number of bytes read. + /// @param[in] bytes_to_write The number of bytes to write to + /// <code>offset</code>. + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of Write(). + /// + /// @return An The number of bytes written or an error code from + /// <code>pp_errors.h</code>. If the return value is 0, then end-of-file was + /// reached. It is valid to call Write() multiple times with a completion + /// callback to queue up parallel writes to the file at different offsets. + int32_t Write(int64_t offset, + const char* buffer, + int32_t bytes_to_write, + const CompletionCallback& cc); + + /// SetLength() sets the length of the file. If the file size is extended, + /// then the extended area of the file is zero-filled. The FileIO object must + /// have been opened with write access. + /// + /// @param[in] length The length of the file to be set. + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of SetLength(). + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + int32_t SetLength(int64_t length, + const CompletionCallback& cc); + + /// Flush() flushes changes to disk. This call can be very expensive! + /// + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of Flush(). + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + int32_t Flush(const CompletionCallback& cc); + + /// Close() cancels any IO that may be pending, and closes the FileIO object. + /// Any pending callbacks will still run, reporting + /// <code>PP_ERROR_ABORTED</code> if pending IO was interrupted. It is not + /// valid to call Open() again after a call to this method. + /// + /// <strong>Note:</strong> If the FileIO object is destroyed, and it is still + /// open, then it will be implicitly closed, so you are not required to call + /// Close(). + void Close(); + + private: + struct CallbackData1_0 { + PP_ArrayOutput output; + char* temp_buffer; + PP_CompletionCallback original_callback; + }; + + // Provide backwards-compatibility for older Read versions. Converts the + // old-style "char*" output buffer of 1.0 to the new "PP_ArrayOutput" + // interface in 1.1. + // + // This takes a heap-allocated CallbackData1_0 struct passed as the user data + // and deletes it when the call completes. + static void CallbackConverter(void* user_data, int32_t result); +}; + +} // namespace pp + +#endif // PPAPI_CPP_FILE_IO_H_ diff --git a/chromium/ppapi/cpp/file_ref.cc b/chromium/ppapi/cpp/file_ref.cc new file mode 100644 index 00000000000..0bc9487eb5e --- /dev/null +++ b/chromium/ppapi/cpp/file_ref.cc @@ -0,0 +1,182 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/file_ref.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/directory_entry.h" +#include "ppapi/cpp/file_system.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_FileRef_1_0>() { + return PPB_FILEREF_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_FileRef_1_1>() { + return PPB_FILEREF_INTERFACE_1_1; +} + +} // namespace + +FileRef::FileRef(PP_Resource resource) : Resource(resource) { +} + +FileRef::FileRef(PassRef, PP_Resource resource) : Resource(PASS_REF, resource) { +} + +FileRef::FileRef(const FileSystem& file_system, + const char* path) { + if (has_interface<PPB_FileRef_1_1>()) { + PassRefFromConstructor(get_interface<PPB_FileRef_1_1>()->Create( + file_system.pp_resource(), path)); + } else if (has_interface<PPB_FileRef_1_0>()) { + PassRefFromConstructor(get_interface<PPB_FileRef_1_0>()->Create( + file_system.pp_resource(), path)); + } +} + +FileRef::FileRef(const FileRef& other) + : Resource(other) { +} + +PP_FileSystemType FileRef::GetFileSystemType() const { + if (has_interface<PPB_FileRef_1_1>()) + return get_interface<PPB_FileRef_1_1>()->GetFileSystemType(pp_resource()); + if (has_interface<PPB_FileRef_1_0>()) + return get_interface<PPB_FileRef_1_0>()->GetFileSystemType(pp_resource()); + return PP_FILESYSTEMTYPE_EXTERNAL; +} + +Var FileRef::GetName() const { + if (has_interface<PPB_FileRef_1_1>()) { + return Var(PASS_REF, + get_interface<PPB_FileRef_1_1>()->GetName(pp_resource())); + } + if (has_interface<PPB_FileRef_1_0>()) { + return Var(PASS_REF, + get_interface<PPB_FileRef_1_0>()->GetName(pp_resource())); + } + return Var(); +} + +Var FileRef::GetPath() const { + if (has_interface<PPB_FileRef_1_1>()) { + return Var(PASS_REF, + get_interface<PPB_FileRef_1_1>()->GetPath(pp_resource())); + } + if (has_interface<PPB_FileRef_1_0>()) { + return Var(PASS_REF, + get_interface<PPB_FileRef_1_0>()->GetPath(pp_resource())); + } + return Var(); +} + +FileRef FileRef::GetParent() const { + if (has_interface<PPB_FileRef_1_1>()) { + return FileRef(PASS_REF, + get_interface<PPB_FileRef_1_1>()->GetParent(pp_resource())); + } + if (has_interface<PPB_FileRef_1_0>()) { + return FileRef(PASS_REF, + get_interface<PPB_FileRef_1_0>()->GetParent(pp_resource())); + } + return FileRef(); +} + +int32_t FileRef::MakeDirectory(const CompletionCallback& cc) { + if (has_interface<PPB_FileRef_1_1>()) { + return get_interface<PPB_FileRef_1_1>()->MakeDirectory( + pp_resource(), + PP_FALSE, // make_ancestors + cc.pp_completion_callback()); + } + if (has_interface<PPB_FileRef_1_0>()) { + return get_interface<PPB_FileRef_1_0>()->MakeDirectory( + pp_resource(), + PP_FALSE, // make_ancestors + cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileRef::MakeDirectoryIncludingAncestors( + const CompletionCallback& cc) { + if (has_interface<PPB_FileRef_1_1>()) { + return get_interface<PPB_FileRef_1_1>()->MakeDirectory( + pp_resource(), + PP_TRUE, // make_ancestors + cc.pp_completion_callback()); + } + if (has_interface<PPB_FileRef_1_0>()) { + return get_interface<PPB_FileRef_1_0>()->MakeDirectory( + pp_resource(), + PP_TRUE, // make_ancestors + cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileRef::Touch(PP_Time last_access_time, + PP_Time last_modified_time, + const CompletionCallback& cc) { + if (has_interface<PPB_FileRef_1_1>()) { + return get_interface<PPB_FileRef_1_1>()->Touch( + pp_resource(), last_access_time, last_modified_time, + cc.pp_completion_callback()); + } + if (has_interface<PPB_FileRef_1_0>()) { + return get_interface<PPB_FileRef_1_0>()->Touch( + pp_resource(), last_access_time, last_modified_time, + cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileRef::Delete(const CompletionCallback& cc) { + if (has_interface<PPB_FileRef_1_1>()) { + return get_interface<PPB_FileRef_1_1>()->Delete( + pp_resource(), cc.pp_completion_callback()); + } + if (has_interface<PPB_FileRef_1_0>()) { + return get_interface<PPB_FileRef_1_0>()->Delete( + pp_resource(), cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileRef::Rename(const FileRef& new_file_ref, + const CompletionCallback& cc) { + if (has_interface<PPB_FileRef_1_1>()) { + return get_interface<PPB_FileRef_1_1>()->Rename( + pp_resource(), new_file_ref.pp_resource(), cc.pp_completion_callback()); + } + if (has_interface<PPB_FileRef_1_0>()) { + return get_interface<PPB_FileRef_1_0>()->Rename( + pp_resource(), new_file_ref.pp_resource(), cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t FileRef::Query(const CompletionCallbackWithOutput<PP_FileInfo>& cc) { + if (!has_interface<PPB_FileRef_1_1>()) + return cc.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_FileRef_1_1>()->Query( + pp_resource(), cc.output(), cc.pp_completion_callback()); +} + +int32_t FileRef::ReadDirectoryEntries( + const CompletionCallbackWithOutput<std::vector<DirectoryEntry> >& + callback) { + if (!has_interface<PPB_FileRef_1_1>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_FileRef_1_1>()->ReadDirectoryEntries( + pp_resource(), callback.output(), callback.pp_completion_callback()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/file_ref.h b/chromium/ppapi/cpp/file_ref.h new file mode 100644 index 00000000000..d229c5fd7ad --- /dev/null +++ b/chromium/ppapi/cpp/file_ref.h @@ -0,0 +1,188 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_FILE_REF_H_ +#define PPAPI_CPP_FILE_REF_H_ + +#include "ppapi/c/pp_file_info.h" +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/ppb_file_ref.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" + +/// @file +/// This file defines the API to create a file reference or "weak pointer" to a +/// file in a file system. + +namespace pp { + +class DirectoryEntry; +class FileSystem; +class CompletionCallback; +template <typename T> class CompletionCallbackWithOutput; + +/// The <code>FileRef</code> class represents a "weak pointer" to a file in +/// a file system. +class FileRef : public Resource { + public: + /// Default constructor for creating an is_null() <code>FileRef</code> + /// object. + FileRef() {} + + /// A constructor used when you have an existing PP_Resource for a FileRef + /// and which to create a C++ object that takes an additional reference to + /// the resource. + /// + /// @param[in] resource A PP_Resource corresponding to file reference. + explicit FileRef(PP_Resource resource); + + /// A constructor used when you have received a PP_Resource as a return + /// value that has already been reference counted. + /// + /// @param[in] resource A PP_Resource corresponding to file reference. + FileRef(PassRef, PP_Resource resource); + + /// A constructor that creates a weak pointer to a file in the given file + /// system. File paths are POSIX style. + /// + /// @param[in] file_system A <code>FileSystem</code> corresponding to a file + /// system type. + /// @param[in] path A path to the file. + FileRef(const FileSystem& file_system, const char* path); + + /// The copy constructor for <code>FileRef</code>. + /// + /// @param[in] other A pointer to a <code>FileRef</code>. + FileRef(const FileRef& other); + + /// GetFileSystemType() returns the type of the file system. + /// + /// @return A <code>PP_FileSystemType</code> with the file system type if + /// valid or <code>PP_FILESYSTEMTYPE_INVALID</code> if the provided resource + /// is not a valid file reference. + PP_FileSystemType GetFileSystemType() const; + + /// GetName() returns the name of the file. + /// + /// @return A <code>Var</code> containing the name of the file. The value + /// returned by this function does not include any path components (such as + /// the name of the parent directory, for example). It is just the name of the + /// file. Use GetPath() to get the full file path. + Var GetName() const; + + /// GetPath() returns the absolute path of the file. + /// + /// @return A <code>Var</code> containing the absolute path of the file. + /// This function fails if the file system type is + /// <code>PP_FileSystemType_External</code>. + Var GetPath() const; + + /// GetParent() returns the parent directory of this file. If + /// <code>file_ref</code> points to the root of the filesystem, then the root + /// is returned. + /// + /// @return A <code>FileRef</code> containing the parent directory of the + /// file. This function fails if the file system type is + /// <code>PP_FileSystemType_External</code>. + FileRef GetParent() const; + + /// MakeDirectory() makes a new directory in the file system. It is not + /// valid to make a directory in the external file system. + /// <strong>Note:</strong> Use MakeDirectoryIncludingAncestors() to create + /// parent directories. + /// + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of MakeDirectory(). + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + /// Succeeds if the directory already exists. Fails if ancestor + /// directortories do not exist (see MakeDirectoryIncludingAncestors for the + /// alternative). + int32_t MakeDirectory(const CompletionCallback& cc); + + /// MakeDirectoryIncludingAncestors() makes a new directory in the file + /// system as well as any parent directories. It is not valid to make a + /// directory in the external file system. + /// + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of MakeDirectoryIncludingAncestors(). + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + /// Succeeds if the directory already exists. + int32_t MakeDirectoryIncludingAncestors(const CompletionCallback& cc); + + /// Touch() Updates time stamps for a file. You must have write access to the + /// file if it exists in the external filesystem. + /// + /// @param[in] last_access_time The last time the file was accessed. + /// @param[in] last_modified_time The last time the file was modified. + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of Touch(). + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + int32_t Touch(PP_Time last_access_time, + PP_Time last_modified_time, + const CompletionCallback& cc); + + /// Delete() deletes a file or directory. If <code>file_ref</code> refers to + /// a directory, then the directory must be empty. It is an error to delete a + /// file or directory that is in use. It is not valid to delete a file in + /// the external file system. + /// + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of Delete(). + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + int32_t Delete(const CompletionCallback& cc); + + /// Rename() renames a file or directory. Argument <code>new_file_ref</code> + /// must refer to files in the same file system as in this object. It is an + /// error to rename a file or directory that is in use. It is not valid to + /// rename a file in the external file system. + /// + /// @param[in] new_file_ref A <code>FileRef</code> corresponding to a new + /// file reference. + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of Rename(). + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + int32_t Rename(const FileRef& new_file_ref, const CompletionCallback& cc); + + /// Query() queries info about a file or directory. You must have access to + /// read this file or directory if it exists in the external filesystem. + /// + /// @param[in] callback A <code>CompletionCallbackWithOutput</code> + /// to be called upon completion of Query(). + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + int32_t Query(const CompletionCallbackWithOutput<PP_FileInfo>& callback); + + /// ReadDirectoryEntries() Reads all entries in the directory. + /// + /// @param[in] cc A <code>CompletionCallbackWithOutput</code> to be called + /// upon completion of ReadDirectoryEntries(). On success, the + /// directory entries will be passed to the given function. + /// + /// Normally you would use a CompletionCallbackFactory to allow callbacks to + /// be bound to your class. See completion_callback_factory.h for more + /// discussion on how to use this. Your callback will generally look like: + /// + /// @code + /// void OnReadDirectoryEntries( + /// int32_t result, + /// const std::vector<DirectoryEntry>& entries) { + /// if (result == PP_OK) + /// // use entries... + /// } + /// @endcode + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + int32_t ReadDirectoryEntries( + const CompletionCallbackWithOutput< std::vector<DirectoryEntry> >& + callback); +}; + +} // namespace pp + +#endif // PPAPI_CPP_FILE_REF_H_ diff --git a/chromium/ppapi/cpp/file_system.cc b/chromium/ppapi/cpp/file_system.cc new file mode 100644 index 00000000000..f993fdaa892 --- /dev/null +++ b/chromium/ppapi/cpp/file_system.cc @@ -0,0 +1,51 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/file_system.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/ppb_file_system.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_FileSystem_1_0>() { + return PPB_FILESYSTEM_INTERFACE_1_0; +} + +} // namespace + +FileSystem::FileSystem() { +} + +FileSystem::FileSystem(const FileSystem& other) : Resource(other) { +} + +FileSystem::FileSystem(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +FileSystem::FileSystem(const InstanceHandle& instance, + PP_FileSystemType type) { + if (!has_interface<PPB_FileSystem_1_0>()) + return; + PassRefFromConstructor(get_interface<PPB_FileSystem_1_0>()->Create( + instance.pp_instance(), type)); +} + +int32_t FileSystem::Open(int64_t expected_size, + const CompletionCallback& cc) { + if (!has_interface<PPB_FileSystem_1_0>()) + return cc.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_FileSystem_1_0>()->Open( + pp_resource(), expected_size, cc.pp_completion_callback()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/file_system.h b/chromium/ppapi/cpp/file_system.h new file mode 100644 index 00000000000..9baa78e31bf --- /dev/null +++ b/chromium/ppapi/cpp/file_system.h @@ -0,0 +1,70 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_FILE_SYSTEM_H_ +#define PPAPI_CPP_FILE_SYSTEM_H_ + +#include "ppapi/c/pp_file_info.h" +#include "ppapi/c/pp_instance.h" +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/pp_time.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the API to create a file system associated with a file. + +namespace pp { + +class CompletionCallback; + +/// The <code>FileSystem</code> class identifies the file system type +/// associated with a file. +class FileSystem : public Resource { + public: + /// Constructs an is_null() filesystem resource. If you use this constructor, + /// you will have to assign it to a "real" FileSystem object before you can + /// use it. + FileSystem(); + + /// The copy constructor for <code>FileSystem</code>. + /// + /// @param[in] other A reference to a <code>FileSystem</code>. + FileSystem(const FileSystem& other); + + /// A constructor used when you have received a PP_Resource as a return + /// value that has already been reference counted. + /// + /// @param[in] resource A PP_Resource corresponding to a PPB_FileSystem. + FileSystem(PassRef, PP_Resource resource); + + /// This constructor creates a file system object of the given type. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + /// + /// @param[in] type A file system type as defined by + /// <code>PP_FileSystemType</code> enum. + FileSystem(const InstanceHandle& instance, PP_FileSystemType type); + + /// Open() opens the file system. A file system must be opened before running + /// any other operation on it. + /// + /// @param[in] expected_size The expected size of the file system. Note that + /// this does not request quota; to do that, you must either invoke + /// requestQuota from JavaScript: + /// http://www.html5rocks.com/en/tutorials/file/filesystem/#toc-requesting-quota + /// or set the unlimitedStorage permission for Chrome Web Store apps: + /// http://code.google.com/chrome/extensions/manifest.html#permissions + /// + /// @param[in] cc A <code>PP_CompletionCallback</code> to be called upon + /// completion of Open(). + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + int32_t Open(int64_t expected_size, const CompletionCallback& cc); +}; + +} // namespace pp + +#endif // PPAPI_CPP_FILE_SYSTEM_H_ diff --git a/chromium/ppapi/cpp/fullscreen.cc b/chromium/ppapi/cpp/fullscreen.cc new file mode 100644 index 00000000000..c5ad4f034ab --- /dev/null +++ b/chromium/ppapi/cpp/fullscreen.cc @@ -0,0 +1,50 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/fullscreen.h" + +#include "ppapi/c/ppb_fullscreen.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/size.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Fullscreen_1_0>() { + return PPB_FULLSCREEN_INTERFACE_1_0; +} + +} // namespace + +Fullscreen::Fullscreen(const InstanceHandle& instance) + : instance_(instance) { +} + +Fullscreen::~Fullscreen() { +} + +bool Fullscreen::IsFullscreen() { + return has_interface<PPB_Fullscreen_1_0>() && + get_interface<PPB_Fullscreen_1_0>()->IsFullscreen( + instance_.pp_instance()); +} + +bool Fullscreen::SetFullscreen(bool fullscreen) { + if (!has_interface<PPB_Fullscreen_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_Fullscreen_1_0>()->SetFullscreen( + instance_.pp_instance(), PP_FromBool(fullscreen))); +} + +bool Fullscreen::GetScreenSize(Size* size) { + if (!has_interface<PPB_Fullscreen_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_Fullscreen_1_0>()->GetScreenSize( + instance_.pp_instance(), &size->pp_size())); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/fullscreen.h b/chromium/ppapi/cpp/fullscreen.h new file mode 100644 index 00000000000..3504424e5a8 --- /dev/null +++ b/chromium/ppapi/cpp/fullscreen.h @@ -0,0 +1,72 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_FULLSCREEN_H_ +#define PPAPI_CPP_FULLSCREEN_H_ + +#include "ppapi/cpp/instance_handle.h" + +/// @file +/// This file defines the API for handling transitions of a module instance to +/// and from fullscreen mode. + +namespace pp { + +class Size; + +/// The Fullscreen class allowing you to check and toggle fullscreen mode. +class Fullscreen { + public: + /// A constructor for creating a <code>Fullscreen</code>. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit Fullscreen(const InstanceHandle& instance); + + /// Destructor. + virtual ~Fullscreen(); + + /// IsFullscreen() checks whether the module instance is currently in + /// fullscreen mode. + /// + /// @return <code>true</code> if the module instance is in fullscreen mode, + /// <code>false</code> if the module instance is not in fullscreen mode. + bool IsFullscreen(); + + /// SetFullscreen() switches the module instance to and from fullscreen + /// mode. + /// + /// The transition to and from fullscreen mode is asynchronous. During the + /// transition, IsFullscreen() will return the previous value and + /// no 2D or 3D device can be bound. The transition ends at DidChangeView() + /// when IsFullscreen() returns the new value. You might receive other + /// DidChangeView() calls while in transition. + /// + /// The transition to fullscreen mode can only occur while the browser is + /// processing a user gesture, even if <code>true</code> is returned. + /// + /// @param[in] fullscreen <code>true</code> to enter fullscreen mode, or + /// <code>false</code> to exit fullscreen mode. + /// + /// @return <code>true</code> on success or <code>false</code> on + /// failure. + bool SetFullscreen(bool fullscreen); + + /// GetScreenSize() gets the size of the screen in pixels. The module instance + /// will be resized to this size when SetFullscreen() is called to enter + /// fullscreen mode. + /// + /// @param[out] size The size of the entire screen in pixels. + /// + /// @return <code>true</code> on success or <code>false</code> on + /// failure. + bool GetScreenSize(Size* size); + + private: + InstanceHandle instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_FULLSCREEN_H_ diff --git a/chromium/ppapi/cpp/graphics_2d.cc b/chromium/ppapi/cpp/graphics_2d.cc new file mode 100644 index 00000000000..3a766c83546 --- /dev/null +++ b/chromium/ppapi/cpp/graphics_2d.cc @@ -0,0 +1,155 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/graphics_2d.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/ppb_graphics_2d.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/rect.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Graphics2D_1_0>() { + return PPB_GRAPHICS_2D_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_Graphics2D_1_1>() { + return PPB_GRAPHICS_2D_INTERFACE_1_1; +} + +} // namespace + +Graphics2D::Graphics2D() : Resource() { +} + +Graphics2D::Graphics2D(const Graphics2D& other) + : Resource(other), + size_(other.size_) { +} + +Graphics2D::Graphics2D(const InstanceHandle& instance, + const Size& size, + bool is_always_opaque) + : Resource() { + if (has_interface<PPB_Graphics2D_1_1>()) { + PassRefFromConstructor(get_interface<PPB_Graphics2D_1_1>()->Create( + instance.pp_instance(), + &size.pp_size(), + PP_FromBool(is_always_opaque))); + } else if (has_interface<PPB_Graphics2D_1_0>()) { + PassRefFromConstructor(get_interface<PPB_Graphics2D_1_0>()->Create( + instance.pp_instance(), + &size.pp_size(), + PP_FromBool(is_always_opaque))); + } else { + return; + } + if (!is_null()) { + // Only save the size if allocation succeeded. + size_ = size; + } +} + +Graphics2D::~Graphics2D() { +} + +Graphics2D& Graphics2D::operator=(const Graphics2D& other) { + Resource::operator=(other); + size_ = other.size_; + return *this; +} + +void Graphics2D::PaintImageData(const ImageData& image, + const Point& top_left) { + if (has_interface<PPB_Graphics2D_1_1>()) { + get_interface<PPB_Graphics2D_1_1>()->PaintImageData(pp_resource(), + image.pp_resource(), + &top_left.pp_point(), + NULL); + } else if (has_interface<PPB_Graphics2D_1_0>()) { + get_interface<PPB_Graphics2D_1_0>()->PaintImageData(pp_resource(), + image.pp_resource(), + &top_left.pp_point(), + NULL); + } +} + +void Graphics2D::PaintImageData(const ImageData& image, + const Point& top_left, + const Rect& src_rect) { + if (has_interface<PPB_Graphics2D_1_1>()) { + get_interface<PPB_Graphics2D_1_1>()->PaintImageData(pp_resource(), + image.pp_resource(), + &top_left.pp_point(), + &src_rect.pp_rect()); + } else if (has_interface<PPB_Graphics2D_1_0>()) { + get_interface<PPB_Graphics2D_1_0>()->PaintImageData(pp_resource(), + image.pp_resource(), + &top_left.pp_point(), + &src_rect.pp_rect()); + } +} + +void Graphics2D::Scroll(const Rect& clip, const Point& amount) { + if (has_interface<PPB_Graphics2D_1_1>()) { + get_interface<PPB_Graphics2D_1_1>()->Scroll(pp_resource(), + &clip.pp_rect(), + &amount.pp_point()); + } else if (has_interface<PPB_Graphics2D_1_0>()) { + get_interface<PPB_Graphics2D_1_0>()->Scroll(pp_resource(), + &clip.pp_rect(), + &amount.pp_point()); + } +} + +void Graphics2D::ReplaceContents(ImageData* image) { + if (has_interface<PPB_Graphics2D_1_1>()) { + get_interface<PPB_Graphics2D_1_1>()->ReplaceContents(pp_resource(), + image->pp_resource()); + } else if (has_interface<PPB_Graphics2D_1_0>()) { + get_interface<PPB_Graphics2D_1_0>()->ReplaceContents(pp_resource(), + image->pp_resource()); + } else { + return; + } + + // On success, reset the image data. This is to help prevent people + // from continuing to use the resource which will result in artifacts. + *image = ImageData(); +} + +int32_t Graphics2D::Flush(const CompletionCallback& cc) { + if (has_interface<PPB_Graphics2D_1_1>()) { + return get_interface<PPB_Graphics2D_1_1>()->Flush( + pp_resource(), cc.pp_completion_callback()); + } else if (has_interface<PPB_Graphics2D_1_0>()) { + return get_interface<PPB_Graphics2D_1_0>()->Flush( + pp_resource(), cc.pp_completion_callback()); + } else { + return cc.MayForce(PP_ERROR_NOINTERFACE); + } +} + +bool Graphics2D::SetScale(float scale) { + if (!has_interface<PPB_Graphics2D_1_1>()) + return false; + return PP_ToBool(get_interface<PPB_Graphics2D_1_1>()->SetScale(pp_resource(), + scale)); +} + +float Graphics2D::GetScale() { + if (!has_interface<PPB_Graphics2D_1_1>()) + return 1.0f; + return get_interface<PPB_Graphics2D_1_1>()->GetScale(pp_resource()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/graphics_2d.h b/chromium/ppapi/cpp/graphics_2d.h new file mode 100644 index 00000000000..c6a23905d6f --- /dev/null +++ b/chromium/ppapi/cpp/graphics_2d.h @@ -0,0 +1,293 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_GRAPHICS_2D_H_ +#define PPAPI_CPP_GRAPHICS_2D_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/size.h" + + +/// @file +/// This file defines the API to create a 2D graphics context in the browser. +namespace pp { + +class CompletionCallback; +class ImageData; +class InstanceHandle; +class Point; +class Rect; + +class Graphics2D : public Resource { + public: + /// Default constructor for creating an is_null() <code>Graphics2D</code> + /// object. + Graphics2D(); + + /// The copy constructor for Graphics2D. The underlying 2D context is not + /// copied; this constructor creates another reference to the original 2D + /// context. + /// + /// @param[in] other A pointer to a <code>Graphics2D</code> context. + Graphics2D(const Graphics2D& other); + + /// A constructor allocating a new 2D graphics context with the given size + /// in the browser, resulting object will be is_null() if the allocation + /// failed. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + /// + /// @param[in] size The size of the 2D graphics context in the browser, + /// measured in pixels. See <code>SetScale()</code> for more information. + /// + /// @param[in] is_always_opaque Set the <code>is_always_opaque</code> flag + /// to true if you know that you will be painting only opaque data to this + /// context. This option will disable blending when compositing the module + /// with the web page, which might give higher performance on some computers. + /// + /// If you set <code>is_always_opaque</code>, your alpha channel should + /// always be set to 0xFF or there may be painting artifacts. The alpha values + /// overwrite the destination alpha values without blending when + /// <code>is_always_opaque</code> is true. + Graphics2D(const InstanceHandle& instance, + const Size& size, + bool is_always_opaque); + + /// A destructor that decrements the reference count of a + /// <code>Graphics2D</code> object made using the previous copy constructor. + /// It is possible that the destructor does not totally destroy the underlying + /// 2D context if there are outstanding references to it. + virtual ~Graphics2D(); + + /// This function assigns one 2D graphics context to this 2D graphics + /// context. This function increases the reference count of the 2D resource + /// of the other 2D graphics context while decrementing the reference counter + /// of this 2D graphics context. + /// + /// @param[in] other An other 2D graphics context. + /// + /// @return A new Graphics2D context. + Graphics2D& operator=(const Graphics2D& other); + + /// Getter function for returning size of the 2D graphics context. + /// + /// @return The size of the 2D graphics context measured in pixels. + const Size& size() const { return size_; } + + /// PaintImageData() enqueues a paint command of the given image into + /// the context. This command has no effect until you call Flush(). As a + /// result, what counts is the contents of the bitmap when you call Flush, + /// not when you call this function. + /// + /// The provided image will be placed at <code>top_left</code> from the top + /// left of the context's internal backing store. This version of + /// PaintImageData paints the entire image. Refer to the other version of + /// this function to paint only part of the area. + /// + /// The painted area of the source bitmap must fall entirely within the + /// context. Attempting to paint outside of the context will result in an + /// error. + /// + /// There are two methods most modules will use for painting. The first + /// method is to generate a new <code>ImageData</code> and then paint it. + /// In this case, you'll set the location of your painting to + /// <code>top_left</code> and set <code>src_rect</code> to <code>NULL</code>. + /// The second is that you're generating small invalid regions out of a larger + /// bitmap representing your entire module's image. + /// + /// @param[in] image The <code>ImageData</code> to be painted. + /// @param[in] top_left A <code>Point</code> representing the + /// <code>top_left</code> location where the <code>ImageData</code> will be + /// painted. + void PaintImageData(const ImageData& image, + const Point& top_left); + + /// PaintImageData() enqueues a paint command of the given image into + /// the context. This command has no effect until you call Flush(). As a + /// result, what counts is the contents of the bitmap when you call Flush(), + /// not when you call this function. + /// + /// The provided image will be placed at <code>top_left</code> from the top + /// left of the context's internal backing store. Then the pixels contained + /// in <code>src_rect</code> will be copied into the backing store. This + /// means that the rectangle being painted will be at <code>src_rect</code> + /// offset by <code>top_left</code>. + /// + /// The <code>src_rect</code> is specified in the coordinate system of the + /// image being painted, not the context. For the common case of copying the + /// entire image, you may specify an empty <code>src_rect</code>. + /// + /// The painted area of the source bitmap must fall entirely within the + /// context. Attempting to paint outside of the context will result in an + /// error. However, the source bitmap may fall outside the context, as long + /// as the <code>src_rect</code> subset of it falls entirely within the + /// context. + /// + /// There are two methods most modules will use for painting. The first + /// method is to generate a new <code>ImageData</code> and then paint it. In + /// this case, you'll set the location of your painting to + /// <code>top_left</code> and set <code>src_rect</code> to <code>NULL</code>. + /// The second is that you're generating small invalid regions out of a larger + /// bitmap representing your entire module. In this case, you would set the + /// location of your image to (0,0) and then set <code>src_rect</code> to the + /// pixels you changed. + /// + /// @param[in] image The <code>ImageData</code> to be painted. + /// @param[in] top_left A <code>Point</code> representing the + /// <code>top_left</code> location where the <code>ImageData</code> will be + /// painted. + /// @param[in] src_rect The rectangular area where the <code>ImageData</code> + /// will be painted. + void PaintImageData(const ImageData& image, + const Point& top_left, + const Rect& src_rect); + + /// Scroll() enqueues a scroll of the context's backing store. This + /// function has no effect until you call Flush(). The data within the + /// provided clipping rectangle will be shifted by (dx, dy) pixels. + /// + /// This function will result in some exposed region which will have + /// undefined contents. The module should call PaintImageData() on + /// these exposed regions to give the correct contents. + /// + /// The scroll can be larger than the area of the clipping rectangle, which + /// means the current image will be scrolled out of the rectangle. This + /// scenario is not an error but will result in a no-op. + /// + /// @param[in] clip The clipping rectangle. + /// @param[in] amount The amount the area in the clipping rectangle will + /// shifted. + void Scroll(const Rect& clip, const Point& amount); + + /// ReplaceContents() provides a slightly more efficient way to paint the + /// entire module's image. Normally, calling PaintImageData() requires that + /// the browser copy the pixels out of the image and into the graphics + /// context's backing store. This function replaces the graphics context's + /// backing store with the given image, avoiding the copy. + /// + /// The new image must be the exact same size as this graphics context. If + /// the new image uses a different image format than the browser's native + /// bitmap format (use ImageData::GetNativeImageDataFormat() to retrieve the + /// format), then a conversion will be done inside the browser which may slow + /// the performance a little bit. + /// + /// <strong>Note:</strong> The new image will not be painted until you call + /// Flush(). + /// + /// After this call, you should take care to release your references to the + /// image. If you paint to the image after ReplaceContents(), there is the + /// possibility of significant painting artifacts because the page might use + /// partially-rendered data when copying out of the backing store. + /// + /// In the case of an animation, you will want to allocate a new image for + /// the next frame. It is best if you wait until the flush callback has + /// executed before allocating this bitmap. This gives the browser the option + /// of caching the previous backing store and handing it back to you + /// (assuming the sizes match). In the optimal case, this means no bitmaps are + /// allocated during the animation, and the backing store and "front buffer" + /// (which the module is painting into) are just being swapped back and forth. + /// + /// @param[in] image The <code>ImageData</code> to be painted. + void ReplaceContents(ImageData* image); + + /// Flush() flushes any enqueued paint, scroll, and replace commands + /// to the backing store. This actually executes the updates, and causes a + /// repaint of the webpage, assuming this graphics context is bound to a + /// module instance. + /// + /// Flush() runs in asynchronous mode. Specify a callback function and + /// the argument for that callback function. The callback function will be + /// executed on the calling thread when the image has been painted to the + /// screen. While you are waiting for a <code>Flush</code> callback, + /// additional calls to Flush() will fail. + /// + /// Because the callback is executed (or thread unblocked) only when the + /// module's image is actually on the screen, this function provides + /// a way to rate limit animations. By waiting until the image is on the + /// screen before painting the next frame, you can ensure you're not + /// flushing 2D graphics faster than the screen can be updated. + /// + /// <strong>Unbound contexts</strong> + /// If the context is not bound to a module instance, you will + /// still get a callback. The callback will execute after Flush() returns + /// to avoid reentrancy. The callback will not wait until anything is + /// painted to the screen because there will be nothing on the screen. The + /// timing of this callback is not guaranteed and may be deprioritized by + /// the browser because it is not affecting the user experience. + /// + /// <strong>Off-screen instances</strong> + /// If the context is bound to an instance that is + /// currently not visible (for example, scrolled out of view) it will + /// behave like the "unbound context" case. + /// + /// <strong>Detaching a context</strong> + /// If you detach a context from a module instance, any + /// pending flush callbacks will be converted into the "unbound context" + /// case. + /// + /// <strong>Released contexts</strong> + /// A callback may or may not still get called even if you have released all + /// of your references to the context. This can occur if there are internal + /// references to the context that means it has not been internally + /// destroyed (for example, if it is still bound to an instance) or due to + /// other implementation details. As a result, you should be careful to + /// check that flush callbacks are for the context you expect and that + /// you're capable of handling callbacks for context that you may have + /// released your reference to. + /// + /// <strong>Shutdown</strong> + /// If a module instance is removed when a Flush is pending, the + /// callback will not be executed. + /// + /// @param[in] cc A <code>CompletionCallback</code> to be called when the + /// image has been painted on the screen. + /// + /// @return Returns <code>PP_OK</code> on success or + /// <code>PP_ERROR_BADRESOURCE</code> if the graphics context is invalid, + /// <code>PP_ERROR_BADARGUMENT</code> if the callback is null and + /// flush is being called from the main thread of the module, or + /// <code>PP_ERROR_INPROGRESS</code> if a flush is already pending that has + /// not issued its callback yet. In the failure case, nothing will be + /// updated and no callback will be scheduled. + + // TODO(darin): We should ensure that the completion callback always runs, so + // that it is easier for consumers to manage memory referenced by a callback. + + // TODO(): Add back in the synchronous mode description once we have support + // for it. + int32_t Flush(const CompletionCallback& cc); + + /// SetScale() sets the scale factor that will be applied when painting the + /// graphics context onto the output device. Typically, if rendering at device + /// resolution is desired, the context would be created with the width and + /// height scaled up by the view's GetDeviceScale and SetScale called with a + /// scale of 1.0 / GetDeviceScale(). For example, if the view resource passed + /// to DidChangeView has a rectangle of (w=200, h=100) and a device scale of + /// 2.0, one would call Create with a size of (w=400, h=200) and then call + /// SetScale with 0.5. One would then treat each pixel in the context as a + /// single device pixel. + /// + /// @param[in] scale The scale to apply when painting. + /// + /// @return Returns <code>true</code> on success or <code>false</code> + /// if the resource is invalid or the scale factor is 0 or less. + bool SetScale(float scale); + + /// GetScale() gets the scale factor that will be applied when painting the + /// graphics context onto the output device. + /// + /// @return Returns the scale factor for the graphics context. If the resource + /// is invalid, 0.0 will be returned. The default scale for a graphics context + /// is 1.0. + float GetScale(); + + private: + Size size_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_GRAPHICS_2D_H_ diff --git a/chromium/ppapi/cpp/graphics_3d.cc b/chromium/ppapi/cpp/graphics_3d.cc new file mode 100644 index 00000000000..be11bec6b51 --- /dev/null +++ b/chromium/ppapi/cpp/graphics_3d.cc @@ -0,0 +1,83 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/graphics_3d.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Graphics3D_1_0>() { + return PPB_GRAPHICS_3D_INTERFACE_1_0; +} + +} // namespace + +Graphics3D::Graphics3D() { +} + +Graphics3D::Graphics3D(const InstanceHandle& instance, + const int32_t attrib_list[]) { + if (has_interface<PPB_Graphics3D_1_0>()) { + PassRefFromConstructor(get_interface<PPB_Graphics3D_1_0>()->Create( + instance.pp_instance(), 0, attrib_list)); + } +} + +Graphics3D::Graphics3D(const InstanceHandle& instance, + const Graphics3D& share_context, + const int32_t attrib_list[]) { + if (has_interface<PPB_Graphics3D_1_0>()) { + PassRefFromConstructor(get_interface<PPB_Graphics3D_1_0>()->Create( + instance.pp_instance(), + share_context.pp_resource(), + attrib_list)); + } +} + +Graphics3D::~Graphics3D() { +} + +int32_t Graphics3D::GetAttribs(int32_t attrib_list[]) const { + if (!has_interface<PPB_Graphics3D_1_0>()) + return PP_ERROR_NOINTERFACE; + + return get_interface<PPB_Graphics3D_1_0>()->GetAttribs( + pp_resource(), + attrib_list); +} + +int32_t Graphics3D::SetAttribs(const int32_t attrib_list[]) { + if (!has_interface<PPB_Graphics3D_1_0>()) + return PP_ERROR_NOINTERFACE; + + return get_interface<PPB_Graphics3D_1_0>()->SetAttribs( + pp_resource(), + attrib_list); +} + +int32_t Graphics3D::ResizeBuffers(int32_t width, int32_t height) { + if (!has_interface<PPB_Graphics3D_1_0>()) + return PP_ERROR_NOINTERFACE; + + return get_interface<PPB_Graphics3D_1_0>()->ResizeBuffers( + pp_resource(), width, height); +} + +int32_t Graphics3D::SwapBuffers(const CompletionCallback& cc) { + if (!has_interface<PPB_Graphics3D_1_0>()) + return PP_ERROR_NOINTERFACE; + + return get_interface<PPB_Graphics3D_1_0>()->SwapBuffers( + pp_resource(), + cc.pp_completion_callback()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/graphics_3d.h b/chromium/ppapi/cpp/graphics_3d.h new file mode 100644 index 00000000000..31af6877829 --- /dev/null +++ b/chromium/ppapi/cpp/graphics_3d.h @@ -0,0 +1,193 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_GRAPHICS_3D_H_ +#define PPAPI_CPP_GRAPHICS_3D_H_ + +#include "ppapi/c/ppb_graphics_3d.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the API to create a 3D rendering context in the browser. +namespace pp { + +class CompletionCallback; +class InstanceHandle; + +/// This class represents a 3D rendering context in the browser. +class Graphics3D : public Resource { + public: + /// Default constructor for creating an is_null() Graphics3D object. + Graphics3D(); + + /// A constructor for creating and initializing a 3D rendering context. + /// The returned context is created off-screen and must be attached + /// to a module instance using <code>Instance::BindGraphics</code> to draw on + /// the web page. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + /// + /// @param[in] attrib_list The list of attributes (name=value pairs) for the + /// context. The list is terminated with + /// <code>PP_GRAPHICS3DATTRIB_NONE</code>. The <code>attrib_list</code> may + /// be <code>NULL</code> or empty (first attribute is + /// <code>PP_GRAPHICS3DATTRIB_NONE</code>). If an attribute is not specified + /// in <code>attrib_list</code>, then the default value is used. + /// + /// Attributes are classified into two categories: + /// + /// 1. AtLeast: The attribute value in the returned context will meet or + /// exceed the value requested when creating the object. + /// 2. Exact: The attribute value in the returned context is equal to + /// the value requested when creating the object. + /// + /// AtLeast attributes are (all have default values of 0): + /// + /// <code>PP_GRAPHICS3DATTRIB_ALPHA_SIZE</code> + /// <code>PP_GRAPHICS3DATTRIB_BLUE_SIZE</code> + /// <code>PP_GRAPHICS3DATTRIB_GREEN_SIZE</code> + /// <code>PP_GRAPHICS3DATTRIB_RED_SIZE</code> + /// <code>PP_GRAPHICS3DATTRIB_DEPTH_SIZE</code> + /// <code>PP_GRAPHICS3DATTRIB_STENCIL_SIZE</code> + /// <code>PP_GRAPHICS3DATTRIB_SAMPLES</code> + /// <code>PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS</code> + /// + /// Exact attributes are: + /// + /// <code>PP_GRAPHICS3DATTRIB_WIDTH</code> Default 0 + /// <code>PP_GRAPHICS3DATTRIB_HEIGHT</code> Default 0 + /// <code>PP_GRAPHICS3DATTRIB_SWAP_BEHAVIOR</code> + /// Default: Implementation defined. + /// + /// On failure, the object will be is_null(). + Graphics3D(const InstanceHandle& instance, + const int32_t attrib_list[]); + + /// A constructor for creating and initializing a 3D rendering context. The + /// returned context is created off-screen. It must be attached to a + /// module instance using <code>Instance::BindGraphics</code> to draw on the + /// web page. + /// + /// This constructor is identical to the 2-argument version except that this + /// version allows sharing of resources with another context. + /// + /// @param[in] instance The instance that will own the new Graphics3D. + /// + /// @param[in] share_context Specifies the context with which all + /// shareable data will be shared. The shareable data is defined by the + /// client API (note that for OpenGL and OpenGL ES, shareable data excludes + /// texture objects named 0). An arbitrary number of Graphics3D resources + /// can share data in this fashion. + // + /// @param[in] attrib_list The list of attributes for the context. See the + /// 2-argument version of this constructor for more information. + /// + /// On failure, the object will be is_null(). + Graphics3D(const InstanceHandle& instance, + const Graphics3D& share_context, + const int32_t attrib_list[]); + + /// Destructor. + ~Graphics3D(); + + /// GetAttribs() retrieves the value for each attribute in + /// <code>attrib_list</code>. The list has the same structure as described + /// for the constructor. All attribute values specified in + /// <code>pp_graphics_3d.h</code> can be retrieved. + /// + /// @param[in,out] attrib_list The list of attributes (name=value pairs) for + /// the context. The list is terminated with + /// <code>PP_GRAPHICS3DATTRIB_NONE</code>. + /// + /// The following error codes may be returned on failure: + /// + /// PP_ERROR_BADRESOURCE if context is invalid. + /// PP_ERROR_BADARGUMENT if <code>attrib_list</code> is NULL or any attribute + /// in the <code>attrib_list</code> is not a valid attribute. + /// + /// <strong>Example:</strong> + /// + /// @code + /// int attrib_list[] = {PP_GRAPHICS3DATTRIB_RED_SIZE, 0, + /// PP_GRAPHICS3DATTRIB_GREEN_SIZE, 0, + /// PP_GRAPHICS3DATTRIB_BLUE_SIZE, 0, + /// PP_GRAPHICS3DATTRIB_NONE}; + /// GetAttribs(context, attrib_list); + /// int red_bits = attrib_list[1]; + /// int green_bits = attrib_list[3]; + /// int blue_bits = attrib_list[5]; + /// @endcode + /// + /// This example retrieves the values for rgb bits in the color buffer. + int32_t GetAttribs(int32_t attrib_list[]) const; + + /// SetAttribs() sets the values for each attribute in + /// <code>attrib_list</code>. The list has the same structure as the list + /// used in the constructors. + /// + /// Attributes that can be specified are: + /// - PP_GRAPHICS3DATTRIB_SWAP_BEHAVIOR + /// + /// On failure the following error codes may be returned: + /// - PP_ERROR_BADRESOURCE if context is invalid. + /// - PP_ERROR_BADARGUMENT if attrib_list is NULL or any attribute in the + /// attrib_list is not a valid attribute. + int32_t SetAttribs(const int32_t attrib_list[]); + + /// ResizeBuffers() resizes the backing surface for the context. + /// + /// @param[in] width The width of the backing surface. + /// @param[in] height The height of the backing surface. + /// + /// @return An int32_t containing <code>PP_ERROR_BADRESOURCE</code> if + /// context is invalid or <code>PP_ERROR_BADARGUMENT</code> if the value + /// specified for width or height is less than zero. + /// <code>PP_ERROR_NOMEMORY</code> might be returned on the next + /// SwapBuffers() callback if the surface could not be resized due to + /// insufficient resources. + int32_t ResizeBuffers(int32_t width, int32_t height); + + /// SwapBuffers() makes the contents of the color buffer available for + /// compositing. This function has no effect on off-screen surfaces: surfaces + /// not bound to any module instance. The contents of ancillary buffers are + /// always undefined after calling SwapBuffers(). The contents of the color + /// buffer are undefined if the value of the + /// <code>PP_GRAPHICS3DATTRIB_SWAP_BEHAVIOR</code> attribute of context is + /// not <code>PP_GRAPHICS3DATTRIB_BUFFER_PRESERVED</code>. + /// + /// SwapBuffers() runs in asynchronous mode. Specify a callback function and + /// the argument for that callback function. The callback function will be + /// executed on the calling thread after the color buffer has been composited + /// with rest of the html page. While you are waiting for a SwapBuffers() + /// callback, additional calls to SwapBuffers() will fail. + /// + /// Because the callback is executed (or thread unblocked) only when the + /// instance's current state is actually on the screen, this function + /// provides a way to rate limit animations. By waiting until the image is on + /// the screen before painting the next frame, you can ensure you're not + /// generating updates faster than the screen can be updated. + /// + /// SwapBuffers() performs an implicit flush operation on context. + /// If the context gets into an unrecoverable error condition while + /// processing a command, the error code will be returned as the argument + /// for the callback. The callback may return the following error codes: + /// + /// <code>PP_ERROR_NOMEMORY</code> + /// <code>PP_ERROR_CONTEXT_LOST</code> + /// + /// Note that the same error code may also be obtained by calling GetError(). + /// + /// param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion of SwapBuffers(). + /// + /// @return An int32_t containing <code>PP_ERROR_BADRESOURCE</code> if + /// context is invalid or <code>PP_ERROR_BADARGUMENT</code> if callback is + /// invalid. + int32_t SwapBuffers(const CompletionCallback& cc); +}; + +} // namespace pp + +#endif // PPAPI_CPP_GRAPHICS_3D_H_ diff --git a/chromium/ppapi/cpp/graphics_3d_client.cc b/chromium/ppapi/cpp/graphics_3d_client.cc new file mode 100644 index 00000000000..a00d2f3db99 --- /dev/null +++ b/chromium/ppapi/cpp/graphics_3d_client.cc @@ -0,0 +1,45 @@ +// Copyright (c) 2011 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 "ppapi/cpp/graphics_3d_client.h" + +#include "ppapi/c/ppp_graphics_3d.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +const char kPPPGraphics3DInterface[] = PPP_GRAPHICS_3D_INTERFACE; + +void Graphics3D_ContextLost(PP_Instance instance) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPGraphics3DInterface); + if (!object) + return; + return static_cast<Graphics3DClient*>(object)->Graphics3DContextLost(); +} + +static PPP_Graphics3D graphics3d_interface = { + &Graphics3D_ContextLost, +}; + +} // namespace + +Graphics3DClient::Graphics3DClient(Instance* instance) + : associated_instance_(instance) { + Module::Get()->AddPluginInterface(kPPPGraphics3DInterface, + &graphics3d_interface); + instance->AddPerInstanceObject(kPPPGraphics3DInterface, this); +} + +Graphics3DClient::~Graphics3DClient() { + Instance::RemovePerInstanceObject(associated_instance_, + kPPPGraphics3DInterface, this); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/graphics_3d_client.h b/chromium/ppapi/cpp/graphics_3d_client.h new file mode 100644 index 00000000000..186acd4bfd3 --- /dev/null +++ b/chromium/ppapi/cpp/graphics_3d_client.h @@ -0,0 +1,43 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_GRAPHICS_3D_CLIENT_H_ +#define PPAPI_CPP_GRAPHICS_3D_CLIENT_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/instance_handle.h" + +/// @file +/// This file defines the API for callbacks related to 3D. + +namespace pp { + +class Instance; + +// This class provides a C++ interface for callbacks related to 3D. You +// would normally use multiple inheritance to derive from this class in your +// instance. +class Graphics3DClient { + public: + /// + /// A constructor for creating a Graphics3DClient. + /// + /// @param[in] instance The instance that will own the new + /// <code>Graphics3DClient</code>. + explicit Graphics3DClient(Instance* instance); + + /// Destructor. + virtual ~Graphics3DClient(); + + /// Graphics3DContextLost() is a notification that the context was lost for + /// the 3D devices. + virtual void Graphics3DContextLost() = 0; + + private: + InstanceHandle associated_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_GRAPHICS_3D_CLIENT_H_ diff --git a/chromium/ppapi/cpp/host_resolver.cc b/chromium/ppapi/cpp/host_resolver.cc new file mode 100644 index 00000000000..656c743775f --- /dev/null +++ b/chromium/ppapi/cpp/host_resolver.cc @@ -0,0 +1,93 @@ +// Copyright 2013 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 "ppapi/cpp/host_resolver.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_HostResolver_1_0>() { + return PPB_HOSTRESOLVER_INTERFACE_1_0; +} + +} // namespace + +HostResolver::HostResolver() { +} + +HostResolver::HostResolver(const InstanceHandle& instance) { + if (has_interface<PPB_HostResolver_1_0>()) { + PassRefFromConstructor(get_interface<PPB_HostResolver_1_0>()->Create( + instance.pp_instance())); + } +} + +HostResolver::HostResolver(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +HostResolver::HostResolver(const HostResolver& other) : Resource(other) { +} + +HostResolver::~HostResolver() { +} + +HostResolver& HostResolver::operator=(const HostResolver& other) { + Resource::operator=(other); + return *this; +} + +// static +bool HostResolver::IsAvailable() { + return has_interface<PPB_HostResolver_1_0>(); +} + +int32_t HostResolver::Resolve(const char* host, + uint16_t port, + const PP_HostResolver_Hint& hint, + const CompletionCallback& callback) { + if (has_interface<PPB_HostResolver_1_0>()) { + return get_interface<PPB_HostResolver_1_0>()->Resolve( + pp_resource(), host, port, &hint, callback.pp_completion_callback()); + } + + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +Var HostResolver::GetCanonicalName() const { + if (has_interface<PPB_HostResolver_1_0>()) { + return Var(PASS_REF, + get_interface<PPB_HostResolver_1_0>()->GetCanonicalName( + pp_resource())); + } + + return Var(); +} + +uint32_t HostResolver::GetNetAddressCount() const { + if (has_interface<PPB_HostResolver_1_0>()) { + return get_interface<PPB_HostResolver_1_0>()->GetNetAddressCount( + pp_resource()); + } + + return 0; +} + +NetAddress HostResolver::GetNetAddress(uint32_t index) const { + if (has_interface<PPB_HostResolver_1_0>()) { + return NetAddress(PASS_REF, + get_interface<PPB_HostResolver_1_0>()->GetNetAddress( + pp_resource(), index)); + } + + return NetAddress(); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/host_resolver.h b/chromium/ppapi/cpp/host_resolver.h new file mode 100644 index 00000000000..075ba6da0ba --- /dev/null +++ b/chromium/ppapi/cpp/host_resolver.h @@ -0,0 +1,115 @@ +// Copyright 2013 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. + +#ifndef PPAPI_CPP_HOST_RESOLVER_H_ +#define PPAPI_CPP_HOST_RESOLVER_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/ppb_host_resolver.h" +#include "ppapi/cpp/net_address.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +class CompletionCallback; +class InstanceHandle; + +/// The <code>HostResolver</code> class supports host name resolution. +/// +/// Permissions: In order to run <code>Resolve()</code>, apps permission +/// <code>socket</code> with subrule <code>resolve-host</code> is required. +/// For more details about network communication permissions, please see: +/// http://developer.chrome.com/apps/app_network.html +class HostResolver : public Resource { + public: + /// Default constructor for creating an is_null() <code>HostResolver</code> + /// object. + HostResolver(); + + /// A constructor used to create a <code>HostResolver</code> object. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit HostResolver(const InstanceHandle& instance); + + /// A constructor used when you have received a <code>PP_Resource</code> as a + /// return value that has had 1 ref added for you. + /// + /// @param[in] resource A <code>PPB_HostResolver</code> resource. + HostResolver(PassRef, PP_Resource resource); + + /// The copy constructor for <code>HostResolver</code>. + /// + /// @param[in] other A reference to another <code>HostResolver</code>. + HostResolver(const HostResolver& other); + + /// The destructor. + virtual ~HostResolver(); + + /// The assignment operator for <code>HostResolver</code>. + /// + /// @param[in] other A reference to another <code>HostResolver</code>. + /// + /// @return A reference to this <code>HostResolver</code> object. + HostResolver& operator=(const HostResolver& other); + + /// Static function for determining whether the browser supports the + /// <code>PPB_HostResolver</code> interface. + /// + /// @return true if the interface is available, false otherwise. + static bool IsAvailable(); + + /// Requests resolution of a host name. If the call completes successully, the + /// results can be retrieved by <code>GetCanonicalName()</code>, + /// <code>GetNetAddressCount()</code> and <code>GetNetAddress()</code>. + /// + /// @param[in] host The host name (or IP address literal) to resolve. + /// @param[in] port The port number to be set in the resulting network + /// addresses. + /// @param[in] hint A <code>PP_HostResolver_Hint</code> structure + /// providing hints for host resolution. + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion. + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + /// <code>PP_ERROR_NOACCESS</code> will be returned if the caller doesn't have + /// required permissions. <code>PP_ERROR_NAME_NOT_RESOLVED</code> will be + /// returned if the host name couldn't be resolved. + int32_t Resolve(const char* host, + uint16_t port, + const PP_HostResolver_Hint& hint, + const CompletionCallback& callback); + + /// Gets the canonical name of the host. + /// + /// @return A string <code>Var</code> on success, which is an empty string + /// if <code>PP_HOSTRESOLVER_FLAG_CANONNAME</code> is not set in the hint + /// flags when calling <code>Resolve()</code>; an undefined <code>Var</code> + /// if there is a pending <code>Resolve()</code> call or the previous + /// <code>Resolve()</code> call failed. + Var GetCanonicalName() const; + + /// Gets the number of network addresses. + /// + /// @return The number of available network addresses on success; 0 if there + /// is a pending <code>Resolve()</code> call or the previous + /// <code>Resolve()</code> call failed. + uint32_t GetNetAddressCount() const; + + /// Gets a network address. + /// + /// @param[in] index An index indicating which address to return. + /// + /// @return A <code>NetAddress</code> object. The object will be null + /// (i.e., is_null() returns true) if there is a pending + /// <code>Resolve()</code> call or the previous <code>Resolve()</code> call + /// failed, or the specified index is out of range. + NetAddress GetNetAddress(uint32_t index) const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_HOST_RESOLVER_H_ diff --git a/chromium/ppapi/cpp/image_data.cc b/chromium/ppapi/cpp/image_data.cc new file mode 100644 index 00000000000..a0c3aeff796 --- /dev/null +++ b/chromium/ppapi/cpp/image_data.cc @@ -0,0 +1,100 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/image_data.h" + +#include <string.h> // Needed for memset. + +#include <algorithm> + +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_ImageData_1_0>() { + return PPB_IMAGEDATA_INTERFACE_1_0; +} + +} // namespace + +ImageData::ImageData() : data_(NULL) { + memset(&desc_, 0, sizeof(PP_ImageDataDesc)); +} + +ImageData::ImageData(const ImageData& other) + : Resource(other), + desc_(other.desc_), + data_(other.data_) { +} + +ImageData::ImageData(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource), + data_(NULL) { + memset(&desc_, 0, sizeof(PP_ImageDataDesc)); + InitData(); +} + +ImageData::ImageData(const InstanceHandle& instance, + PP_ImageDataFormat format, + const Size& size, + bool init_to_zero) + : data_(NULL) { + memset(&desc_, 0, sizeof(PP_ImageDataDesc)); + + if (!has_interface<PPB_ImageData_1_0>()) + return; + + PassRefFromConstructor(get_interface<PPB_ImageData_1_0>()->Create( + instance.pp_instance(), format, &size.pp_size(), + PP_FromBool(init_to_zero))); + InitData(); +} + +ImageData& ImageData::operator=(const ImageData& other) { + Resource::operator=(other); + desc_ = other.desc_; + data_ = other.data_; + return *this; +} + +const uint32_t* ImageData::GetAddr32(const Point& coord) const { + // Prefer evil const casts rather than evil code duplication. + return const_cast<ImageData*>(this)->GetAddr32(coord); +} + +uint32_t* ImageData::GetAddr32(const Point& coord) { + // If we add more image format types that aren't 32-bit, we'd want to check + // here and fail. + return reinterpret_cast<uint32_t*>( + &static_cast<char*>(data())[coord.y() * stride() + coord.x() * 4]); +} + +// static +bool ImageData::IsImageDataFormatSupported(PP_ImageDataFormat format) { + if (!has_interface<PPB_ImageData_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_ImageData_1_0>()-> + IsImageDataFormatSupported(format)); +} + +// static +PP_ImageDataFormat ImageData::GetNativeImageDataFormat() { + if (!has_interface<PPB_ImageData_1_0>()) + return PP_IMAGEDATAFORMAT_BGRA_PREMUL; // Default to something on failure. + return get_interface<PPB_ImageData_1_0>()->GetNativeImageDataFormat(); +} + +void ImageData::InitData() { + if (!has_interface<PPB_ImageData_1_0>()) + return; + if (!get_interface<PPB_ImageData_1_0>()->Describe(pp_resource(), &desc_) || + !(data_ = get_interface<PPB_ImageData_1_0>()->Map(pp_resource()))) + *this = ImageData(); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/image_data.h b/chromium/ppapi/cpp/image_data.h new file mode 100644 index 00000000000..d94ea820b53 --- /dev/null +++ b/chromium/ppapi/cpp/image_data.h @@ -0,0 +1,141 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_IMAGE_DATA_H_ +#define PPAPI_CPP_IMAGE_DATA_H_ + +#include "ppapi/c/ppb_image_data.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/size.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the APIs for determining how a browser +/// handles image data. +namespace pp { + +class InstanceHandle; + +class ImageData : public Resource { + public: + /// Default constructor for creating an is_null() <code>ImageData</code> + /// object. + ImageData(); + + /// A constructor used when you have received a <code>PP_Resource</code> as a + /// return value that has already been reference counted. + /// + /// @param[in] resource A PP_Resource corresponding to image data. + ImageData(PassRef, PP_Resource resource); + + /// The copy constructor for <code>ImageData</code>. This constructor + /// produces an <code>ImageData</code> object that shares the underlying + /// <code>Image</code> resource with <code>other</code>. + /// + /// @param[in] other A pointer to an image data. + ImageData(const ImageData& other); + + /// A constructor that allocates a new <code>ImageData</code> in the browser + /// with the provided parameters. The resulting object will be is_null() if + /// the allocation failed. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + /// + /// @param[in] format A PP_ImageDataFormat containing desired image format. + /// PP_ImageDataFormat is an enumeration of the different types of + /// image data formats. Refer to + /// <a href="../pepperc/ppb__image__data_8h.html"> + /// <code>ppb_image_data.h</code></a> for further information. + /// + /// @param[in] size A pointer to a <code>Size</code> containing the image + /// size. + /// + /// @param[in] init_to_zero A bool used to determine transparency at + /// creation. Set the <code>init_to_zero</code> flag if you want the bitmap + /// initialized to transparent during the creation process. If this flag is + /// not set, the current contents of the bitmap will be undefined, and the + /// module should be sure to set all the pixels. + ImageData(const InstanceHandle& instance, + PP_ImageDataFormat format, + const Size& size, + bool init_to_zero); + + /// This function decrements the reference count of this + /// <code>ImageData</code> and increments the reference count of the + /// <code>other</code> <code>ImageData</code>. This <code>ImageData</code> + /// shares the underlying image resource with <code>other</code>. + /// + /// @param[in] other An other image data. + /// + /// @return A new image data context. + ImageData& operator=(const ImageData& other); + + /// IsImageDataFormatSupported() returns <code>true</code> if the supplied + /// format is supported by the browser. Note: + /// <code>PP_IMAGEDATAFORMAT_BGRA_PREMUL</code> and + /// <code>PP_IMAGEDATAFORMAT_RGBA_PREMUL</code> formats are always supported. + /// Other image formats do not make this guarantee, and should be checked + /// first with IsImageDataFormatSupported() before using. + /// + /// @param[in] format Image data format. + /// + /// @return <code>true</code> if the format is supported by the browser. + static bool IsImageDataFormatSupported(PP_ImageDataFormat format); + + /// GetNativeImageDataFormat() determines the browser's preferred format for + /// images. Using this format guarantees no extra conversions will occur when + /// painting. + /// + /// @return <code>PP_ImageDataFormat</code> containing the preferred format. + static PP_ImageDataFormat GetNativeImageDataFormat(); + + /// A getter function for returning the current format for images. + /// + /// @return <code>PP_ImageDataFormat</code> containing the preferred format. + PP_ImageDataFormat format() const { return desc_.format; } + + /// A getter function for returning the image size. + /// + /// @return The image size in pixels. + pp::Size size() const { return desc_.size; } + + /// A getter function for returning the row width in bytes. + /// + /// @return The row width in bytes. + int32_t stride() const { return desc_.stride; } + + /// A getter function for returning a raw pointer to the image pixels. + /// + /// @return A raw pointer to the image pixels. + void* data() const { return data_; } + + /// This function is used retrieve the address of the given pixel for 32-bit + /// pixel formats. + /// + /// @param[in] coord A <code>Point</code> representing the x and y + /// coordinates for a specific pixel. + /// + /// @return The address for the pixel. + const uint32_t* GetAddr32(const Point& coord) const; + + /// This function is used retrieve the address of the given pixel for 32-bit + /// pixel formats. + /// + /// @param[in] coord A <code>Point</code> representing the x and y + /// coordinates for a specific pixel. + /// + /// @return The address for the pixel. + uint32_t* GetAddr32(const Point& coord); + + private: + void InitData(); + + PP_ImageDataDesc desc_; + void* data_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_IMAGE_DATA_H_ diff --git a/chromium/ppapi/cpp/input_event.cc b/chromium/ppapi/cpp/input_event.cc new file mode 100644 index 00000000000..e4e00039300 --- /dev/null +++ b/chromium/ppapi/cpp/input_event.cc @@ -0,0 +1,362 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/input_event.h" + +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/touch_point.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_InputEvent_1_0>() { + return PPB_INPUT_EVENT_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_KeyboardInputEvent_1_0>() { + return PPB_KEYBOARD_INPUT_EVENT_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_MouseInputEvent_1_1>() { + return PPB_MOUSE_INPUT_EVENT_INTERFACE_1_1; +} + +template <> const char* interface_name<PPB_WheelInputEvent_1_0>() { + return PPB_WHEEL_INPUT_EVENT_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_TouchInputEvent_1_0>() { + return PPB_TOUCH_INPUT_EVENT_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_IMEInputEvent_1_0>() { + return PPB_IME_INPUT_EVENT_INTERFACE_1_0; +} + +} // namespace + +// InputEvent ------------------------------------------------------------------ + +InputEvent::InputEvent() : Resource() { +} + +InputEvent::InputEvent(PP_Resource input_event_resource) : Resource() { + // Type check the input event before setting it. + if (!has_interface<PPB_InputEvent_1_0>()) + return; + if (get_interface<PPB_InputEvent_1_0>()->IsInputEvent(input_event_resource)) { + Module::Get()->core()->AddRefResource(input_event_resource); + PassRefFromConstructor(input_event_resource); + } +} + +InputEvent::~InputEvent() { +} + +PP_InputEvent_Type InputEvent::GetType() const { + if (!has_interface<PPB_InputEvent_1_0>()) + return PP_INPUTEVENT_TYPE_UNDEFINED; + return get_interface<PPB_InputEvent_1_0>()->GetType(pp_resource()); +} + +PP_TimeTicks InputEvent::GetTimeStamp() const { + if (!has_interface<PPB_InputEvent_1_0>()) + return 0.0f; + return get_interface<PPB_InputEvent_1_0>()->GetTimeStamp(pp_resource()); +} + +uint32_t InputEvent::GetModifiers() const { + if (!has_interface<PPB_InputEvent_1_0>()) + return 0; + return get_interface<PPB_InputEvent_1_0>()->GetModifiers(pp_resource()); +} + +// MouseInputEvent ------------------------------------------------------------- + +MouseInputEvent::MouseInputEvent() : InputEvent() { +} + +MouseInputEvent::MouseInputEvent(const InputEvent& event) : InputEvent() { + // Type check the input event before setting it. + if (!has_interface<PPB_MouseInputEvent_1_1>()) + return; + if (get_interface<PPB_MouseInputEvent_1_1>()->IsMouseInputEvent( + event.pp_resource())) { + Module::Get()->core()->AddRefResource(event.pp_resource()); + PassRefFromConstructor(event.pp_resource()); + } +} + +MouseInputEvent::MouseInputEvent(const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + uint32_t modifiers, + PP_InputEvent_MouseButton mouse_button, + const Point& mouse_position, + int32_t click_count, + const Point& mouse_movement) { + // Type check the input event before setting it. + if (!has_interface<PPB_MouseInputEvent_1_1>()) + return; + PassRefFromConstructor(get_interface<PPB_MouseInputEvent_1_1>()->Create( + instance.pp_instance(), type, time_stamp, modifiers, mouse_button, + &mouse_position.pp_point(), click_count, &mouse_movement.pp_point())); +} + +PP_InputEvent_MouseButton MouseInputEvent::GetButton() const { + if (!has_interface<PPB_MouseInputEvent_1_1>()) + return PP_INPUTEVENT_MOUSEBUTTON_NONE; + return get_interface<PPB_MouseInputEvent_1_1>()->GetButton(pp_resource()); +} + +Point MouseInputEvent::GetPosition() const { + if (!has_interface<PPB_MouseInputEvent_1_1>()) + return Point(); + return get_interface<PPB_MouseInputEvent_1_1>()->GetPosition(pp_resource()); +} + +int32_t MouseInputEvent::GetClickCount() const { + if (!has_interface<PPB_MouseInputEvent_1_1>()) + return 0; + return get_interface<PPB_MouseInputEvent_1_1>()->GetClickCount(pp_resource()); +} + +Point MouseInputEvent::GetMovement() const { + if (!has_interface<PPB_MouseInputEvent_1_1>()) + return Point(); + return get_interface<PPB_MouseInputEvent_1_1>()->GetMovement(pp_resource()); +} + +// WheelInputEvent ------------------------------------------------------------- + +WheelInputEvent::WheelInputEvent() : InputEvent() { +} + +WheelInputEvent::WheelInputEvent(const InputEvent& event) : InputEvent() { + // Type check the input event before setting it. + if (!has_interface<PPB_WheelInputEvent_1_0>()) + return; + if (get_interface<PPB_WheelInputEvent_1_0>()->IsWheelInputEvent( + event.pp_resource())) { + Module::Get()->core()->AddRefResource(event.pp_resource()); + PassRefFromConstructor(event.pp_resource()); + } +} + +WheelInputEvent::WheelInputEvent(const InstanceHandle& instance, + PP_TimeTicks time_stamp, + uint32_t modifiers, + const FloatPoint& wheel_delta, + const FloatPoint& wheel_ticks, + bool scroll_by_page) { + // Type check the input event before setting it. + if (!has_interface<PPB_WheelInputEvent_1_0>()) + return; + PassRefFromConstructor(get_interface<PPB_WheelInputEvent_1_0>()->Create( + instance.pp_instance(), time_stamp, modifiers, + &wheel_delta.pp_float_point(), &wheel_ticks.pp_float_point(), + PP_FromBool(scroll_by_page))); +} + +FloatPoint WheelInputEvent::GetDelta() const { + if (!has_interface<PPB_WheelInputEvent_1_0>()) + return FloatPoint(); + return get_interface<PPB_WheelInputEvent_1_0>()->GetDelta(pp_resource()); +} + +FloatPoint WheelInputEvent::GetTicks() const { + if (!has_interface<PPB_WheelInputEvent_1_0>()) + return FloatPoint(); + return get_interface<PPB_WheelInputEvent_1_0>()->GetTicks(pp_resource()); +} + +bool WheelInputEvent::GetScrollByPage() const { + if (!has_interface<PPB_WheelInputEvent_1_0>()) + return false; + return PP_ToBool( + get_interface<PPB_WheelInputEvent_1_0>()->GetScrollByPage(pp_resource())); +} + +// KeyboardInputEvent ---------------------------------------------------------- + +KeyboardInputEvent::KeyboardInputEvent() : InputEvent() { +} + +KeyboardInputEvent::KeyboardInputEvent(const InputEvent& event) : InputEvent() { + // Type check the input event before setting it. + if (!has_interface<PPB_KeyboardInputEvent_1_0>()) + return; + if (get_interface<PPB_KeyboardInputEvent_1_0>()->IsKeyboardInputEvent( + event.pp_resource())) { + Module::Get()->core()->AddRefResource(event.pp_resource()); + PassRefFromConstructor(event.pp_resource()); + } +} + +KeyboardInputEvent::KeyboardInputEvent(const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + uint32_t modifiers, + uint32_t key_code, + const Var& character_text) { + // Type check the input event before setting it. + if (!has_interface<PPB_KeyboardInputEvent_1_0>()) + return; + PassRefFromConstructor(get_interface<PPB_KeyboardInputEvent_1_0>()->Create( + instance.pp_instance(), type, time_stamp, modifiers, key_code, + character_text.pp_var())); +} + +uint32_t KeyboardInputEvent::GetKeyCode() const { + if (!has_interface<PPB_KeyboardInputEvent_1_0>()) + return 0; + return get_interface<PPB_KeyboardInputEvent_1_0>()->GetKeyCode(pp_resource()); +} + +Var KeyboardInputEvent::GetCharacterText() const { + if (!has_interface<PPB_KeyboardInputEvent_1_0>()) + return Var(); + return Var(PASS_REF, + get_interface<PPB_KeyboardInputEvent_1_0>()->GetCharacterText( + pp_resource())); +} + +// TouchInputEvent ------------------------------------------------------------ +TouchInputEvent::TouchInputEvent() : InputEvent() { +} + +TouchInputEvent::TouchInputEvent(const InputEvent& event) : InputEvent() { + if (!has_interface<PPB_TouchInputEvent_1_0>()) + return; + // Type check the input event before setting it. + if (get_interface<PPB_TouchInputEvent_1_0>()->IsTouchInputEvent( + event.pp_resource())) { + Module::Get()->core()->AddRefResource(event.pp_resource()); + PassRefFromConstructor(event.pp_resource()); + } +} + +TouchInputEvent::TouchInputEvent(const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + uint32_t modifiers) { + // Type check the input event before setting it. + if (!has_interface<PPB_TouchInputEvent_1_0>()) + return; + PassRefFromConstructor(get_interface<PPB_TouchInputEvent_1_0>()->Create( + instance.pp_instance(), type, time_stamp, modifiers)); +} + +void TouchInputEvent::AddTouchPoint(PP_TouchListType list, + PP_TouchPoint point) { + if (!has_interface<PPB_TouchInputEvent_1_0>()) + return; + get_interface<PPB_TouchInputEvent_1_0>()->AddTouchPoint(pp_resource(), list, + &point); +} + +uint32_t TouchInputEvent::GetTouchCount(PP_TouchListType list) const { + if (!has_interface<PPB_TouchInputEvent_1_0>()) + return 0; + return get_interface<PPB_TouchInputEvent_1_0>()->GetTouchCount(pp_resource(), + list); +} + +TouchPoint TouchInputEvent::GetTouchById(PP_TouchListType list, + uint32_t id) const { + if (!has_interface<PPB_TouchInputEvent_1_0>()) + return TouchPoint(); + return TouchPoint(get_interface<PPB_TouchInputEvent_1_0>()-> + GetTouchById(pp_resource(), list, id)); +} + +TouchPoint TouchInputEvent::GetTouchByIndex(PP_TouchListType list, + uint32_t index) const { + if (!has_interface<PPB_TouchInputEvent_1_0>()) + return TouchPoint(); + return TouchPoint(get_interface<PPB_TouchInputEvent_1_0>()-> + GetTouchByIndex(pp_resource(), list, index)); +} + +// IMEInputEvent ------------------------------------------------------- + +IMEInputEvent::IMEInputEvent() : InputEvent() { +} + +IMEInputEvent::IMEInputEvent(const InputEvent& event) : InputEvent() { + if (has_interface<PPB_IMEInputEvent_1_0>()) { + if (get_interface<PPB_IMEInputEvent_1_0>()->IsIMEInputEvent( + event.pp_resource())) { + Module::Get()->core()->AddRefResource(event.pp_resource()); + PassRefFromConstructor(event.pp_resource()); + } + } +} + +IMEInputEvent::IMEInputEvent( + const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + const Var& text, + const std::vector<uint32_t>& segment_offsets, + int32_t target_segment, + const std::pair<uint32_t, uint32_t>& selection) : InputEvent() { + if (!has_interface<PPB_IMEInputEvent_1_0>()) + return; + uint32_t dummy = 0; + PassRefFromConstructor(get_interface<PPB_IMEInputEvent_1_0>()->Create( + instance.pp_instance(), type, time_stamp, text.pp_var(), + segment_offsets.empty() ? 0 : segment_offsets.size() - 1, + segment_offsets.empty() ? &dummy : &segment_offsets[0], + target_segment, selection.first, selection.second)); +} + + +Var IMEInputEvent::GetText() const { + if (has_interface<PPB_IMEInputEvent_1_0>()) { + return Var(PASS_REF, + get_interface<PPB_IMEInputEvent_1_0>()->GetText( + pp_resource())); + } + return Var(); +} + +uint32_t IMEInputEvent::GetSegmentNumber() const { + if (has_interface<PPB_IMEInputEvent_1_0>()) { + return get_interface<PPB_IMEInputEvent_1_0>()->GetSegmentNumber( + pp_resource()); + } + return 0; +} + +uint32_t IMEInputEvent::GetSegmentOffset(uint32_t index) const { + if (has_interface<PPB_IMEInputEvent_1_0>()) { + return get_interface<PPB_IMEInputEvent_1_0>()->GetSegmentOffset( + pp_resource(), index); + } + return 0; +} + +int32_t IMEInputEvent::GetTargetSegment() const { + if (has_interface<PPB_IMEInputEvent_1_0>()) { + return get_interface<PPB_IMEInputEvent_1_0>()->GetTargetSegment( + pp_resource()); + } + return 0; +} + +void IMEInputEvent::GetSelection(uint32_t* start, uint32_t* end) const { + if (has_interface<PPB_IMEInputEvent_1_0>()) { + get_interface<PPB_IMEInputEvent_1_0>()->GetSelection(pp_resource(), + start, + end); + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/input_event.h b/chromium/ppapi/cpp/input_event.h new file mode 100644 index 00000000000..69651841d01 --- /dev/null +++ b/chromium/ppapi/cpp/input_event.h @@ -0,0 +1,432 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_INPUT_EVENT_H_ +#define PPAPI_CPP_INPUT_EVENT_H_ + +#include <string> +#include <vector> + +#include "ppapi/c/ppb_input_event.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/touch_point.h" + +/// @file +/// This file defines the API used to handle mouse and keyboard input events. + +namespace pp { + +class FloatPoint; +class InstanceHandle; +class Point; +class Var; + +/// This class represents an input event resource. Normally you will get passed +/// this object through the HandleInputEvent() function on the +/// <code>Instance</code> object. +/// +/// Typically you would check the type of the event and then create the +/// appropriate event-specific object to query the properties. +/// +/// <strong>Example:</strong> +/// @code +/// +/// bool MyInstance::HandleInputEvent(const pp::InputEvent& event) { +/// switch (event.GetType()) { +/// case PP_INPUTEVENT_TYPE_MOUSEDOWN { +/// pp::MouseInputEvent mouse_event(event); +/// return HandleMouseDown(mouse_event.GetMousePosition()); +/// } +/// default: +/// return false; +/// } +/// +/// @endcode +class InputEvent : public Resource { + public: + /// Default constructor that creates an is_null() InputEvent object. + InputEvent(); + + /// This constructor constructs an input event from the provided input event + /// resource ID. The InputEvent object will be is_null() if the given + /// resource is not a valid input event. + /// + /// @param[in] input_event_resource A input event resource ID. + explicit InputEvent(PP_Resource input_event_resource); + + ~InputEvent(); + + /// GetType() returns the type of input event for this input event + /// object. + /// + /// @return A <code>PP_InputEvent_Type</code> if successful, + /// PP_INPUTEVENT_TYPE_UNDEFINED if the resource is invalid. + PP_InputEvent_Type GetType() const; + + /// GetTimeStamp() returns the time that the event was generated. The time + /// will be before the current time since processing and dispatching the + /// event has some overhead. Use this value to compare the times the user + /// generated two events without being sensitive to variable processing time. + /// + /// The return value is in time ticks, which is a monotonically increasing + /// clock not related to the wall clock time. It will not change if the user + /// changes their clock or daylight savings time starts, so can be reliably + /// used to compare events. This means, however, that you can't correlate + /// event times to a particular time of day on the system clock. + /// + /// @return A <code>PP_TimeTicks</code> containing the time the event was + /// generated. + PP_TimeTicks GetTimeStamp() const; + + /// GetModifiers() returns a bitfield indicating which modifiers were down + /// at the time of the event. This is a combination of the flags in the + /// <code>PP_InputEvent_Modifier</code> enum. + /// + /// @return The modifiers associated with the event, or 0 if the given + /// resource is not a valid event resource. + uint32_t GetModifiers() const; +}; + +/// This class handles mouse events. +class MouseInputEvent : public InputEvent { + public: + /// Constructs an is_null() mouse input event object. + MouseInputEvent(); + + /// This constructor constructs a mouse input event object from the provided + /// generic input event. If the given event is itself is_null() or is not + /// a mouse input event, the mouse object will be is_null(). + /// + /// @param event An <code>InputEvent</code>. + explicit MouseInputEvent(const InputEvent& event); + + /// This constructor manually constructs a mouse event from the provided + /// parameters. + /// + /// @param[in] instance The instance for which this event occurred. + /// + /// @param[in] type A <code>PP_InputEvent_Type</code> identifying the type of + /// input event. + /// + /// @param[in] time_stamp A <code>PP_TimeTicks</code> indicating the time + /// when the event occurred. + /// + /// @param[in] modifiers A bit field combination of the + /// <code>PP_InputEvent_Modifier</code> flags. + /// + /// @param[in] mouse_button The button that changed for mouse down or up + /// events. This value will be <code>PP_EVENT_MOUSEBUTTON_NONE</code> for + /// mouse move, enter, and leave events. + /// + /// @param[in] mouse_position A <code>Point</code> containing the x and y + /// position of the mouse when the event occurred. + /// + /// @param[in] click_count + // TODO(brettw) figure out exactly what this means. + /// + /// @param[in] mouse_movement The change in position of the mouse. + MouseInputEvent(const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + uint32_t modifiers, + PP_InputEvent_MouseButton mouse_button, + const Point& mouse_position, + int32_t click_count, + const Point& mouse_movement); + + /// GetButton() returns the mouse position for a mouse input event. + /// + /// @return The mouse button associated with mouse down and up events. This + /// value will be PP_EVENT_MOUSEBUTTON_NONE for mouse move, enter, and leave + /// events, and for all non-mouse events. + PP_InputEvent_MouseButton GetButton() const; + + /// GetPosition() returns the pixel location of a mouse input event. When + /// the mouse is locked, it returns the last known mouse position just as + /// mouse lock was entered. + /// + /// @return The point associated with the mouse event, relative to the upper- + /// left of the instance receiving the event. These values can be negative for + /// mouse drags. The return value will be (0, 0) for non-mouse events. + Point GetPosition() const; + + // TODO(brettw) figure out exactly what this means. + int32_t GetClickCount() const; + + /// Returns the change in position of the mouse. When the mouse is locked, + /// although the mouse position doesn't actually change, this function + /// still provides movement information, which indicates what the change in + /// position would be had the mouse not been locked. + /// + /// @return The change in position of the mouse, relative to the previous + /// position. + Point GetMovement() const; +}; + +class WheelInputEvent : public InputEvent { + public: + /// Constructs an is_null() wheel input event object. + WheelInputEvent(); + + /// This constructor constructs a wheel input event object from the + /// provided generic input event. If the given event is itself + /// is_null() or is not a wheel input event, the wheel object will be + /// is_null(). + /// + /// @param[in] event A generic input event. + explicit WheelInputEvent(const InputEvent& event); + + /// Constructs a wheel input even from the given parameters. + /// + /// @param[in] instance The instance for which this event occurred. + /// + /// @param[in] time_stamp A <code>PP_TimeTicks</code> indicating the time + /// when the event occurred. + /// + /// @param[in] modifiers A bit field combination of the + /// <code>PP_InputEvent_Modifier</code> flags. + /// + /// @param[in] wheel_delta The scroll wheel's horizontal and vertical scroll + /// amounts. + /// + /// @param[in] wheel_ticks The number of "clicks" of the scroll wheel that + /// have produced the event. + /// + /// @param[in] scroll_by_page When true, the user is requesting to scroll + /// by pages. When false, the user is requesting to scroll by lines. + WheelInputEvent(const InstanceHandle& instance, + PP_TimeTicks time_stamp, + uint32_t modifiers, + const FloatPoint& wheel_delta, + const FloatPoint& wheel_ticks, + bool scroll_by_page); + + /// GetDelta() returns the amount vertically and horizontally the user has + /// requested to scroll by with their mouse wheel. A scroll down or to the + /// right (where the content moves up or left) is represented as positive + /// values, and a scroll up or to the left (where the content moves down or + /// right) is represented as negative values. + /// + /// This amount is system dependent and will take into account the user's + /// preferred scroll sensitivity and potentially also nonlinear acceleration + /// based on the speed of the scrolling. + /// + /// Devices will be of varying resolution. Some mice with large detents will + /// only generate integer scroll amounts. But fractional values are also + /// possible, for example, on some trackpads and newer mice that don't have + /// "clicks". + /// + /// @return The vertical and horizontal scroll values. The units are either in + /// pixels (when scroll_by_page is false) or pages (when scroll_by_page is + /// true). For example, y = -3 means scroll up 3 pixels when scroll_by_page + /// is false, and scroll up 3 pages when scroll_by_page is true. + FloatPoint GetDelta() const; + + /// GetTicks() returns the number of "clicks" of the scroll wheel + /// that have produced the event. The value may have system-specific + /// acceleration applied to it, depending on the device. The positive and + /// negative meanings are the same as for GetDelta(). + /// + /// If you are scrolling, you probably want to use the delta values. These + /// tick events can be useful if you aren't doing actual scrolling and don't + /// want or pixel values. An example may be cycling between different items in + /// a game. + /// + /// @return The number of "clicks" of the scroll wheel. You may receive + /// fractional values for the wheel ticks if the mouse wheel is high + /// resolution or doesn't have "clicks". If your program wants discrete + /// events (as in the "picking items" example) you should accumulate + /// fractional click values from multiple messages until the total value + /// reaches positive or negative one. This should represent a similar amount + /// of scrolling as for a mouse that has a discrete mouse wheel. + FloatPoint GetTicks() const; + + /// GetScrollByPage() indicates if the scroll delta x/y indicates pages or + /// lines to scroll by. + /// + /// @return true if the event is a wheel event and the user is scrolling + /// by pages, false if not or if the resource is not a wheel event. + bool GetScrollByPage() const; +}; + +class KeyboardInputEvent : public InputEvent { + public: + /// Constructs an is_null() keyboard input event object. + KeyboardInputEvent(); + + /// Constructs a keyboard input event object from the provided generic input + /// event. If the given event is itself is_null() or is not a keyboard input + /// event, the keybaord object will be is_null(). + /// + /// @param[in] event A generic input event. + explicit KeyboardInputEvent(const InputEvent& event); + + /// Constructs a keyboard input even from the given parameters. + /// + /// @param[in] instance The instance for which this event occurred. + /// + /// @param[in] type A <code>PP_InputEvent_Type</code> identifying the type of + /// input event. + /// + /// @param[in] time_stamp A <code>PP_TimeTicks</code> indicating the time + /// when the event occurred. + /// + /// @param[in] modifiers A bit field combination of the + /// <code>PP_InputEvent_Modifier</code> flags. + /// + /// @param[in] key_code This value reflects the DOM KeyboardEvent + /// <code>keyCode</code> field. Chrome populates this with the Windows-style + /// Virtual Key code of the key. + /// + /// @param[in] character_text This value represents the typed character as a + /// UTF-8 string. + KeyboardInputEvent(const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + uint32_t modifiers, + uint32_t key_code, + const Var& character_text); + + /// Returns the DOM keyCode field for the keyboard event. + /// Chrome populates this with the Windows-style Virtual Key code of the key. + uint32_t GetKeyCode() const; + + /// Returns the typed character for the given character event. + /// + /// @return A string var representing a single typed character for character + /// input events. For non-character input events the return value will be an + /// undefined var. + Var GetCharacterText() const; +}; + +class TouchInputEvent : public InputEvent { + public: + /// Constructs an is_null() touch input event object. + TouchInputEvent(); + + /// Constructs a touch input event object from the given generic input event. + /// If the given event is itself is_null() or is not a touch input event, the + /// touch object will be is_null(). + explicit TouchInputEvent(const InputEvent& event); + + /// Constructs a touch input even from the given parameters. + /// + /// @param[in] instance The instance for which this event occurred. + /// + /// @param[in] type A <code>PP_InputEvent_Type</code> identifying the type of + /// input event. + /// + /// @param[in] time_stamp A <code>PP_TimeTicks</code> indicating the time + /// when the event occurred. + /// + /// @param[in] modifiers A bit field combination of the + /// <code>PP_InputEvent_Modifier</code> flags. + TouchInputEvent(const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + uint32_t modifiers); + + /// Adds the touch-point to the specified TouchList. + void AddTouchPoint(PP_TouchListType list, PP_TouchPoint point); + + /// @return The number of TouchPoints in this TouchList. + uint32_t GetTouchCount(PP_TouchListType list) const; + + /// @return The TouchPoint at the given index of the given list, or an empty + /// TouchPoint if the index is out of range. + TouchPoint GetTouchByIndex(PP_TouchListType list, uint32_t index) const; + + /// @return The TouchPoint in the given list with the given identifier, or an + /// empty TouchPoint if the list does not contain a TouchPoint with that + /// identifier. + TouchPoint GetTouchById(PP_TouchListType list, uint32_t id) const; +}; + +class IMEInputEvent : public InputEvent { + public: + /// Constructs an is_null() IME input event object. + IMEInputEvent(); + + /// Constructs an IME input event object from the provided generic input + /// event. If the given event is itself is_null() or is not an IME input + /// event, the object will be is_null(). + /// + /// @param[in] event A generic input event. + explicit IMEInputEvent(const InputEvent& event); + + /// This constructor manually constructs an IME event from the provided + /// parameters. + /// + /// @param[in] instance The instance for which this event occurred. + /// + /// @param[in] type A <code>PP_InputEvent_Type</code> identifying the type of + /// input event. The type must be one of the ime event types. + /// + /// @param[in] time_stamp A <code>PP_TimeTicks</code> indicating the time + /// when the event occurred. + /// + /// @param[in] text The string returned by <code>GetText</code>. + /// + /// @param[in] segment_offsets The array of numbers returned by + /// <code>GetSegmentOffset</code>. + /// + /// @param[in] target_segment The number returned by + /// <code>GetTargetSegment</code>. + /// + /// @param[in] selection The range returned by <code>GetSelection</code>. + IMEInputEvent(const InstanceHandle& instance, + PP_InputEvent_Type type, + PP_TimeTicks time_stamp, + const Var& text, + const std::vector<uint32_t>& segment_offsets, + int32_t target_segment, + const std::pair<uint32_t, uint32_t>& selection); + + /// Returns the composition text as a UTF-8 string for the given IME event. + /// + /// @return A string var representing the composition text. For non-IME + /// input events the return value will be an undefined var. + Var GetText() const; + + /// Returns the number of segments in the composition text. + /// + /// @return The number of segments. For events other than COMPOSITION_UPDATE, + /// returns 0. + uint32_t GetSegmentNumber() const; + + /// Returns the position of the index-th segmentation point in the composition + /// text. The position is given by a byte-offset (not a character-offset) of + /// the string returned by GetText(). It always satisfies + /// 0=GetSegmentOffset(0) < ... < GetSegmentOffset(i) < GetSegmentOffset(i+1) + /// < ... < GetSegmentOffset(GetSegmentNumber())=(byte-length of GetText()). + /// Note that [GetSegmentOffset(i), GetSegmentOffset(i+1)) represents the + /// range of the i-th segment, and hence GetSegmentNumber() can be a valid + /// argument to this function instead of an off-by-1 error. + /// + /// @param[in] ime_event A <code>PP_Resource</code> corresponding to an IME + /// event. + /// + /// @param[in] index An integer indicating a segment. + /// + /// @return The byte-offset of the segmentation point. If the event is not + /// COMPOSITION_UPDATE or index is out of range, returns 0. + uint32_t GetSegmentOffset(uint32_t index) const; + + /// Returns the index of the current target segment of composition. + /// + /// @return An integer indicating the index of the target segment. When there + /// is no active target segment, or the event is not COMPOSITION_UPDATE, + /// returns -1. + int32_t GetTargetSegment() const; + + /// Obtains the range selected by caret in the composition text. + /// + /// @param[out] start An integer indicating a start offset of selection range. + /// + /// @param[out] end An integer indicating an end offset of selection range. + void GetSelection(uint32_t* start, uint32_t* end) const; +}; +} // namespace pp + +#endif // PPAPI_CPP_INPUT_EVENT_H_ diff --git a/chromium/ppapi/cpp/instance.cc b/chromium/ppapi/cpp/instance.cc new file mode 100644 index 00000000000..d285fd49366 --- /dev/null +++ b/chromium/ppapi/cpp/instance.cc @@ -0,0 +1,198 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/instance.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/ppb_console.h" +#include "ppapi/c/ppb_input_event.h" +#include "ppapi/c/ppb_instance.h" +#include "ppapi/c/ppb_messaging.h" +#include "ppapi/cpp/graphics_2d.h" +#include "ppapi/cpp/graphics_3d.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/view.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Console_1_0>() { + return PPB_CONSOLE_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_InputEvent_1_0>() { + return PPB_INPUT_EVENT_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_Instance_1_0>() { + return PPB_INSTANCE_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_Messaging_1_0>() { + return PPB_MESSAGING_INTERFACE_1_0; +} + +} // namespace + +Instance::Instance(PP_Instance instance) : pp_instance_(instance) { +} + +Instance::~Instance() { +} + +bool Instance::Init(uint32_t /*argc*/, const char* /*argn*/[], + const char* /*argv*/[]) { + return true; +} + +void Instance::DidChangeView(const View& view) { + // Call the deprecated version for source backwards-compat. + DidChangeView(view.GetRect(), view.GetClipRect()); +} + +void Instance::DidChangeView(const pp::Rect& /*position*/, + const pp::Rect& /*clip*/) { +} + +void Instance::DidChangeFocus(bool /*has_focus*/) { +} + + +bool Instance::HandleDocumentLoad(const URLLoader& /*url_loader*/) { + return false; +} + +bool Instance::HandleInputEvent(const InputEvent& /*event*/) { + return false; +} + +void Instance::HandleMessage(const Var& /*message*/) { + return; +} + +bool Instance::BindGraphics(const Graphics2D& graphics) { + if (!has_interface<PPB_Instance_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_Instance_1_0>()->BindGraphics( + pp_instance(), graphics.pp_resource())); +} + +bool Instance::BindGraphics(const Graphics3D& graphics) { + if (!has_interface<PPB_Instance_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_Instance_1_0>()->BindGraphics( + pp_instance(), graphics.pp_resource())); +} + +bool Instance::IsFullFrame() { + if (!has_interface<PPB_Instance_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_Instance_1_0>()->IsFullFrame( + pp_instance())); +} + +int32_t Instance::RequestInputEvents(uint32_t event_classes) { + if (!has_interface<PPB_InputEvent_1_0>()) + return PP_ERROR_NOINTERFACE; + return get_interface<PPB_InputEvent_1_0>()->RequestInputEvents(pp_instance(), + event_classes); +} + +int32_t Instance::RequestFilteringInputEvents(uint32_t event_classes) { + if (!has_interface<PPB_InputEvent_1_0>()) + return PP_ERROR_NOINTERFACE; + return get_interface<PPB_InputEvent_1_0>()->RequestFilteringInputEvents( + pp_instance(), event_classes); +} + +void Instance::ClearInputEventRequest(uint32_t event_classes) { + if (!has_interface<PPB_InputEvent_1_0>()) + return; + get_interface<PPB_InputEvent_1_0>()->ClearInputEventRequest(pp_instance(), + event_classes); +} + +void Instance::PostMessage(const Var& message) { + if (!has_interface<PPB_Messaging_1_0>()) + return; + get_interface<PPB_Messaging_1_0>()->PostMessage(pp_instance(), + message.pp_var()); +} + +void Instance::LogToConsole(PP_LogLevel level, const Var& value) { + if (!has_interface<PPB_Console_1_0>()) + return; + get_interface<PPB_Console_1_0>()->Log( + pp_instance(), level, value.pp_var()); +} + +void Instance::LogToConsoleWithSource(PP_LogLevel level, + const Var& source, + const Var& value) { + if (!has_interface<PPB_Console_1_0>()) + return; + get_interface<PPB_Console_1_0>()->LogWithSource( + pp_instance(), level, source.pp_var(), value.pp_var()); +} + +void Instance::AddPerInstanceObject(const std::string& interface_name, + void* object) { + // Ensure we're not trying to register more than one object per interface + // type. Otherwise, we'll get confused in GetPerInstanceObject. + PP_DCHECK(interface_name_to_objects_.find(interface_name) == + interface_name_to_objects_.end()); + interface_name_to_objects_[interface_name] = object; +} + +void Instance::RemovePerInstanceObject(const std::string& interface_name, + void* object) { + InterfaceNameToObjectMap::iterator found = interface_name_to_objects_.find( + interface_name); + if (found == interface_name_to_objects_.end()) { + // Attempting to unregister an object that doesn't exist or was already + // unregistered. + PP_DCHECK(false); + return; + } + + // Validate that we're removing the object we thing we are. + PP_DCHECK(found->second == object); + (void)object; // Prevent warning in release mode. + + interface_name_to_objects_.erase(found); +} + +// static +void Instance::RemovePerInstanceObject(const InstanceHandle& instance, + const std::string& interface_name, + void* object) { + // TODO(brettw) assert we're on the main thread. + Instance* that = Module::Get()->InstanceForPPInstance(instance.pp_instance()); + if (!that) + return; + that->RemovePerInstanceObject(interface_name, object); +} + +// static +void* Instance::GetPerInstanceObject(PP_Instance instance, + const std::string& interface_name) { + Instance* that = Module::Get()->InstanceForPPInstance(instance); + if (!that) + return NULL; + InterfaceNameToObjectMap::iterator found = + that->interface_name_to_objects_.find(interface_name); + if (found == that->interface_name_to_objects_.end()) + return NULL; + return found->second; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/instance.h b/chromium/ppapi/cpp/instance.h new file mode 100644 index 00000000000..6bf4e839381 --- /dev/null +++ b/chromium/ppapi/cpp/instance.h @@ -0,0 +1,578 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_INSTANCE_H_ +#define PPAPI_CPP_INSTANCE_H_ + +/// @file +/// This file defines the C++ wrapper for an instance. + +#include <map> +#include <string> + +#include "ppapi/c/pp_instance.h" +#include "ppapi/c/pp_resource.h" +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/ppb_console.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/view.h" + +// Windows defines 'PostMessage', so we have to undef it. +#ifdef PostMessage +#undef PostMessage +#endif + +struct PP_InputEvent; + +/// The C++ interface to the Pepper API. +namespace pp { + +class Graphics2D; +class Graphics3D; +class InputEvent; +class InstanceHandle; +class Rect; +class URLLoader; +class Var; + +class Instance { + public: + /// Default constructor. Construction of an instance should only be done in + /// response to a browser request in <code>Module::CreateInstance</code>. + /// Otherwise, the instance will lack the proper bookkeeping in the browser + /// and in the C++ wrapper. + /// + /// Init() will be called immediately after the constructor. This allows you + /// to perform initialization tasks that can fail and to report that failure + /// to the browser. + explicit Instance(PP_Instance instance); + + /// Destructor. When the instance is removed from the web page, + /// the <code>pp::Instance</code> object will be deleted. You should never + /// delete the <code>Instance</code> object yourself since the lifetime is + /// handled by the C++ wrapper and is controlled by the browser's calls to + /// the <code>PPP_Instance</code> interface. + /// + /// The <code>PP_Instance</code> identifier will still be valid during this + /// call so the instance can perform cleanup-related tasks. Once this function + /// returns, the <code>PP_Instance</code> handle will be invalid. This means + /// that you can't do any asynchronous operations such as network requests or + /// file writes from this destructor since they will be immediately canceled. + /// + /// <strong>Note:</strong> This function may be skipped in certain + /// call so the instance can perform cleanup-related tasks. Once this function + /// returns, the <code>PP_Instance</code> handle will be invalid. This means + /// that you can't do any asynchronous operations such as network requests or + /// file writes from this destructor since they will be immediately canceled. + virtual ~Instance(); + + /// This function returns the <code>PP_Instance</code> identifying this + /// object. + /// + /// @return A <code>PP_Instance</code> identifying this object. + PP_Instance pp_instance() const { return pp_instance_; } + + /// Init() initializes this instance with the provided arguments. This + /// function will be called immediately after the instance object is + /// constructed. + /// + /// @param[in] argc The number of arguments contained in <code>argn</code> + /// and <code>argv</code>. + /// + /// @param[in] argn An array of argument names. These argument names are + /// supplied in the \<embed\> tag, for example: + /// <code>\<embed id="nacl_module" dimensions="2"\></code> will produce two + /// argument names: "id" and "dimensions". + /// + /// @param[in] argv An array of argument values. These are the values of the + /// arguments listed in the \<embed\> tag, for example + /// <code>\<embed id="nacl_module" dimensions="2"\></code> will produce two + /// argument values: "nacl_module" and "2". The indices of these values + /// match the indices of the corresponding names in <code>argn</code>. + /// + /// @return true on success. Returning false causes the instance to be + /// deleted and no other functions to be called. + virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]); + + /// @{ + /// @name PPP_Instance methods for the module to override: + + /// DidChangeView() is called when the view information for the Instance + /// has changed. See the <code>View</code> object for information. + /// + /// Most implementations will want to check if the size and user visibility + /// changed, and either resize themselves or start/stop generating updates. + /// + /// You should not call the default implementation. For + /// backwards-compatibility, it will call the deprecated version of + /// DidChangeView below. + virtual void DidChangeView(const View& view); + + /// Deprecated backwards-compatible version of <code>DidChangeView()</code>. + /// New code should derive from the version that takes a + /// <code>ViewChanged</code> object rather than this version. This function + /// is called by the default implementation of the newer + /// <code>DidChangeView</code> function for source compatibility with older + /// code. + /// + /// A typical implementation will check the size of the <code>position</code> + /// argument and reallocate the graphics context when a different size is + /// received. Note that this function will be called for scroll events where + /// the size doesn't change, so you should always check that the size is + /// actually different before doing any reallocations. + /// + /// @param[in] position The location on the page of the instance. The + /// position is relative to the top left corner of the viewport, which changes + /// as the page is scrolled. Generally the size of this value will be used to + /// create a graphics device, and the position is ignored (most things are + /// relative to the instance so the absolute position isn't useful in most + /// cases). + /// + /// @param[in] clip The visible region of the instance. This is relative to + /// the top left of the instance's coordinate system (not the page). If the + /// instance is invisible, <code>clip</code> will be (0, 0, 0, 0). + /// + /// It's recommended to check for invisible instances and to stop + /// generating graphics updates in this case to save system resources. It's + /// not usually worthwhile, however, to generate partial updates according to + /// the clip when the instance is partially visible. Instead, update the + /// entire region. The time saved doing partial paints is usually not + /// significant and it can create artifacts when scrolling (this notification + /// is sent asynchronously from scrolling so there can be flashes of old + /// content in the exposed regions). + virtual void DidChangeView(const Rect& position, const Rect& clip); + + /// DidChangeFocus() is called when an instance has gained or lost focus. + /// Having focus means that keyboard events will be sent to the instance. + /// An instance's default condition is that it will not have focus. + /// + /// The focus flag takes into account both browser tab and window focus as + /// well as focus of the plugin element on the page. In order to be deemed + /// to have focus, the browser window must be topmost, the tab must be + /// selected in the window, and the instance must be the focused element on + /// the page. + /// + /// <strong>Note:</strong>Clicks on instances will give focus only if you + /// handle the click event. Return <code>true</code> from + /// <code>HandleInputEvent</code> in <code>PPP_InputEvent</code> (or use + /// unfiltered events) to signal that the click event was handled. Otherwise, + /// the browser will bubble the event and give focus to the element on the + /// page that actually did end up consuming it. If you're not getting focus, + /// check to make sure you're either requesting them via + /// <code>RequestInputEvents()<code> (which implicitly marks all input events + /// as consumed) or via <code>RequestFilteringInputEvents()</code> and + /// returning true from your event handler. + /// + /// @param[in] has_focus Indicates the new focused state of the instance. + virtual void DidChangeFocus(bool has_focus); + + /// HandleInputEvent() handles input events from the browser. The default + /// implementation does nothing and returns false. + /// + /// In order to receive input events, you must register for them by calling + /// RequestInputEvents() or RequestFilteringInputEvents(). By + /// default, no events are delivered. + /// + /// If the event was handled, it will not be forwarded to the web page or + /// browser. If it was not handled, it will bubble according to the normal + /// rules. So it is important that an instance respond accurately with whether + /// event propagation should continue. + /// + /// Event propagation also controls focus. If you handle an event like a mouse + /// event, typically the instance will be given focus. Returning false from + /// a filtered event handler or not registering for an event type means that + /// the click will be given to a lower part of the page and your instance will + /// not receive focus. This allows an instance to be partially transparent, + /// where clicks on the transparent areas will behave like clicks to the + /// underlying page. + /// + /// In general, you should try to keep input event handling short. Especially + /// for filtered input events, the browser or page may be blocked waiting for + /// you to respond. + /// + /// The caller of this function will maintain a reference to the input event + /// resource during this call. Unless you take a reference to the resource + /// to hold it for later, you don't need to release it. + /// + /// <strong>Note: </strong>If you're not receiving input events, make sure + /// you register for the event classes you want by calling + /// <code>RequestInputEvents</code> or + /// <code>RequestFilteringInputEvents</code>. If you're still not receiving + /// keyboard input events, make sure you're returning true (or using a + /// non-filtered event handler) for mouse events. Otherwise, the instance will + /// not receive focus and keyboard events will not be sent. + /// + /// Refer to <code>RequestInputEvents</code> and + /// <code>RequestFilteringInputEvents</code> for further information. + /// + /// @param[in] event The event to handle. + /// + /// @return true if the event was handled, false if not. If you have + /// registered to filter this class of events by calling + /// <code>RequestFilteringInputEvents</code>, and you return false, + /// the event will be forwarded to the page (and eventually the browser) + /// for the default handling. For non-filtered events, the return value + /// will be ignored. + virtual bool HandleInputEvent(const pp::InputEvent& event); + + /// HandleDocumentLoad() is called after Init() for a full-frame + /// instance that was instantiated based on the MIME type of a DOMWindow + /// navigation. This situation only applies to modules that are + /// pre-registered to handle certain MIME types. If you haven't specifically + /// registered to handle a MIME type or aren't positive this applies to you, + /// your implementation of this function can just return false. + /// + /// The given url_loader corresponds to a <code>URLLoader</code> object that + /// is already opened. Its response headers may be queried using + /// GetResponseInfo(). If you want to use the <code>URLLoader</code> to read + /// data, you will need to save a copy of it or the underlying resource will + /// be freed when this function returns and the load will be canceled. + /// + /// This method returns false if the module cannot handle the data. In + /// response to this method, the module should call ReadResponseBody() to read + /// the incoming data. + /// + /// @param[in] url_loader An open <code>URLLoader</code> instance. + /// + /// @return true if the data was handled, false otherwise. + virtual bool HandleDocumentLoad(const URLLoader& url_loader); + + /// HandleMessage() is a function that the browser calls when PostMessage() + /// is invoked on the DOM element for the instance in JavaScript. Note + /// that PostMessage() in the JavaScript interface is asynchronous, meaning + /// JavaScript execution will not be blocked while HandleMessage() is + /// processing the message. + /// + /// When converting JavaScript arrays, any object properties whose name + /// is not an array index are ignored. When passing arrays and objects, the + /// entire reference graph will be converted and transferred. If the reference + /// graph has cycles, the message will not be sent and an error will be logged + /// to the console. + /// + /// <strong>Example:</strong> + /// + /// The following JavaScript code invokes <code>HandleMessage</code>, passing + /// the instance on which it was invoked, with <code>message</code> being a + /// string <code>Var</code> containing "Hello world!" + /// + /// @code{.html} + /// + /// <body> + /// <object id="plugin" + /// type="application/x-ppapi-postMessage-example"/> + /// <script type="text/javascript"> + /// document.getElementById('plugin').postMessage("Hello world!"); + /// </script> + /// </body> + /// + /// @endcode + /// + /// Refer to PostMessage() for sending messages to JavaScript. + /// + /// @param[in] message A <code>Var</code> which has been converted from a + /// JavaScript value. JavaScript array/object types are supported from Chrome + /// M29 onward. All JavaScript values are copied when passing them to the + /// plugin. + virtual void HandleMessage(const Var& message); + + /// @} + + /// @{ + /// @name PPB_Instance methods for querying the browser: + + /// BindGraphics() binds the given graphics as the current display surface. + /// The contents of this device is what will be displayed in the instance's + /// area on the web page. The device must be a 2D or a 3D device. + /// + /// You can pass an <code>is_null()</code> (default constructed) Graphics2D + /// as the device parameter to unbind all devices from the given instance. + /// The instance will then appear transparent. Re-binding the same device + /// will return <code>true</code> and will do nothing. + /// + /// Any previously-bound device will be released. It is an error to bind + /// a device when it is already bound to another instance. If you want + /// to move a device between instances, first unbind it from the old one, and + /// then rebind it to the new one. + /// + /// Binding a device will invalidate that portion of the web page to flush the + /// contents of the new device to the screen. + /// + /// @param[in] graphics A <code>Graphics2D</code> to bind. + /// + /// @return true if bind was successful or false if the device was not the + /// correct type. On success, a reference to the device will be held by the + /// instance, so the caller can release its reference if it chooses. + bool BindGraphics(const Graphics2D& graphics); + + /// Binds the given Graphics3D as the current display surface. + /// Refer to <code>BindGraphics(const Graphics2D& graphics)</code> for + /// further information. + /// + /// @param[in] graphics A <code>Graphics3D</code> to bind. + /// + /// @return true if bind was successful or false if the device was not the + /// correct type. On success, a reference to the device will be held by the + /// instance, so the caller can release its reference if it chooses. + bool BindGraphics(const Graphics3D& graphics); + + /// IsFullFrame() determines if the instance is full-frame (repr). + /// Such an instance represents the entire document in a frame rather than an + /// embedded resource. This can happen if the user does a top-level + /// navigation or the page specifies an iframe to a resource with a MIME + /// type registered by the module. + /// + /// @return true if the instance is full-frame, false if not. + bool IsFullFrame(); + + /// RequestInputEvents() requests that input events corresponding to the + /// given input events are delivered to the instance. + /// + /// By default, no input events are delivered. Call this function with the + /// classes of events you are interested in to have them be delivered to + /// the instance. Calling this function will override any previous setting for + /// each specified class of input events (for example, if you previously + /// called RequestFilteringInputEvents(), this function will set those events + /// to non-filtering mode). + /// + /// Input events may have high overhead, so you should only request input + /// events that your plugin will actually handle. For example, the browser may + /// do optimizations for scroll or touch events that can be processed + /// substantially faster if it knows there are no non-default receivers for + /// that message. Requesting that such messages be delivered, even if they are + /// processed very quickly, may have a noticeable effect on the performance of + /// the page. + /// + /// When requesting input events through this function, the events will be + /// delivered and <em>not</em> bubbled to the page. This means that even if + /// you aren't interested in the message, no other parts of the page will get + /// the message. + /// + /// <strong>Example:</strong> + /// + /// @code + /// RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE); + /// RequestFilteringInputEvents( + /// PP_INPUTEVENT_CLASS_WHEEL | PP_INPUTEVENT_CLASS_KEYBOARD); + /// + /// @endcode + /// + /// @param event_classes A combination of flags from + /// <code>PP_InputEvent_Class</code> that identifies the classes of events + /// the instance is requesting. The flags are combined by logically ORing + /// their values. + /// + /// @return <code>PP_OK</code> if the operation succeeded, + /// <code>PP_ERROR_BADARGUMENT</code> if instance is invalid, or + /// <code>PP_ERROR_NOTSUPPORTED</code> if one of the event class bits were + /// illegal. In the case of an invalid bit, all valid bits will be applied + /// and only the illegal bits will be ignored. + int32_t RequestInputEvents(uint32_t event_classes); + + /// RequestFilteringInputEvents() requests that input events corresponding + /// to the given input events are delivered to the instance for filtering. + /// + /// By default, no input events are delivered. In most cases you would + /// register to receive events by calling RequestInputEvents(). In some cases, + /// however, you may wish to filter events such that they can be bubbled up + /// to the DOM. In this case, register for those classes of events using + /// this function instead of RequestInputEvents(). Keyboard events must always + /// be registered in filtering mode. + /// + /// Filtering input events requires significantly more overhead than just + /// delivering them to the instance. As such, you should only request + /// filtering in those cases where it's absolutely necessary. The reason is + /// that it requires the browser to stop and block for the instance to handle + /// the input event, rather than sending the input event asynchronously. This + /// can have significant overhead. + /// + /// <strong>Example:</strong> + /// + /// @code + /// + /// RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE); + /// RequestFilteringInputEvents( + /// PP_INPUTEVENT_CLASS_WHEEL | PP_INPUTEVENT_CLASS_KEYBOARD); + /// + /// @endcode + /// + /// @param event_classes A combination of flags from + /// <code>PP_InputEvent_Class</code> that identifies the classes of events + /// the instance is requesting. The flags are combined by logically ORing + /// their values. + /// + /// @return <code>PP_OK</code> if the operation succeeded, + /// <code>PP_ERROR_BADARGUMENT</code> if instance is invalid, or + /// <code>PP_ERROR_NOTSUPPORTED</code> if one of the event class bits were + /// illegal. In the case of an invalid bit, all valid bits will be applied + /// and only the illegal bits will be ignored. + int32_t RequestFilteringInputEvents(uint32_t event_classes); + + /// ClearInputEventRequest() requests that input events corresponding to the + /// given input classes no longer be delivered to the instance. + /// + /// By default, no input events are delivered. If you have previously + /// requested input events using RequestInputEvents() or + /// RequestFilteringInputEvents(), this function will unregister handling + /// for the given instance. This will allow greater browser performance for + /// those events. + /// + /// <strong>Note: </strong> You may still get some input events after + /// clearing the flag if they were dispatched before the request was cleared. + /// For example, if there are 3 mouse move events waiting to be delivered, + /// and you clear the mouse event class during the processing of the first + /// one, you'll still receive the next two. You just won't get more events + /// generated. + /// + /// @param[in] event_classes A combination of flags from + /// <code>PP_InputEvent_Class</code> that identifies the classes of events the + /// instance is no longer interested in. + void ClearInputEventRequest(uint32_t event_classes); + + /// PostMessage() asynchronously invokes any listeners for message events on + /// the DOM element for the given instance. A call to PostMessage() will + /// not block while the message is processed. + /// + /// <strong>Example:</strong> + /// + /// @code{.html} + /// + /// <body> + /// <object id="plugin" + /// type="application/x-ppapi-postMessage-example"/> + /// <script type="text/javascript"> + /// var plugin = document.getElementById('plugin'); + /// plugin.addEventListener("message", + /// function(message) { alert(message.data); }, + /// false); + /// </script> + /// </body> + /// + /// @endcode + /// + /// The instance then invokes PostMessage() as follows: + /// + /// @code + /// + /// PostMessage(pp::Var("Hello world!")); + /// + /// @endcode + /// + /// The browser will pop-up an alert saying "Hello world!" + /// + /// When passing array or dictionary <code>PP_Var</code>s, the entire + /// reference graph will be converted and transferred. If the reference graph + /// has cycles, the message will not be sent and an error will be logged to + /// the console. + /// + /// Listeners for message events in JavaScript code will receive an object + /// conforming to the HTML 5 <code>MessageEvent</code> interface. + /// Specifically, the value of message will be contained as a property called + /// data in the received <code>MessageEvent</code>. + /// + /// This messaging system is similar to the system used for listening for + /// messages from Web Workers. Refer to + /// <code>http://www.whatwg.org/specs/web-workers/current-work/</code> for + /// further information. + /// + /// Refer to HandleMessage() for receiving events from JavaScript. + /// + /// @param[in] message A <code>Var</code> containing the data to be sent to + /// JavaScript. Message can have a numeric, boolean, or string value. + /// Array/Dictionary types are supported from Chrome M29 onward. + /// All var types are copied when passing them to JavaScript. + void PostMessage(const Var& message); + + /// @} + + /// @{ + /// @name PPB_Console methods for logging to the console: + + /// Logs the given message to the JavaScript console associated with the + /// given plugin instance with the given logging level. The name of the plugin + /// issuing the log message will be automatically prepended to the message. + /// The value may be any type of Var. + void LogToConsole(PP_LogLevel level, const Var& value); + + /// Logs a message to the console with the given source information rather + /// than using the internal PPAPI plugin name. The name must be a string var. + /// + /// The regular log function will automatically prepend the name of your + /// plugin to the message as the "source" of the message. Some plugins may + /// wish to override this. For example, if your plugin is a Python + /// interpreter, you would want log messages to contain the source .py file + /// doing the log statement rather than have "python" show up in the console. + void LogToConsoleWithSource(PP_LogLevel level, + const Var& source, + const Var& value); + + /// @} + + /// AddPerInstanceObject() associates an instance with an interface, + /// creating an object. + /// + /// Many optional interfaces are associated with a plugin instance. For + /// example, the find in PPP_Find interface receives updates on a per-instance + /// basis. This "per-instance" tracking allows such objects to associate + /// themselves with an instance as "the" handler for that interface name. + /// + /// In the case of the find example, the find object registers with its + /// associated instance in its constructor and unregisters in its destructor. + /// Then whenever it gets updates with a PP_Instance parameter, it can + /// map back to the find object corresponding to that given PP_Instance by + /// calling GetPerInstanceObject. + /// + /// This lookup is done on a per-interface-name basis. This means you can + /// only have one object of a given interface name associated with an + /// instance. + /// + /// If you are adding a handler for an additional interface, be sure to + /// register with the module (AddPluginInterface) for your interface name to + /// get the C calls in the first place. + /// + /// Refer to RemovePerInstanceObject() and GetPerInstanceObject() for further + /// information. + /// + /// @param[in] interface_name The name of the interface to associate with the + /// instance + /// @param[in] object + void AddPerInstanceObject(const std::string& interface_name, void* object); + + // {PENDING: summarize Remove method here} + /// + /// Refer to AddPerInstanceObject() for further information. + /// + /// @param[in] interface_name The name of the interface to associate with the + /// instance + /// @param[in] object + void RemovePerInstanceObject(const std::string& interface_name, void* object); + + /// Static version of AddPerInstanceObject that takes an InstanceHandle. As + /// with all other instance functions, this must only be called on the main + /// thread. + static void RemovePerInstanceObject(const InstanceHandle& instance, + const std::string& interface_name, + void* object); + + /// Look up an object previously associated with an instance. Returns NULL + /// if the instance is invalid or there is no object for the given interface + /// name on the instance. + /// + /// Refer to AddPerInstanceObject() for further information. + /// + /// @param[in] instance + /// @param[in] interface_name The name of the interface to associate with the + /// instance. + static void* GetPerInstanceObject(PP_Instance instance, + const std::string& interface_name); + + private: + PP_Instance pp_instance_; + + typedef std::map<std::string, void*> InterfaceNameToObjectMap; + InterfaceNameToObjectMap interface_name_to_objects_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_INSTANCE_H_ diff --git a/chromium/ppapi/cpp/instance_handle.cc b/chromium/ppapi/cpp/instance_handle.cc new file mode 100644 index 00000000000..8c3195a3b8c --- /dev/null +++ b/chromium/ppapi/cpp/instance_handle.cc @@ -0,0 +1,15 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/instance_handle.h" + +#include "ppapi/cpp/instance.h" + +namespace pp { + +InstanceHandle::InstanceHandle(Instance* instance) + : pp_instance_(instance->pp_instance()) { +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/instance_handle.h b/chromium/ppapi/cpp/instance_handle.h new file mode 100644 index 00000000000..fd118fdd35e --- /dev/null +++ b/chromium/ppapi/cpp/instance_handle.h @@ -0,0 +1,75 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_INSTANCE_HANDLE_H_ +#define PPAPI_CPP_INSTANCE_HANDLE_H_ + +#include "ppapi/c/pp_instance.h" + + +/// @file +/// This file defines an instance handle used to identify an instance in a +/// constructor for a resource. +namespace pp { + +class Instance; + +/// An instance handle identifies an instance in a constructor for a resource. +/// This class solves two different problems: +/// +/// 1. A pp::Instance object's lifetime is managed by the system on the main +/// pepper thread of the module. This means that it may get destroyed at any +/// time based on something that happens on the web page. Therefore, it's not +/// safe to refer to a <code>pp::Instance</code> object on a background thread. +/// Instead, we need to pass some kind of identifier to resource constructors +/// so that they may safely be used on background threads. If the instance +/// becomes invalid, the resource creation will fail on the background thread, +/// but it won't crash. +/// +/// 2. <code>PP_Instance</code> would be a good identifier to use for this case. +/// However, using <code>PP_Instance</code> in the constructor to resources is +/// problematic because it is just a typedef for an integer, as is a +/// <code>PP_Resource</code>. Many resources have alternate constructors that +/// just take an existing <code>PP_Resource</code>, so the constructors would +/// be ambiguous. Having this wrapper around a <code>PP_Instance</code> +/// prevents this ambiguity, and also provides a nice place to consolidate an +/// implicit conversion from <code>pp::Instance*</code> for prettier code on +/// the main thread (you can just pass "this" to resource constructors in your +/// instance objects). +/// +/// You should always pass an <code>InstanceHandle</code> to background threads +/// instead of a <code>pp::Instance</code>, and use them in resource +/// constructors and code that may be used from background threads. +class InstanceHandle { + public: + /// Implicit constructor for converting a <code>pp::Instance</code> to an + /// instance handle. + /// + /// @param[in] instance The instance with which this + /// <code>InstanceHandle</code> will be associated. + InstanceHandle(Instance* instance); + + /// This constructor explicitly converts a <code>PP_Instance</code> to an + /// instance handle. This should not be implicit because it can make some + /// resource constructors ambiguous. <code>PP_Instance</code> is just a + /// typedef for an integer, as is <code>PP_Resource</code>, so the compiler + /// can get confused between the two. + /// + /// @param[in] pp_instance The instance with which this + /// <code>InstanceHandle</code> will be associated. + explicit InstanceHandle(PP_Instance pp_instance) + : pp_instance_(pp_instance) {} + + /// The pp_instance() function returns the <code>PP_Instance</code>. + /// + /// @return A <code>PP_Instance</code> internal instance handle. + PP_Instance pp_instance() const { return pp_instance_; } + + private: + PP_Instance pp_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_INSTANCE_HANDLE_H_ diff --git a/chromium/ppapi/cpp/logging.h b/chromium/ppapi/cpp/logging.h new file mode 100644 index 00000000000..d0a4f5b29a5 --- /dev/null +++ b/chromium/ppapi/cpp/logging.h @@ -0,0 +1,34 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_LOGGING_H_ +#define PPAPI_CPP_LOGGING_H_ + +/// @file +/// This file defines two macro asserts. + +#include <cassert> + +/// This macro asserts that 'a' evaluates to true. In debug mode, this macro +/// will crash the program if the assertion evaluates to false. It (typically) +/// has no effect in release mode. +#define PP_DCHECK(a) assert(a) + +/// This macro asserts false in debug builds. It's used in code paths that you +/// don't expect to execute. +/// +/// <strong>Example:</strong> +/// +/// @code +/// if (!pointer) { +/// // Pointer wasn't valid! This shouldn't happen. +/// PP_NOTREACHED(); +/// return; +/// } +/// // Do stuff to the pointer, since you know it's valid. +/// pointer->DoSomething(); +/// @endcode +#define PP_NOTREACHED() assert(false) + +#endif // PPAPI_CPP_LOGGING_H_ diff --git a/chromium/ppapi/cpp/message_loop.cc b/chromium/ppapi/cpp/message_loop.cc new file mode 100644 index 00000000000..df3800737dd --- /dev/null +++ b/chromium/ppapi/cpp/message_loop.cc @@ -0,0 +1,87 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/message_loop.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/ppb_message_loop.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_MessageLoop>() { + return PPB_MESSAGELOOP_INTERFACE_1_0; +} + +} // namespace + +MessageLoop::MessageLoop() : Resource() { +} + +MessageLoop::MessageLoop(const InstanceHandle& instance) : Resource() { + if (has_interface<PPB_MessageLoop>()) { + PassRefFromConstructor(get_interface<PPB_MessageLoop>()->Create( + instance.pp_instance())); + } +} + +MessageLoop::MessageLoop(const MessageLoop& other) + : Resource(other) { +} + +MessageLoop::MessageLoop(PP_Resource pp_message_loop) + : Resource(pp_message_loop) { +} + +// static +MessageLoop MessageLoop::GetForMainThread() { + if (!has_interface<PPB_MessageLoop>()) + return MessageLoop(); + return MessageLoop( + get_interface<PPB_MessageLoop>()->GetForMainThread()); +} + +// static +MessageLoop MessageLoop::GetCurrent() { + if (!has_interface<PPB_MessageLoop>()) + return MessageLoop(); + return MessageLoop( + get_interface<PPB_MessageLoop>()->GetCurrent()); +} + +int32_t MessageLoop::AttachToCurrentThread() { + if (!has_interface<PPB_MessageLoop>()) + return PP_ERROR_NOINTERFACE; + return get_interface<PPB_MessageLoop>()->AttachToCurrentThread( + pp_resource()); +} + +int32_t MessageLoop::Run() { + if (!has_interface<PPB_MessageLoop>()) + return PP_ERROR_NOINTERFACE; + return get_interface<PPB_MessageLoop>()->Run(pp_resource()); +} + +int32_t MessageLoop::PostWork(const CompletionCallback& callback, + int64_t delay_ms) { + if (!has_interface<PPB_MessageLoop>()) + return PP_ERROR_NOINTERFACE; + return get_interface<PPB_MessageLoop>()->PostWork( + pp_resource(), + callback.pp_completion_callback(), + delay_ms); +} + +int32_t MessageLoop::PostQuit(bool should_destroy) { + if (!has_interface<PPB_MessageLoop>()) + return PP_ERROR_NOINTERFACE; + return get_interface<PPB_MessageLoop>()->PostQuit( + pp_resource(), PP_FromBool(should_destroy)); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/message_loop.h b/chromium/ppapi/cpp/message_loop.h new file mode 100644 index 00000000000..c1e217bbe36 --- /dev/null +++ b/chromium/ppapi/cpp/message_loop.h @@ -0,0 +1,268 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_MESSAGE_LOOP_H_ +#define PPAPI_CPP_MESSAGE_LOOP_H_ + +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the PPB_MessageLoop API. + +namespace pp { + +class CompletionCallback; +class InstanceHandle; + +/// A message loop allows PPAPI calls to be issued on a thread. You may not +/// issue any API calls on a thread without creating a message loop. It also +/// allows you to post work to the message loop for a thread. +/// +/// To process work posted to the message loop, as well as completion callbacks +/// for asynchronous operations, you must run the message loop via Run(). +/// +/// Note the system manages the lifetime of the instance (and all associated +/// resources). If the instance is deleted from the page, background threads may +/// suddenly see their PP_Resource handles become invalid. In this case, calls +/// will fail with PP_ERROR_BADRESOURCE. If you need to access data associated +/// with your instance, you will probably want to create some kind of threadsafe +/// proxy object that can handle asynchronous destruction of the instance +/// object. +/// +/// Typical usage: +/// On the main thread: +/// - Create the thread yourself (using pthreads). +/// - Create the message loop resource. +/// - Pass the message loop resource to your thread's main function. +/// - Call PostWork() on the message loop to run functions on the thread. +/// +/// From the background thread's main function: +/// - Call AttachToCurrentThread() with the message loop resource. +/// - Call Run() with the message loop resource. +/// +/// Your callbacks should look like this: +/// @code +/// void DoMyWork(void* user_data, int32_t status) { +/// if (status != PP_OK) { +/// Cleanup(); // e.g. free user_data. +/// return; +/// } +/// ... do your work... +/// } +/// @endcode +/// For a C++ example, see ppapi/utility/threading/simple_thread.h +/// +/// (You can also create the message loop resource on the background thread, +/// but then the main thread will have no reference to it should you want to +/// call PostWork()). +/// +/// +/// THREAD HANDLING +/// +/// The main thread has an implicitly created message loop. The main thread is +/// the thread where PPP_InitializeModule and PPP_Instance functions are called. +/// You can retrieve a reference to this message loop by calling +/// GetForMainThread() or, if your code is on the main thread, +/// GetForCurrentThread() will also work. +/// +/// Some special threads created by the system can not have message loops. In +/// particular, the background thread created for audio processing has this +/// requirement because it's intended to be highly responsive to keep up with +/// the realtime requirements of audio processing. You can not make PPAPI calls +/// from these threads. +/// +/// Once you associate a message loop with a thread, you don't have to keep a +/// reference to it. The system will hold a reference to the message loop for as +/// long as the thread is running. The current message loop can be retrieved +/// using the GetCurrent() function. +/// +/// It is legal to create threads in your plugin without message loops, but +/// PPAPI calls will fail unless explicitly noted in the documentation. +/// +/// You can create a message loop object on a thread and never actually run the +/// message loop. This will allow you to call blocking PPAPI calls (via +/// PP_BlockUntilComplete()). If you make any asynchronous calls, the callbacks +/// from those calls will be queued in the message loop and never run. The same +/// thing will happen if work is scheduled after the message loop exits and +/// the message loop is not run again. +/// +/// +/// DESTRUCTION AND ERROR HANDLING +/// +/// Often, your application will associate memory with completion callbacks. For +/// example, the C++ CompletionCallbackFactory has a small amount of +/// heap-allocated memory for each callback. This memory will be leaked if the +/// callback is never run. To avoid this memory leak, you need to be careful +/// about error handling and shutdown. +/// +/// There are a number of cases where posted callbacks will never be run: +/// +/// - You tear down the thread (via pthreads) without "destroying" the message +/// loop (via PostQuit with should_destroy = PP_TRUE). In this case, any +/// tasks in the message queue will be lost. +/// +/// - You create a message loop, post callbacks to it, and never run it. +/// +/// - You quit the message loop via PostQuit with should_destroy set to +/// PP_FALSE. In this case, the system will assume the message loop will be +/// run again later and keep your tasks. +/// +/// To do proper shutdown, call PostQuit with should_destroy = PP_TRUE. This +/// will prohibit future work from being posted, and will allow the message loop +/// to run until all pending tasks are run. +/// +/// If you post a callback to a message loop that's been destroyed, or to an +/// invalid message loop, PostWork will return an error and will not run the +/// callback. This is true even for callbacks with the "required" flag set, +/// since the system may not even know what thread to issue the error callback +/// on. +/// +/// Therefore, you should check for errors from PostWork and destroy any +/// associated memory to avoid leaks. If you're using the C++ +/// CompletionCallbackFactory, use the following pattern: +/// @code +/// pp::CompletionCallback callback = factory_.NewOptionalCallback(...); +/// int32_t result = message_loop.PostWork(callback); +/// if (result != PP_OK) +/// callback.Run(result); +/// @endcode +/// This will run the callback with an error value, and assumes that the +/// implementation of your callback checks the "result" argument and returns +/// immediately on error. +class MessageLoop : public Resource { + public: + /// Creates an is_null() MessageLoop resource. + MessageLoop(); + + /// Creates a message loop associated with the given instance. The resource + /// will be is_null() on failure. + /// + /// This may be called from any thread. After your thread starts but before + /// issuing any other PPAPI calls on it, you must associate it with a message + /// loop by calling AttachToCurrentThread. + explicit MessageLoop(const InstanceHandle& instance); + + MessageLoop(const MessageLoop& other); + + /// Takes an additional ref to the resource. + explicit MessageLoop(PP_Resource pp_message_loop); + + static MessageLoop GetForMainThread(); + static MessageLoop GetCurrent(); + + /// Sets the given message loop resource as being the associated message loop + /// for the currently running thread. + /// + /// You must call this function exactly once on a thread before making any + /// PPAPI calls. A message loop can only be attached to one thread, and the + /// message loop can not be changed later. The message loop will be attached + /// as long as the thread is running or until you quit with should_destroy + /// set to PP_TRUE. + /// + /// If this function fails, attempting to run the message loop will fail. + /// Note that you can still post work to the message loop: it will get queued + /// up should the message loop eventually be successfully attached and run. + /// + /// @return + /// - PP_OK: The message loop was successfully attached to the thread and is + /// ready to use. + /// - PP_ERROR_BADRESOURCE: The given message loop resource is invalid. + /// - PP_ERROR_INPROGRESS: The current thread already has a message loop + /// attached. This will always be the case for the main thread, which has + /// an implicit system-created message loop attached. + /// - PP_ERROR_WRONG_THREAD: The current thread type can not have a message + /// loop attached to it. See the interface level discussion about these + /// special threads, which include realtime audio threads. + int32_t AttachToCurrentThread(); + + /// Runs the thread message loop. Running the message loop is required for + /// you to get issued completion callbacks on the thread. + /// + /// The message loop identified by the argument must have been previously + /// successfully attached to the current thread. + /// + /// You may not run nested message loops. Since the main thread has an + /// implicit message loop that the system runs, you may not call Run on the + /// main thread. + /// + /// @return + /// - PP_OK: The message loop was successfully run. Note that on + /// success, the message loop will only exit when you call PostQuit(). + /// - PP_ERROR_BADRESOURCE: The given message loop resource is invalid. + /// - PP_ERROR_WRONG_THREAD: You are attempting to run a message loop that + /// has not been successfully attached to the current thread. Call + /// AttachToCurrentThread(). + /// - PP_ERROR_INPROGRESS: You are attempting to call Run in a nested + /// fashion (Run is already on the stack). This will occur if you attempt + /// to call run on the main thread's message loop (see above). + int32_t Run(); + + /// Schedules work to run on the given message loop. This may be called from + /// any thread. Posted work will be executed in the order it was posted when + /// the message loop is Run(). + /// + /// @param callback A pointer to the completion callback to execute from the + /// message loop. + /// + /// @param delay_ms The number of milliseconds to delay execution of the given + /// completion callback. Passing 0 means it will get queued normally and + /// executed in order. + /// + /// + /// The completion callback will be called with PP_OK as the "result" + /// parameter if it is run normally. It is good practice to check for PP_OK + /// and return early otherwise. + /// + /// The "required" flag on the completion callback is ignored. If there is an + /// error posting your callback, the error will be returned from PostWork and + /// the callback will never be run (because there is no appropriate place to + /// run your callback with an error without causing unexpected threading + /// problems). If you associate memory with the completion callback (for + /// example, you're using the C++ CompletionCallbackFactory), you will need to + /// free this or manually run the callback. See "Desctruction and error + /// handling" above. + /// + /// + /// You can call this function before the message loop has started and the + /// work will get queued until the message loop is run. You can also post + /// work after the message loop has exited as long as should_destroy was + /// PP_FALSE. It will be queued until the next invocation of Run(). + /// + /// @return + /// - PP_OK: The work was posted to the message loop's queue. As described + /// above, this does not mean that the work has been or will be executed + /// (if you never run the message loop after posting). + /// - PP_ERROR_BADRESOURCE: The given message loop resource is invalid. + /// - PP_ERROR_BADARGUMENT: The function pointer for the completion callback + /// is null (this will be the case if you pass PP_BlockUntilComplete()). + /// - PP_ERROR_FAILED: The message loop has been destroyed. + int32_t PostWork(const CompletionCallback& callback, + int64_t delay_ms = 0); + + /// Posts a quit message to the given message loop's work queue. Work posted + /// before that point will be processed before quitting. + /// + /// This may be called on the message loop registered for the current thread, + /// or it may be called on the message loop registered for another thread. It + /// is an error to attempt to quit the main thread loop. + /// + /// @param should_destroy Marks the message loop as being in a destroyed + /// state and prevents further posting of messages. + /// + /// If you quit a message loop without setting should_destroy, it will still + /// be attached to the thread and you can still run it again by calling Run() + /// again. If you destroy it, it will be detached from the current thread. + /// + /// @return + /// - PP_OK: The request to quit was successfully posted. + /// - PP_ERROR_BADRESOURCE: The message loop was invalid. + /// - PP_ERROR_WRONG_THREAD: You are attempting to quit the main thread. + /// The main thread's message loop is managed by the system and can't be + /// quit. + int32_t PostQuit(bool should_destroy); +}; + +} // namespace pp + +#endif // PPAPI_CPP_MESSAGE_LOOP_H_ diff --git a/chromium/ppapi/cpp/module.cc b/chromium/ppapi/cpp/module.cc new file mode 100644 index 00000000000..505991d6e58 --- /dev/null +++ b/chromium/ppapi/cpp/module.cc @@ -0,0 +1,219 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Note that the single accessor, Module::Get(), is not actually implemented +// in this file. This is an intentional hook that allows users of ppapi's +// C++ wrapper objects to provide different semantics for how the singleton +// object is accessed. +// +// In general, users of ppapi will also link in ppp_entrypoints.cc, which +// provides a simple default implementation of Module::Get(). +// +// A notable exception where the default ppp_entrypoints will not work is +// when implementing "internal plugins" that are statically linked into the +// browser. In this case, the process may actually have multiple Modules +// loaded at once making a traditional "singleton" unworkable. To get around +// this, the users of ppapi need to get creative about how to properly +// implement the Module::Get() so that ppapi's C++ wrappers can find the +// right Module object. One example solution is to use thread local storage +// to change the Module* returned based on which thread is invoking the +// function. Leaving Module::Get() unimplemented provides a hook for +// implementing such behavior. + +#include "ppapi/cpp/module.h" + +#include <string.h> + +#include "ppapi/c/pp_instance.h" +#include "ppapi/c/pp_var.h" +#include "ppapi/c/ppp_input_event.h" +#include "ppapi/c/ppp_instance.h" +#include "ppapi/c/ppp_messaging.h" +#include "ppapi/cpp/input_event.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/rect.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/url_loader.h" +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/view.h" + +namespace pp { + +// PPP_InputEvent implementation ----------------------------------------------- + +PP_Bool InputEvent_HandleEvent(PP_Instance pp_instance, PP_Resource resource) { + Module* module_singleton = Module::Get(); + if (!module_singleton) + return PP_FALSE; + Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); + if (!instance) + return PP_FALSE; + + return PP_FromBool(instance->HandleInputEvent(InputEvent(resource))); +} + +const PPP_InputEvent input_event_interface = { + &InputEvent_HandleEvent +}; + +// PPP_Instance implementation ------------------------------------------------- + +PP_Bool Instance_DidCreate(PP_Instance pp_instance, + uint32_t argc, + const char* argn[], + const char* argv[]) { + Module* module_singleton = Module::Get(); + if (!module_singleton) + return PP_FALSE; + + Instance* instance = module_singleton->CreateInstance(pp_instance); + if (!instance) + return PP_FALSE; + module_singleton->current_instances_[pp_instance] = instance; + return PP_FromBool(instance->Init(argc, argn, argv)); +} + +void Instance_DidDestroy(PP_Instance instance) { + Module* module_singleton = Module::Get(); + if (!module_singleton) + return; + Module::InstanceMap::iterator found = + module_singleton->current_instances_.find(instance); + if (found == module_singleton->current_instances_.end()) + return; + + // Remove it from the map before deleting to try to catch reentrancy. + Instance* obj = found->second; + module_singleton->current_instances_.erase(found); + delete obj; +} + +void Instance_DidChangeView(PP_Instance pp_instance, + PP_Resource view_resource) { + Module* module_singleton = Module::Get(); + if (!module_singleton) + return; + Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); + if (!instance) + return; + instance->DidChangeView(View(view_resource)); +} + +void Instance_DidChangeFocus(PP_Instance pp_instance, PP_Bool has_focus) { + Module* module_singleton = Module::Get(); + if (!module_singleton) + return; + Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); + if (!instance) + return; + instance->DidChangeFocus(PP_ToBool(has_focus)); +} + +PP_Bool Instance_HandleDocumentLoad(PP_Instance pp_instance, + PP_Resource pp_url_loader) { + Module* module_singleton = Module::Get(); + if (!module_singleton) + return PP_FALSE; + Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); + if (!instance) + return PP_FALSE; + return PP_FromBool(instance->HandleDocumentLoad(URLLoader(pp_url_loader))); +} + +static PPP_Instance instance_interface = { + &Instance_DidCreate, + &Instance_DidDestroy, + &Instance_DidChangeView, + &Instance_DidChangeFocus, + &Instance_HandleDocumentLoad +}; + +// PPP_Messaging implementation ------------------------------------------------ + +void Messaging_HandleMessage(PP_Instance pp_instance, PP_Var var) { + Module* module_singleton = Module::Get(); + if (!module_singleton) + return; + Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); + if (!instance) + return; + instance->HandleMessage(Var(PASS_REF, var)); +} + +static PPP_Messaging instance_messaging_interface = { + &Messaging_HandleMessage +}; + +// Module ---------------------------------------------------------------------- + +Module::Module() : pp_module_(0), get_browser_interface_(NULL), core_(NULL) { +} + +Module::~Module() { + delete core_; + core_ = NULL; +} + +bool Module::Init() { + return true; +} + +const void* Module::GetPluginInterface(const char* interface_name) { + if (strcmp(interface_name, PPP_INPUT_EVENT_INTERFACE) == 0) + return &input_event_interface; + if (strcmp(interface_name, PPP_INSTANCE_INTERFACE) == 0) + return &instance_interface; + if (strcmp(interface_name, PPP_MESSAGING_INTERFACE) == 0) + return &instance_messaging_interface; + + // Now see if anything was dynamically registered. + InterfaceMap::const_iterator found = additional_interfaces_.find( + std::string(interface_name)); + if (found != additional_interfaces_.end()) + return found->second; + + return NULL; +} + +const void* Module::GetBrowserInterface(const char* interface_name) { + return get_browser_interface_(interface_name); +} + +Instance* Module::InstanceForPPInstance(PP_Instance instance) { + InstanceMap::iterator found = current_instances_.find(instance); + if (found == current_instances_.end()) + return NULL; + return found->second; +} + +void Module::AddPluginInterface(const std::string& interface_name, + const void* vtable) { + // Verify that we're not trying to register an interface that's already + // handled, and if it is, that we're re-registering with the same vtable. + // Calling GetPluginInterface rather than looking it up in the map allows + // us to also catch "internal" ones in addition to just previously added ones. + const void* existing_interface = GetPluginInterface(interface_name.c_str()); + if (existing_interface) { + PP_DCHECK(vtable == existing_interface); + return; + } + additional_interfaces_[interface_name] = vtable; +} + +bool Module::InternalInit(PP_Module mod, + PPB_GetInterface get_browser_interface) { + pp_module_ = mod; + get_browser_interface_ = get_browser_interface; + + // Get the core interface which we require to run. + const PPB_Core* core = reinterpret_cast<const PPB_Core*>(GetBrowserInterface( + PPB_CORE_INTERFACE)); + if (!core) + return false; + core_ = new Core(core); + + return Init(); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/module.h b/chromium/ppapi/cpp/module.h new file mode 100644 index 00000000000..40de3b8a583 --- /dev/null +++ b/chromium/ppapi/cpp/module.h @@ -0,0 +1,173 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_MODULE_H_ +#define PPAPI_CPP_MODULE_H_ + +#include <map> +#include <string> + +#include "ppapi/c/pp_instance.h" +#include "ppapi/c/pp_module.h" +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/ppb.h" +#include "ppapi/c/ppb_core.h" +#include "ppapi/cpp/core.h" + + +/// @file +/// This file defines a Module class. +namespace pp { + +class Instance; + +/// The Module class. The browser calls CreateInstance() to create +/// an instance of your module on the web page. The browser creates a new +/// instance for each <code>\<embed></code> tag with +/// <code>type="application/x-nacl"</code> +class Module { + public: + typedef std::map<PP_Instance, Instance*> InstanceMap; + + // You may not call any other PP functions from the constructor, put them + // in Init instead. Various things will not be set up until the constructor + // completes. + Module(); + virtual ~Module(); + + /// Get() returns the global instance of this module object, or NULL if the + /// module is not initialized yet. + /// + /// @return The global instance of the module object. + static Module* Get(); + + /// Init() is automatically called after the object is created. This is where + /// you can put functions that rely on other parts of the API, now that the + /// module has been created. + /// + /// @return true if successful, otherwise false. + virtual bool Init(); + + /// The pp_module() function returns the internal module handle. + /// + /// @return A <code>PP_Module</code> internal module handle. + PP_Module pp_module() const { return pp_module_; } + + /// The get_browser_interface() function returns the internal + /// <code>get_browser_interface</code> pointer. + /// + /// @return A <code>PPB_GetInterface</code> internal pointer. + // TODO(sehr): This should be removed once the NaCl browser plugin no longer + // needs it. + PPB_GetInterface get_browser_interface() const { + return get_browser_interface_; + } + + /// The core() function returns the core interface for doing basic + /// global operations. The return value is guaranteed to be non-NULL once the + /// module has successfully initialized and during the Init() call. + /// + /// It will be NULL before Init() has been called. + /// + /// @return The core interface for doing basic global operations. + Core* core() { return core_; } + + /// GetPluginInterface() implements <code>GetInterface</code> for the browser + /// to get module interfaces. If you need to provide your own implementations + /// of new interfaces, use AddPluginInterface() which this function will use. + /// + /// @param[in] interface_name The module interface for the browser to get. + const void* GetPluginInterface(const char* interface_name); + + /// GetBrowserInterface() returns interfaces which the browser implements + /// (i.e. PPB interfaces). + /// @param[in] interface_name The browser interface for the module to get. + const void* GetBrowserInterface(const char* interface_name); + + /// InstanceForPPInstance() returns the object associated with this + /// <code>PP_Instance</code>, or NULL if one is not found. This should only + /// be called from the main thread! This instance object may be destroyed at + /// any time on the main thread, so using it on other threads may cause a + /// crash. + /// + /// @param[in] instance This <code>PP_Instance</code>. + /// + /// @return The object associated with this <code>PP_Instance</code>, + /// or NULL if one is not found. + Instance* InstanceForPPInstance(PP_Instance instance); + + /// AddPluginInterface() adds a handler for a provided interface name. When + /// the browser requests that interface name, the provided + /// <code>vtable</code> will be returned. + /// + /// In general, modules will not need to call this directly. Instead, the + /// C++ wrappers for each interface will register themselves with this + /// function. + /// + /// This function may be called more than once with the same interface name + /// and vtable with no effect. However, it may not be used to register a + /// different vtable for an already-registered interface. It will assert for + /// a different registration for an already-registered interface in debug + /// mode, and just ignore the registration in release mode. + /// + /// @param[in] interface_name The interface name that will receive a handler. + /// @param[in,out] vtable The vtable to return for + /// <code>interface_name</code>. + void AddPluginInterface(const std::string& interface_name, + const void* vtable); + + // InternalInit() sets the browser interface and calls the regular Init() + /// function that can be overridden by the base classes. + /// + /// @param[in] mod A <code>PP_Module</code>. + /// @param[in] get_browser_interface The browser interface to set. + /// + /// @return true if successful, otherwise false. + // TODO(brettw) make this private when I can figure out how to make the + // initialize function a friend. + bool InternalInit(PP_Module mod, + PPB_GetInterface get_browser_interface); + + /// The current_instances() function allows iteration over the + /// current instances in the module. + /// + /// @return An <code>InstanceMap</code> of all instances in the module. + const InstanceMap& current_instances() const { return current_instances_; } + + protected: + /// CreateInstance() should be overridden to create your own module type. + /// + /// @param[in] instance A <code>PP_Instance</code>. + /// + /// @return The resulting instance. + virtual Instance* CreateInstance(PP_Instance instance) = 0; + + private: + friend PP_Bool Instance_DidCreate(PP_Instance pp_instance, + uint32_t argc, + const char* argn[], + const char* argv[]); + friend void Instance_DidDestroy(PP_Instance instance); + + // Unimplemented (disallow copy and assign). + Module(const Module&); + Module& operator=(const Module&); + + // Instance tracking. + InstanceMap current_instances_; + + PP_Module pp_module_; + PPB_GetInterface get_browser_interface_; + + Core* core_; + + // All additional interfaces this plugin can handle as registered by + // AddPluginInterface. + typedef std::map<std::string, const void*> InterfaceMap; + InterfaceMap additional_interfaces_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_MODULE_H_ diff --git a/chromium/ppapi/cpp/module_embedder.h b/chromium/ppapi/cpp/module_embedder.h new file mode 100644 index 00000000000..a1d00a864f3 --- /dev/null +++ b/chromium/ppapi/cpp/module_embedder.h @@ -0,0 +1,40 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_MODULE_EMBEDDER_H_ +#define PPAPI_CPP_MODULE_EMBEDDER_H_ + +#include "ppapi/c/ppp.h" + +/// @file +/// This file defines the APIs for creating a Module object. +namespace pp { + +class Module; + +/// This function creates the <code>pp::Module</code> object associated with +/// this module. +/// +/// <strong>Note: </strong>NaCl module developers must implement this function. +/// +/// @return Returns the module if it was successfully created, or NULL on +/// failure. Upon failure, the module will be unloaded. +pp::Module* CreateModule(); + +/// Sets the get interface function in the broker process. +/// +/// This function is only relevant when you're using the PPB_Broker interface +/// in a trusted native plugin. In this case, you may need to implement +/// PPP_GetInterface when the plugin is loaded in the unsandboxed process. +/// Normally the C++ wrappers implement PPP_GetInterface for you but this +/// doesn't work in the context of the broker process. +// +/// So if you need to implement PPP_* interfaces in the broker process, call +/// this function in your PPP_InitializeBroker implementation which will set +/// up the given function as implementing PPP_GetInterface. +void SetBrokerGetInterfaceFunc(PP_GetInterface_Func broker_get_interface); + +} // namespace pp + +#endif // PPAPI_CPP_MODULE_EMBEDDER_H_ diff --git a/chromium/ppapi/cpp/module_impl.h b/chromium/ppapi/cpp/module_impl.h new file mode 100644 index 00000000000..fa2c61923be --- /dev/null +++ b/chromium/ppapi/cpp/module_impl.h @@ -0,0 +1,39 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_MODULE_IMPL_H_ +#define PPAPI_CPP_MODULE_IMPL_H_ + +/// @file +/// This file defines some simple function templates that help the C++ wrappers +/// (and are not for external developers to use). + +#include "ppapi/cpp/module.h" + +namespace pp { + +namespace { + +// Specialize this function to return the interface string corresponding to the +// PP?_XXX structure. +template <typename T> const char* interface_name() { + return NULL; +} + +template <typename T> inline T const* get_interface() { + static T const* funcs = reinterpret_cast<T const*>( + pp::Module::Get()->GetBrowserInterface(interface_name<T>())); + return funcs; +} + +template <typename T> inline bool has_interface() { + return get_interface<T>() != NULL; +} + +} // namespace + +} // namespace pp + +#endif // PPAPI_CPP_MODULE_IMPL_H_ + diff --git a/chromium/ppapi/cpp/mouse_cursor.cc b/chromium/ppapi/cpp/mouse_cursor.cc new file mode 100644 index 00000000000..acef57a0b6e --- /dev/null +++ b/chromium/ppapi/cpp/mouse_cursor.cc @@ -0,0 +1,31 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/mouse_cursor.h" + +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_MouseCursor_1_0>() { + return PPB_MOUSECURSOR_INTERFACE_1_0; +} + +} // namespace + +// static +bool MouseCursor::SetCursor(const InstanceHandle& instance, + PP_MouseCursor_Type type, + const ImageData& image, + const Point& hot_spot) { + if (!has_interface<PPB_MouseCursor_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_MouseCursor_1_0>()->SetCursor( + instance.pp_instance(), type, image.pp_resource(), + &hot_spot.pp_point())); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/mouse_cursor.h b/chromium/ppapi/cpp/mouse_cursor.h new file mode 100644 index 00000000000..827d95cdf4e --- /dev/null +++ b/chromium/ppapi/cpp/mouse_cursor.h @@ -0,0 +1,56 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_MOUSE_CURSOR_H_ +#define PPAPI_CPP_MOUSE_CURSOR_H_ + +#include "ppapi/c/ppb_mouse_cursor.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/point.h" + +namespace pp { + +class MouseCursor { + public: + /// Sets the given mouse cursor. The mouse cursor will be in effect whenever + /// the mouse is over the given instance until it is set again by another + /// call. Note that you can hide the mouse cursor by setting it to the + /// <code>PP_MOUSECURSOR_TYPE_NONE</code> type. + /// + /// This function allows setting both system defined mouse cursors and + /// custom cursors. To set a system-defined cursor, pass the type you want + /// and set the custom image to a default-constructor ImageData object. + /// To set a custom cursor, set the type to + /// <code>PP_MOUSECURSOR_TYPE_CUSTOM</code> and specify your image and hot + /// spot. + /// + /// @param[in] instance A handle identifying the instance that the mouse + /// cursor will affect. + /// + /// @param[in] type A <code>PP_MouseCursor_Type</code> identifying the type + /// of mouse cursor to show. See <code>ppapi/c/ppb_mouse_cursor.h</code>. + /// + /// @param[in] image A <code>ImageData</code> object identifying the + /// custom image to set when the type is + /// <code>PP_MOUSECURSOR_TYPE_CUSTOM</code>. The image must be less than 32 + /// pixels in each direction and must be of the system's native image format. + /// When you are specifying a predefined cursor, this parameter should be a + /// default-constructed ImageData. + /// + /// @param[in] hot_spot When setting a custom cursor, this identifies the + /// pixel position within the given image of the "hot spot" of the cursor. + /// When specifying a stock cursor, this parameter is ignored. + /// + /// @return true on success, or false if the instance or cursor type + /// was invalid or if the image was too large. + static bool SetCursor(const InstanceHandle& instance, + PP_MouseCursor_Type type, + const ImageData& image = ImageData(), + const Point& hot_spot = Point(0, 0)); +}; + +} // namespace pp + +#endif // PPAPI_CPP_MOUSE_CURSOR_H_ diff --git a/chromium/ppapi/cpp/mouse_lock.cc b/chromium/ppapi/cpp/mouse_lock.cc new file mode 100644 index 00000000000..2ece8fac263 --- /dev/null +++ b/chromium/ppapi/cpp/mouse_lock.cc @@ -0,0 +1,64 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/mouse_lock.h" + +#include "ppapi/c/ppb_mouse_lock.h" +#include "ppapi/c/ppp_mouse_lock.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +static const char kPPPMouseLockInterface[] = PPP_MOUSELOCK_INTERFACE; + +void MouseLockLost(PP_Instance instance) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPMouseLockInterface); + if (!object) + return; + static_cast<MouseLock*>(object)->MouseLockLost(); +} + +const PPP_MouseLock ppp_mouse_lock = { + &MouseLockLost +}; + +template <> const char* interface_name<PPB_MouseLock_1_0>() { + return PPB_MOUSELOCK_INTERFACE_1_0; +} + +} // namespace + +MouseLock::MouseLock(Instance* instance) + : associated_instance_(instance) { + Module::Get()->AddPluginInterface(kPPPMouseLockInterface, &ppp_mouse_lock); + instance->AddPerInstanceObject(kPPPMouseLockInterface, this); +} + +MouseLock::~MouseLock() { + Instance::RemovePerInstanceObject(associated_instance_, + kPPPMouseLockInterface, this); +} + +int32_t MouseLock::LockMouse(const CompletionCallback& cc) { + if (!has_interface<PPB_MouseLock_1_0>()) + return cc.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_MouseLock_1_0>()->LockMouse( + associated_instance_.pp_instance(), cc.pp_completion_callback()); +} + +void MouseLock::UnlockMouse() { + if (has_interface<PPB_MouseLock_1_0>()) { + get_interface<PPB_MouseLock_1_0>()->UnlockMouse( + associated_instance_.pp_instance()); + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/mouse_lock.h b/chromium/ppapi/cpp/mouse_lock.h new file mode 100644 index 00000000000..ed5b07aa832 --- /dev/null +++ b/chromium/ppapi/cpp/mouse_lock.h @@ -0,0 +1,98 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_MOUSE_LOCK_H_ +#define PPAPI_CPP_MOUSE_LOCK_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/instance_handle.h" + +/// @file +/// This file defines the API for locking the target of mouse events to a +/// specific module instance. + +namespace pp { + +class CompletionCallback; +class Instance; + +/// This class allows you to associate the <code>PPP_MouseLock</code> and +/// <code>PPB_MouseLock</code> C-based interfaces with an object. It associates +/// itself with the given instance, and registers as the global handler for +/// handling the <code>PPP_MouseLock</code> interface that the browser calls. +/// +/// You would typically use this class by inheritance on your instance or by +/// composition. +/// +/// <strong>Example (inheritance):</strong> +/// @code +/// class MyInstance : public pp::Instance, public pp::MouseLock { +/// class MyInstance() : pp::MouseLock(this) { +/// } +/// ... +/// }; +/// @endcode +/// +/// <strong>Example (composition):</strong> +/// @code +/// class MyMouseLock : public pp::MouseLock { +/// ... +/// }; +/// +/// class MyInstance : public pp::Instance { +/// MyInstance() : mouse_lock_(this) { +/// } +/// +/// MyMouseLock mouse_lock_; +/// }; +/// @endcode +class MouseLock { + public: + /// A constructor for creating a <code>MouseLock</code>. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit MouseLock(Instance* instance); + + /// Destructor. + virtual ~MouseLock(); + + /// PPP_MouseLock functions exposed as virtual functions for you to override. + virtual void MouseLockLost() = 0; + + /// LockMouse() requests the mouse to be locked. + /// + /// While the mouse is locked, the cursor is implicitly hidden from the user. + /// Any movement of the mouse will generate a + /// <code>PP_INPUTEVENT_TYPE_MOUSEMOVE</code> event. The + /// <code>GetPosition()</code> function in <code>InputEvent()</code> + /// reports the last known mouse position just as mouse lock was + /// entered. The <code>GetMovement()</code> function provides relative + /// movement information indicating what the change in position of the mouse + /// would be had it not been locked. + /// + /// The browser may revoke the mouse lock for reasons including (but not + /// limited to) the user pressing the ESC key, the user activating another + /// program using a reserved keystroke (e.g. ALT+TAB), or some other system + /// event. + /// + /// @param[in] cc A <code>CompletionCallback</code> to be called upon + /// completion. + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + int32_t LockMouse(const CompletionCallback& cc); + + /// UnlockMouse causes the mouse to be unlocked, allowing it to track user + /// movement again. This is an asynchronous operation. The module instance + /// will be notified using the <code>PPP_MouseLock</code> interface when it + /// has lost the mouse lock. + void UnlockMouse(); + + private: + InstanceHandle associated_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_MOUSE_LOCK_H_ diff --git a/chromium/ppapi/cpp/net_address.cc b/chromium/ppapi/cpp/net_address.cc new file mode 100644 index 00000000000..e96b03da126 --- /dev/null +++ b/chromium/ppapi/cpp/net_address.cc @@ -0,0 +1,99 @@ +// Copyright 2013 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 "ppapi/cpp/net_address.h" + +#include "ppapi/c/pp_bool.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_NetAddress_1_0>() { + return PPB_NETADDRESS_INTERFACE_1_0; +} + +} // namespace + +NetAddress::NetAddress() { +} + +NetAddress::NetAddress(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +NetAddress::NetAddress(const InstanceHandle& instance, + const PP_NetAddress_IPv4& ipv4_addr) { + if (has_interface<PPB_NetAddress_1_0>()) { + PassRefFromConstructor( + get_interface<PPB_NetAddress_1_0>()->CreateFromIPv4Address( + instance.pp_instance(), &ipv4_addr)); + } +} + +NetAddress::NetAddress(const InstanceHandle& instance, + const PP_NetAddress_IPv6& ipv6_addr) { + if (has_interface<PPB_NetAddress_1_0>()) { + PassRefFromConstructor( + get_interface<PPB_NetAddress_1_0>()->CreateFromIPv6Address( + instance.pp_instance(), &ipv6_addr)); + } +} + +NetAddress::NetAddress(const NetAddress& other) : Resource(other) { +} + +NetAddress::~NetAddress() { +} + +NetAddress& NetAddress::operator=(const NetAddress& other) { + Resource::operator=(other); + return *this; +} + +// static +bool NetAddress::IsAvailable() { + return has_interface<PPB_NetAddress_1_0>(); +} + +PP_NetAddress_Family NetAddress::GetFamily() const { + if (has_interface<PPB_NetAddress_1_0>()) + return get_interface<PPB_NetAddress_1_0>()->GetFamily(pp_resource()); + + return PP_NETADDRESS_FAMILY_UNSPECIFIED; +} + +Var NetAddress::DescribeAsString(bool include_port) const { + if (has_interface<PPB_NetAddress_1_0>()) { + return Var(PASS_REF, + get_interface<PPB_NetAddress_1_0>()->DescribeAsString( + pp_resource(), PP_FromBool(include_port))); + } + + return Var(); +} + +bool NetAddress::DescribeAsIPv4Address(PP_NetAddress_IPv4* ipv4_addr) const { + if (has_interface<PPB_NetAddress_1_0>()) { + return PP_ToBool( + get_interface<PPB_NetAddress_1_0>()->DescribeAsIPv4Address( + pp_resource(), ipv4_addr)); + } + + return false; +} + +bool NetAddress::DescribeAsIPv6Address(PP_NetAddress_IPv6* ipv6_addr) const { + if (has_interface<PPB_NetAddress_1_0>()) { + return PP_ToBool( + get_interface<PPB_NetAddress_1_0>()->DescribeAsIPv6Address( + pp_resource(), ipv6_addr)); + } + + return false; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/net_address.h b/chromium/ppapi/cpp/net_address.h new file mode 100644 index 00000000000..9f101f24788 --- /dev/null +++ b/chromium/ppapi/cpp/net_address.h @@ -0,0 +1,114 @@ +// Copyright 2013 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. + +#ifndef PPAPI_CPP_NET_ADDRESS_H_ +#define PPAPI_CPP_NET_ADDRESS_H_ + +#include "ppapi/c/ppb_net_address.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +class InstanceHandle; + +/// The <code>NetAddress</code> class represents a network address. +class NetAddress : public Resource { + public: + /// Default constructor for creating an is_null() <code>NetAddress</code> + /// object. + NetAddress(); + + /// A constructor used when you have received a <code>PP_Resource</code> as a + /// return value that has had 1 ref added for you. + /// + /// @param[in] resource A <code>PPB_NetAddress</code> resource. + NetAddress(PassRef, PP_Resource resource); + + /// A constructor used to create a <code>NetAddress</code> object with the + /// specified IPv4 address. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + /// @param[in] ipv4_addr An IPv4 address. + NetAddress(const InstanceHandle& instance, + const PP_NetAddress_IPv4& ipv4_addr); + + /// A constructor used to create a <code>NetAddress</code> object with the + /// specified IPv6 address. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + /// @param[in] ipv6_addr An IPv6 address. + NetAddress(const InstanceHandle& instance, + const PP_NetAddress_IPv6& ipv6_addr); + + /// The copy constructor for <code>NetAddress</code>. + /// + /// @param[in] other A reference to another <code>NetAddress</code>. + NetAddress(const NetAddress& other); + + /// The destructor. + virtual ~NetAddress(); + + /// The assignment operator for <code>NetAddress</code>. + /// + /// @param[in] other A reference to another <code>NetAddress</code>. + /// + /// @return A reference to this <code>NetAddress</code> object. + NetAddress& operator=(const NetAddress& other); + + /// Static function for determining whether the browser supports the + /// <code>PPB_NetAddress</code> interface. + /// + /// @return true if the interface is available, false otherwise. + static bool IsAvailable(); + + /// Gets the address family. + /// + /// @return The address family on success; + /// <code>PP_NETADDRESS_FAMILY_UNSPECIFIED</code> on failure. + PP_NetAddress_Family GetFamily() const; + + /// Returns a human-readable description of the network address. The + /// description is in the form of host [ ":" port ] and conforms to + /// http://tools.ietf.org/html/rfc3986#section-3.2 for IPv4 and IPv6 addresses + /// (e.g., "192.168.0.1", "192.168.0.1:99", or "[::1]:80"). + /// + /// @param[in] include_port Whether to include the port number in the + /// description. + /// + /// @return A string <code>Var</code> on success; an undefined + /// <code>Var</code> on failure. + Var DescribeAsString(bool include_port) const; + + /// Fills a <code>PP_NetAddress_IPv4</code> structure if the network address + /// is of <code>PP_NETADDRESS_FAMILY_IPV4</code> address family. + /// Note that passing a network address of + /// <code>PP_NETADDRESS_FAMILY_IPV6</code> address family will fail even if + /// the address is an IPv4-mapped IPv6 address. + /// + /// @param[out] ipv4_addr A <code>PP_NetAddress_IPv4</code> structure to store + /// the result. + /// + /// @return A boolean value indicating whether the operation succeeded. + bool DescribeAsIPv4Address(PP_NetAddress_IPv4* ipv4_addr) const; + + /// Fills a <code>PP_NetAddress_IPv6</code> structure if the network address + /// is of <code>PP_NETADDRESS_FAMILY_IPV6</code> address family. + /// Note that passing a network address of + /// <code>PP_NETADDRESS_FAMILY_IPV4</code> address family will fail - this + /// method doesn't map it to an IPv6 address. + /// + /// @param[out] ipv6_addr A <code>PP_NetAddress_IPv6</code> structure to store + /// the result. + /// + /// @return A boolean value indicating whether the operation succeeded. + bool DescribeAsIPv6Address(PP_NetAddress_IPv6* ipv6_addr) const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_NET_ADDRESS_H_ diff --git a/chromium/ppapi/cpp/network_proxy.cc b/chromium/ppapi/cpp/network_proxy.cc new file mode 100644 index 00000000000..2d81cb3f63d --- /dev/null +++ b/chromium/ppapi/cpp/network_proxy.cc @@ -0,0 +1,38 @@ +// Copyright 2013 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 "ppapi/cpp/network_proxy.h" + +#include "ppapi/c/ppb_network_proxy.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_NetworkProxy_1_0>() { + return PPB_NETWORKPROXY_INTERFACE_1_0; +} + +} // namespace + +// static +bool NetworkProxy::IsAvailable() { + return has_interface<PPB_NetworkProxy_1_0>(); +} + +// static +int32_t NetworkProxy::GetProxyForURL( + const InstanceHandle& instance, + const Var& url, + const CompletionCallbackWithOutput<Var>& callback) { + if (!has_interface<PPB_NetworkProxy_1_0>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + + return get_interface<PPB_NetworkProxy_1_0>()->GetProxyForURL( + instance.pp_instance(), url.pp_var(), + callback.output(), callback.pp_completion_callback()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/network_proxy.h b/chromium/ppapi/cpp/network_proxy.h new file mode 100644 index 00000000000..25696de5a4b --- /dev/null +++ b/chromium/ppapi/cpp/network_proxy.h @@ -0,0 +1,49 @@ +// Copyright 2013 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. + +#ifndef PPAPI_CPP_NETWORK_PROXY_H_ +#define PPAPI_CPP_NETWORK_PROXY_H_ + +#include <string> + +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +/// This class provides a way to determine the appropriate proxy settings for +/// for a given URL. +/// +/// Permissions: Apps permission <code>socket</code> with subrule +/// <code>resolve-proxy</code> is required for using this API. +/// For more details about network communication permissions, please see: +/// http://developer.chrome.com/apps/app_network.html +class NetworkProxy { + public: + /// Returns true if the browser supports this API, false otherwise. + static bool IsAvailable(); + + /// Retrieves the proxy that will be used for the given URL. The result will + /// be a string in PAC format. For more details about PAC format, please see + /// http://en.wikipedia.org/wiki/Proxy_auto-config + /// + /// @param[in] instance An <code>InstanceHandle</code> identifying one + /// instance of a module. + /// + /// @param[in] url A string <code>Var</code> containing a URL. + /// + /// @param[in] callback A <code>CompletionCallbackWithOutput</code> to be + /// called upon completion. It will be passed a string <code>Var</code> + /// containing the appropriate PAC string for <code>url</code>. + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + static int32_t GetProxyForURL( + const InstanceHandle& instance, + const Var& url, + const pp::CompletionCallbackWithOutput<Var>& callback); +}; + +} // namespace pp + +#endif // PPAPI_CPP_NETWORK_PROXY_H_ diff --git a/chromium/ppapi/cpp/output_traits.h b/chromium/ppapi/cpp/output_traits.h new file mode 100644 index 00000000000..37a8a656e12 --- /dev/null +++ b/chromium/ppapi/cpp/output_traits.h @@ -0,0 +1,259 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_OUTPUT_TRAITS_H_ +#define PPAPI_CPP_OUTPUT_TRAITS_H_ + +#include <vector> + +#include "ppapi/c/pp_resource.h" +#include "ppapi/cpp/array_output.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines internal templates for defining how data is passed to the +/// browser via output parameters and how to convert that data to the +/// corresponding C++ object types. +/// +/// It is used by the callback system, it should not be necessary for end-users +/// to use these templates directly. + +struct PP_Var; + +namespace pp { + +class Var; + +namespace internal { + +// This goop is a trick used to implement a template that can be used to +// determine if a given class is the base class of another given class. It is +// used in the resource object partial specialization below. +template<typename, typename> struct IsSame { + static bool const value = false; +}; +template<typename A> struct IsSame<A, A> { + static bool const value = true; +}; +template<typename Base, typename Derived> struct IsBaseOf { + private: + // This class doesn't work correctly with forward declarations. + // Because sizeof cannot be applied to incomplete types, this line prevents us + // from passing in forward declarations. + typedef char (*EnsureTypesAreComplete)[sizeof(Base) + sizeof(Derived)]; + + static Derived* CreateDerived(); + static char (&Check(Base*))[1]; + static char (&Check(...))[2]; + + public: + static bool const value = sizeof Check(CreateDerived()) == 1 && + !IsSame<Base const, void const>::value; +}; + +// Template to optionally derive from a given base class T if the given +// predicate P is true. +template <class T, bool P> struct InheritIf {}; +template <class T> struct InheritIf<T, true> : public T {}; + +// Single output parameters ---------------------------------------------------- + +// Output traits for all "plain old data" (POD) types. It is implemented to +// pass a pointer to the browser as an output parameter. +// +// This is used as a base class for the general CallbackOutputTraits below in +// the case where T is not a resource. +template<typename T> +struct GenericCallbackOutputTraits { + // The type passed to the PPAPI C API for this parameter. For normal out + // params, we pass a pointer to the object so the browser can write into it. + typedef T* APIArgType; + + // The type used to store the value. This is used internally in asynchronous + // callbacks by the CompletionCallbackFactory to have the browser write into + // a temporary value associated with the callback, which is passed to the + // plugin code when the callback is issued. + typedef T StorageType; + + // Converts a "storage type" to a value that can be passed to the browser as + // an output parameter. This just takes the address to convert the value to + // a pointer. + static inline APIArgType StorageToAPIArg(StorageType& t) { return &t; } + + // Converts the "storage type" to the value we pass to the plugin for + // callbacks. This doesn't actually need to do anything in this case, + // it's needed for some of more complex template specializations below. + static inline T& StorageToPluginArg(StorageType& t) { return t; } + + // Initializes the "storage type" to a default value, if necessary. Here, + // we do nothing, assuming that the default constructor for T suffices. + static inline void Initialize(StorageType* /* t */) {} +}; + +// Output traits for all resource types. It is implemented to pass a +// PP_Resource* as an output parameter to the browser, and convert to the +// given resource object type T when passing to the plugin. +// +// Note that this class is parameterized by the resource object, for example +// ResourceCallbackOutputTraits<pp::FileRef>. This is used as a base class for +// CallbackOutputTraits below for the case where T is a derived class of +// pp::Resource. +template<typename T> +struct ResourceCallbackOutputTraits { + // To call the browser, we just pass a PP_Resource pointer as the out param. + typedef PP_Resource* APIArgType; + typedef PP_Resource StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return &t; + } + + // Converts the PP_Resource to a pp::* object, passing any reference counted + // object along with it. This must only be called once since there will only + // be one reference that the browser has assigned to us for the out param! + // When calling into the plugin, convert the PP_Resource into the requested + // resource object type. + static inline T StorageToPluginArg(StorageType& t) { + return T(PASS_REF, t); + } + + static inline void Initialize(StorageType* t) { + *t = 0; + } +}; + +// The general templatized base class for all CallbackOutputTraits. This class +// covers both resources and POD (ints, structs, etc.) by inheriting from the +// appropriate base class depending on whether the given type derives from +// pp::Resource. This trick allows us to do this once rather than writing +// specializations for every resource object type. +template<typename T> +struct CallbackOutputTraits + : public InheritIf<GenericCallbackOutputTraits<T>, + !IsBaseOf<Resource, T>::value>, + public InheritIf<ResourceCallbackOutputTraits<T>, + IsBaseOf<Resource, T>::value> { +}; + +// A specialization of CallbackOutputTraits for pp::Var output parameters. +// It passes a PP_Var* to the browser and converts to a pp::Var when passing +// to the plugin. +template<> +struct CallbackOutputTraits<Var> { + // To call the browser, we just pass a PP_Var* as an output param. + typedef PP_Var* APIArgType; + typedef PP_Var StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return &t; + } + + // Converts the PP_Var to a pp::Var object, passing any reference counted + // object along with it. This must only be called once since there will only + // be one reference that the browser has assigned to us for the out param! + static inline pp::Var StorageToPluginArg(StorageType& t) { + return Var(PASS_REF, t); + } + + static inline void Initialize(StorageType* t) { + *t = PP_MakeUndefined(); + } +}; + +// Array output parameters ----------------------------------------------------- + +// Output traits for vectors of all "plain old data" (POD) types. It is +// implemented to pass a pointer to the browser as an output parameter. +// +// This is used as a base class for the general vector CallbackOutputTraits +// below in the case where T is not a resource. +template<typename T> +struct GenericVectorCallbackOutputTraits { + // All arrays are output via a PP_ArrayOutput type. + typedef PP_ArrayOutput APIArgType; + + // We store the array as this adapter which combines the PP_ArrayOutput + // structure with the underlying std::vector that it will write into. + typedef ArrayOutputAdapterWithStorage<T> StorageType; + + // Retrieves the PP_ArrayOutput interface for our vector object that the + // browser will use to write into our code. + static inline APIArgType StorageToAPIArg(StorageType& t) { + return t.pp_array_output(); + } + + // Retrieves the underlying vector that can be passed to the plugin. + static inline std::vector<T>& StorageToPluginArg(StorageType& t) { + return t.output(); + } + + static inline void Initialize(StorageType* /* t */) {} +}; + +// Output traits for all vectors of resource types. It is implemented to pass +// a PP_ArrayOutput parameter to the browser, and convert the returned resources +// to a vector of the given resource object type T when passing to the plugin. +// +// Note that this class is parameterized by the resource object, for example +// ResourceVectorCallbackOutputTraits<pp::FileRef>. This is used as a base +// class for CallbackOutputTraits below for the case where T is a derived +// class of pp::Resource. +template<typename T> +struct ResourceVectorCallbackOutputTraits { + typedef PP_ArrayOutput APIArgType; + typedef ResourceArrayOutputAdapterWithStorage<T> StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return t.pp_array_output(); + } + static inline std::vector<T>& StorageToPluginArg(StorageType& t) { + return t.output(); + } + + static inline void Initialize(StorageType* /* t */) {} +}; + +// Specialization of CallbackOutputTraits for vectors. This struct covers both +// arrays of resources and arrays of POD (ints, structs, etc.) by inheriting +// from the appropriate base class depending on whether the given type derives +// from pp::Resource. This trick allows us to do this once rather than writing +// specializations for every resource object type. +template<typename T> +struct CallbackOutputTraits< std::vector<T> > + : public InheritIf<GenericVectorCallbackOutputTraits<T>, + !IsBaseOf<Resource, T>::value>, + public InheritIf<ResourceVectorCallbackOutputTraits<T>, + IsBaseOf<Resource, T>::value> { +}; + +// A specialization of CallbackOutputTraits to provide the callback system +// the information on how to handle vectors of pp::Var. Vectors of resources +// and plain data are handled separately. See the above definition for more. +template<> +struct CallbackOutputTraits< std::vector<pp::Var> > { + // All arrays are output via a PP_ArrayOutput type. + typedef PP_ArrayOutput APIArgType; + + // We store the array as this adapter which combines the PP_ArrayOutput + // structure with the underlying std::vector that it will write into. + typedef VarArrayOutputAdapterWithStorage StorageType; + + // Retrieves the PP_ArrayOutput interface for our vector object that the + // browser will use to write into our code. + static inline APIArgType StorageToAPIArg(StorageType& t) { + return t.pp_array_output(); + } + + // Retrieves the underlying vector that can be passed to the plugin. + static inline std::vector<pp::Var>& StorageToPluginArg(StorageType& t) { + return t.output(); + } + + static inline void Initialize(StorageType* /* t */) {} +}; + +} // namespace internal +} // namespace pp + +#endif // PPAPI_CPP_OUTPUT_TRAITS_H_ diff --git a/chromium/ppapi/cpp/pass_ref.h b/chromium/ppapi/cpp/pass_ref.h new file mode 100644 index 00000000000..724867421e4 --- /dev/null +++ b/chromium/ppapi/cpp/pass_ref.h @@ -0,0 +1,21 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PASS_REF_H_ +#define PPAPI_CPP_PASS_REF_H_ + +/// @file +/// This file defines an annotation for constructors and other functions that +/// take ownership of a pointer. +namespace pp { + +/// An annotation for constructors and other functions that take ownership of +/// a pointer. For example, a resource constructor that takes ownership of a +/// provided <code>PP_Resource</code> ref count would take this enumeration to +/// differentiate from the more typical use case of taking its own reference. +enum PassRef { PASS_REF }; + +} // namespace pp + +#endif // PPAPI_CPP_PASS_REF_H_ diff --git a/chromium/ppapi/cpp/point.h b/chromium/ppapi/cpp/point.h new file mode 100644 index 00000000000..c881bbd5506 --- /dev/null +++ b/chromium/ppapi/cpp/point.h @@ -0,0 +1,336 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_POINT_H_ +#define PPAPI_CPP_POINT_H_ + +#include "ppapi/c/pp_point.h" + +/// @file +/// This file defines the API to create a 2 dimensional point. + +namespace pp { + +/// A 2 dimensional point with 0,0 being the upper-left starting coordinate. +class Point { + public: + /// The default constructor for a point at 0,0. + Point() { + point_.x = 0; + point_.y = 0; + } + + /// A constructor accepting two int32_t values for x and y and converting + /// them to a Point. + /// + /// @param[in] in_x An int32_t value representing a horizontal coordinate + /// of a point, starting with 0 as the left-most coordinate. + /// @param[in] in_y An int32_t value representing a vertical coordinate + /// of a point, starting with 0 as the top-most coordinate. + Point(int32_t in_x, int32_t in_y) { + point_.x = in_x; + point_.y = in_y; + } + + /// A constructor accepting a pointer to a PP_Point and converting the + /// PP_Point to a Point. This is an implicit conversion constructor. + /// + /// @param[in] point A pointer to a PP_Point. + Point(const PP_Point& point) { // Implicit. + point_.x = point.x; + point_.y = point.y; + } + + /// Destructor. + ~Point() { + } + + /// A function allowing implicit conversion of a Point to a PP_Point. + /// @return A Point. + operator PP_Point() const { + return point_; + } + + /// Getter function for returning the internal PP_Point struct. + /// + /// @return A const reference to the internal PP_Point struct. + const PP_Point& pp_point() const { + return point_; + } + + /// Getter function for returning the internal PP_Point struct. + /// + /// @return A mutable reference to the PP_Point struct. + PP_Point& pp_point() { + return point_; + } + + /// Getter function for returning the value of x. + /// + /// @return The value of x for this Point. + int32_t x() const { return point_.x; } + + /// Setter function for setting the value of x. + /// + /// @param[in] in_x A new x value. + void set_x(int32_t in_x) { + point_.x = in_x; + } + + /// Getter function for returning the value of y. + /// + /// @return The value of y for this Point. + int32_t y() const { return point_.y; } + + /// Setter function for setting the value of y. + /// + /// @param[in] in_y A new y value. + void set_y(int32_t in_y) { + point_.y = in_y; + } + + /// Adds two Points (this and other) together by adding their x values and + /// y values. + /// + /// @param[in] other A Point. + /// + /// @return A new Point containing the result. + Point operator+(const Point& other) const { + return Point(x() + other.x(), y() + other.y()); + } + + /// Subtracts one Point from another Point by subtracting their x values + /// and y values. Returns a new point with the result. + /// + /// @param[in] other A Point. + /// + /// @return A new Point containing the result. + Point operator-(const Point& other) const { + return Point(x() - other.x(), y() - other.y()); + } + + /// Adds two Points (this and other) together by adding their x and y + /// values. Returns this point as the result. + /// + /// @param[in] other A Point. + /// + /// @return This Point containing the result. + Point& operator+=(const Point& other) { + point_.x += other.x(); + point_.y += other.y(); + return *this; + } + + /// Subtracts one Point from another Point by subtracting their x values + /// and y values. Returns this point as the result. + /// + /// @param[in] other A Point. + /// + /// @return This Point containing the result. + Point& operator-=(const Point& other) { + point_.x -= other.x(); + point_.y -= other.y(); + return *this; + } + + /// Swaps the coordinates of two Points. + /// + /// @param[in] other A Point. + void swap(Point& other) { + int32_t x = point_.x; + int32_t y = point_.y; + point_.x = other.point_.x; + point_.y = other.point_.y; + other.point_.x = x; + other.point_.y = y; + } + + private: + PP_Point point_; +}; + +/// A 2 dimensional floating-point point with 0,0 being the upper-left starting +/// coordinate. +class FloatPoint { + public: + /// A constructor for a point at 0,0. + FloatPoint() { + float_point_.x = 0.0f; + float_point_.y = 0.0f; + } + + /// A constructor accepting two values for x and y and converting them to a + /// FloatPoint. + /// + /// @param[in] in_x An value representing a horizontal coordinate of a + /// point, starting with 0 as the left-most coordinate. + /// + /// @param[in] in_y An value representing a vertical coordinate of a point, + /// starting with 0 as the top-most coordinate. + FloatPoint(float in_x, float in_y) { + float_point_.x = in_x; + float_point_.y = in_y; + } + + /// A constructor accepting a pointer to a PP_FloatPoint and converting the + /// PP_Point to a Point. This is an implicit conversion constructor. + /// + /// @param[in] point A PP_FloatPoint. + FloatPoint(const PP_FloatPoint& point) { // Implicit. + float_point_.x = point.x; + float_point_.y = point.y; + } + /// Destructor. + ~FloatPoint() { + } + + /// A function allowing implicit conversion of a FloatPoint to a + /// PP_FloatPoint. + operator PP_FloatPoint() const { + return float_point_; + } + + /// Getter function for returning the internal PP_FloatPoint struct. + /// + /// @return A const reference to the internal PP_FloatPoint struct. + const PP_FloatPoint& pp_float_point() const { + return float_point_; + } + + /// Getter function for returning the internal PP_Point struct. + /// + /// @return A mutable reference to the PP_Point struct. + PP_FloatPoint& pp_float_point() { + return float_point_; + } + + /// Getter function for returning the value of x. + /// + /// @return The value of x for this Point. + float x() const { return float_point_.x; } + + /// Setter function for setting the value of x. + /// + /// @param[in] in_x A new x value. + void set_x(float in_x) { + float_point_.x = in_x; + } + + /// Getter function for returning the value of y. + /// + /// @return The value of y for this Point. + float y() const { return float_point_.y; } + + /// Setter function for setting the value of y. + /// + /// @param[in] in_y A new y value. + void set_y(float in_y) { + float_point_.y = in_y; + } + + /// Adds two Points (this and other) together by adding their x values and + /// y values. + /// + /// @param[in] other A Point. + /// + /// @return A new Point containing the result. + FloatPoint operator+(const FloatPoint& other) const { + return FloatPoint(x() + other.x(), y() + other.y()); + } + + /// Subtracts one Point from another Point by subtracting their x values + /// and y values. Returns a new point with the result. + /// + /// @param[in] other A FloatPoint. + /// + /// @return A new Point containing the result. + FloatPoint operator-(const FloatPoint& other) const { + return FloatPoint(x() - other.x(), y() - other.y()); + } + + /// Adds two Points (this and other) together by adding their x and y + /// values. Returns this point as the result. + /// + /// @param[in] other A Point. + /// + /// @return This Point containing the result. + FloatPoint& operator+=(const FloatPoint& other) { + float_point_.x += other.x(); + float_point_.y += other.y(); + return *this; + } + + /// Subtracts one Point from another Point by subtracting their x values + /// and y values. Returns this point as the result. + /// + /// @param[in] other A Point. + /// + /// @return This Point containing the result. + FloatPoint& operator-=(const FloatPoint& other) { + float_point_.x -= other.x(); + float_point_.y -= other.y(); + return *this; + } + + /// Swaps the coordinates of two Points. + /// + /// @param[in] other A Point. + void swap(FloatPoint& other) { + float x = float_point_.x; + float y = float_point_.y; + float_point_.x = other.float_point_.x; + float_point_.y = other.float_point_.y; + other.float_point_.x = x; + other.float_point_.y = y; + } + + private: + PP_FloatPoint float_point_; +}; + +} // namespace pp + +/// Determines whether the x and y values of two Points are equal. +/// +/// @param[in] lhs The Point on the left-hand side of the equation. +/// @param[in] rhs The Point on the right-hand side of the equation. +/// +/// @return true if they are equal, false if unequal. +inline bool operator==(const pp::Point& lhs, const pp::Point& rhs) { + return lhs.x() == rhs.x() && lhs.y() == rhs.y(); +} + +/// Determines whether two Points have different coordinates. +/// +/// @param[in] lhs The Point on the left-hand side of the equation. +/// @param[in] rhs The Point on the right-hand side of the equation. +/// +/// @return true if the coordinates of lhs are equal to the coordinates +/// of rhs, otherwise false. +inline bool operator!=(const pp::Point& lhs, const pp::Point& rhs) { + return !(lhs == rhs); +} + +/// Determines whether the x and y values of two FloatPoints are equal. +/// +/// @param[in] lhs The Point on the left-hand side of the equation. +/// @param[in] rhs The Point on the right-hand side of the equation. +/// +/// @return true if they are equal, false if unequal. +inline bool operator==(const pp::FloatPoint& lhs, const pp::FloatPoint& rhs) { + return lhs.x() == rhs.x() && lhs.y() == rhs.y(); +} + +/// Determines whether two Points have different coordinates. +/// +/// @param[in] lhs The Point on the left-hand side of the equation. +/// @param[in] rhs The Point on the right-hand side of the equation. +/// +/// @return true if the coordinates of lhs are equal to the coordinates +/// of rhs, otherwise false. +inline bool operator!=(const pp::FloatPoint& lhs, const pp::FloatPoint& rhs) { + return !(lhs == rhs); +} + +#endif // PPAPI_CPP_POINT_H_ diff --git a/chromium/ppapi/cpp/ppp_entrypoints.cc b/chromium/ppapi/cpp/ppp_entrypoints.cc new file mode 100644 index 00000000000..e9e64573c1e --- /dev/null +++ b/chromium/ppapi/cpp/ppp_entrypoints.cc @@ -0,0 +1,59 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// When used in conjunction with module_embedder.h, this gives a default +// implementation of ppp.h for clients of the ppapi C++ interface. Most +// plugin implementors can export their derivation of Module by just +// linking to this implementation. + +#include "ppapi/c/ppb.h" +#include "ppapi/c/ppp.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_embedder.h" + +static pp::Module* g_module_singleton = NULL; +static PP_GetInterface_Func g_broker_get_interface = NULL; + +namespace pp { + +// Give a default implementation of Module::Get(). See module.cc for details. +pp::Module* Module::Get() { + return g_module_singleton; +} + +void SetBrokerGetInterfaceFunc(PP_GetInterface_Func broker_get_interface) { + g_broker_get_interface = broker_get_interface; +} + +} // namespace pp + +// Global PPP functions -------------------------------------------------------- + +PP_EXPORT int32_t PPP_InitializeModule(PP_Module module_id, + PPB_GetInterface get_browser_interface) { + pp::Module* module = pp::CreateModule(); + if (!module) + return PP_ERROR_FAILED; + + if (!module->InternalInit(module_id, get_browser_interface)) { + delete module; + return PP_ERROR_FAILED; + } + g_module_singleton = module; + return PP_OK; +} + +PP_EXPORT void PPP_ShutdownModule() { + delete g_module_singleton; + g_module_singleton = NULL; +} + +PP_EXPORT const void* PPP_GetInterface(const char* interface_name) { + if (g_module_singleton) + return g_module_singleton->GetPluginInterface(interface_name); + if (g_broker_get_interface) + return g_broker_get_interface(interface_name); + return NULL; +} diff --git a/chromium/ppapi/cpp/private/DEPS b/chromium/ppapi/cpp/private/DEPS new file mode 100644 index 00000000000..89916e4d70b --- /dev/null +++ b/chromium/ppapi/cpp/private/DEPS @@ -0,0 +1,5 @@ +include_rules = [ + "+ppapi/c/private", + "+ppapi/c/trusted", + "+ppapi/cpp/trusted", +] diff --git a/chromium/ppapi/cpp/private/content_decryptor_private.cc b/chromium/ppapi/cpp/private/content_decryptor_private.cc new file mode 100644 index 00000000000..48690946128 --- /dev/null +++ b/chromium/ppapi/cpp/private/content_decryptor_private.cc @@ -0,0 +1,346 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/content_decryptor_private.h" + +#include <cstring> // memcpy + +#include "ppapi/c/ppb_var.h" +#include "ppapi/c/private/ppb_content_decryptor_private.h" +#include "ppapi/c/private/ppp_content_decryptor_private.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +static const char kPPPContentDecryptorInterface[] = + PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE; + +void GenerateKeyRequest(PP_Instance instance, + PP_Var key_system_arg, + PP_Var type_arg, + PP_Var init_data_arg) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPContentDecryptorInterface); + if (!object) + return; + + pp::Var key_system_var(pp::PASS_REF, key_system_arg); + if (!key_system_var.is_string()) + return; + + pp::Var type_var(pp::PASS_REF, type_arg); + if (!type_var.is_string()) + return; + + pp::Var init_data_var(pp::PASS_REF, init_data_arg); + if (!init_data_var.is_array_buffer()) + return; + pp::VarArrayBuffer init_data_array_buffer(init_data_var); + + static_cast<ContentDecryptor_Private*>(object)->GenerateKeyRequest( + key_system_var.AsString(), + type_var.AsString(), + init_data_array_buffer); +} + +void AddKey(PP_Instance instance, + PP_Var session_id_arg, + PP_Var key_arg, + PP_Var init_data_arg) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPContentDecryptorInterface); + if (!object) + return; + + pp::Var session_id_var(pp::PASS_REF, session_id_arg); + if (!session_id_var.is_string()) + return; + + pp::Var key_var(pp::PASS_REF, key_arg); + if (!key_var.is_array_buffer()) + return; + pp::VarArrayBuffer key(key_var); + + pp::Var init_data_var(pp::PASS_REF, init_data_arg); + if (!init_data_var.is_array_buffer()) + return; + pp::VarArrayBuffer init_data(init_data_var); + + + static_cast<ContentDecryptor_Private*>(object)->AddKey( + session_id_var.AsString(), + key, + init_data); +} + +void CancelKeyRequest(PP_Instance instance, PP_Var session_id_arg) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPContentDecryptorInterface); + if (!object) + return; + + pp::Var session_id_var(pp::PASS_REF, session_id_arg); + if (!session_id_var.is_string()) + return; + + static_cast<ContentDecryptor_Private*>(object)->CancelKeyRequest( + session_id_var.AsString()); +} + + +void Decrypt(PP_Instance instance, + PP_Resource encrypted_resource, + const PP_EncryptedBlockInfo* encrypted_block_info) { + pp::Buffer_Dev encrypted_block(encrypted_resource); + + void* object = + Instance::GetPerInstanceObject(instance, kPPPContentDecryptorInterface); + if (!object) + return; + + static_cast<ContentDecryptor_Private*>(object)->Decrypt( + encrypted_block, + *encrypted_block_info); +} + +void InitializeAudioDecoder( + PP_Instance instance, + const PP_AudioDecoderConfig* decoder_config, + PP_Resource extra_data_resource) { + pp::Buffer_Dev extra_data_buffer(extra_data_resource); + + void* object = + Instance::GetPerInstanceObject(instance, kPPPContentDecryptorInterface); + if (!object) + return; + + static_cast<ContentDecryptor_Private*>(object)->InitializeAudioDecoder( + *decoder_config, + extra_data_buffer); +} + +void InitializeVideoDecoder( + PP_Instance instance, + const PP_VideoDecoderConfig* decoder_config, + PP_Resource extra_data_resource) { + pp::Buffer_Dev extra_data_buffer(extra_data_resource); + + void* object = + Instance::GetPerInstanceObject(instance, kPPPContentDecryptorInterface); + if (!object) + return; + + static_cast<ContentDecryptor_Private*>(object)->InitializeVideoDecoder( + *decoder_config, + extra_data_buffer); +} + +void DeinitializeDecoder(PP_Instance instance, + PP_DecryptorStreamType decoder_type, + uint32_t request_id) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPContentDecryptorInterface); + if (!object) + return; + static_cast<ContentDecryptor_Private*>(object)->DeinitializeDecoder( + decoder_type, + request_id); +} + +void ResetDecoder(PP_Instance instance, + PP_DecryptorStreamType decoder_type, + uint32_t request_id) { + void* object = + Instance::GetPerInstanceObject(instance, kPPPContentDecryptorInterface); + if (!object) + return; + static_cast<ContentDecryptor_Private*>(object)->ResetDecoder(decoder_type, + request_id); +} + +void DecryptAndDecode(PP_Instance instance, + PP_DecryptorStreamType decoder_type, + PP_Resource encrypted_resource, + const PP_EncryptedBlockInfo* encrypted_block_info) { + pp::Buffer_Dev encrypted_buffer(encrypted_resource); + + void* object = + Instance::GetPerInstanceObject(instance, kPPPContentDecryptorInterface); + if (!object) + return; + + static_cast<ContentDecryptor_Private*>(object)->DecryptAndDecode( + decoder_type, + encrypted_buffer, + *encrypted_block_info); +} + +const PPP_ContentDecryptor_Private ppp_content_decryptor = { + &GenerateKeyRequest, + &AddKey, + &CancelKeyRequest, + &Decrypt, + &InitializeAudioDecoder, + &InitializeVideoDecoder, + &DeinitializeDecoder, + &ResetDecoder, + &DecryptAndDecode +}; + +template <> const char* interface_name<PPB_ContentDecryptor_Private>() { + return PPB_CONTENTDECRYPTOR_PRIVATE_INTERFACE; +} + +} // namespace + +ContentDecryptor_Private::ContentDecryptor_Private(Instance* instance) + : associated_instance_(instance) { + Module::Get()->AddPluginInterface(kPPPContentDecryptorInterface, + &ppp_content_decryptor); + instance->AddPerInstanceObject(kPPPContentDecryptorInterface, this); +} + +ContentDecryptor_Private::~ContentDecryptor_Private() { + Instance::RemovePerInstanceObject(associated_instance_, + kPPPContentDecryptorInterface, + this); +} + +void ContentDecryptor_Private::NeedKey(const std::string& key_system, + const std::string& session_id, + pp::VarArrayBuffer init_data) { + // session_id can be empty here. + if (has_interface<PPB_ContentDecryptor_Private>()) { + pp::Var key_system_var(key_system); + pp::Var session_id_var(session_id); + + get_interface<PPB_ContentDecryptor_Private>()->NeedKey( + associated_instance_.pp_instance(), + key_system_var.pp_var(), + session_id_var.pp_var(), + init_data.pp_var()); + } +} + +void ContentDecryptor_Private::KeyAdded(const std::string& key_system, + const std::string& session_id) { + if (has_interface<PPB_ContentDecryptor_Private>()) { + pp::Var key_system_var(key_system); + pp::Var session_id_var(session_id); + get_interface<PPB_ContentDecryptor_Private>()->KeyAdded( + associated_instance_.pp_instance(), + key_system_var.pp_var(), + session_id_var.pp_var()); + } +} + +void ContentDecryptor_Private::KeyMessage(const std::string& key_system, + const std::string& session_id, + pp::VarArrayBuffer message, + const std::string& default_url) { + if (has_interface<PPB_ContentDecryptor_Private>()) { + pp::Var key_system_var(key_system); + pp::Var session_id_var(session_id); + pp::Var default_url_var(default_url); + get_interface<PPB_ContentDecryptor_Private>()->KeyMessage( + associated_instance_.pp_instance(), + key_system_var.pp_var(), + session_id_var.pp_var(), + message.pp_var(), + default_url_var.pp_var()); + } +} + +void ContentDecryptor_Private::KeyError(const std::string& key_system, + const std::string& session_id, + int32_t media_error, + int32_t system_code) { + if (has_interface<PPB_ContentDecryptor_Private>()) { + pp::Var key_system_var(key_system); + pp::Var session_id_var(session_id); + get_interface<PPB_ContentDecryptor_Private>()->KeyError( + associated_instance_.pp_instance(), + key_system_var.pp_var(), + session_id_var.pp_var(), + media_error, + system_code); + } +} + +void ContentDecryptor_Private::DeliverBlock( + pp::Buffer_Dev decrypted_block, + const PP_DecryptedBlockInfo& decrypted_block_info) { + if (has_interface<PPB_ContentDecryptor_Private>()) { + get_interface<PPB_ContentDecryptor_Private>()->DeliverBlock( + associated_instance_.pp_instance(), + decrypted_block.pp_resource(), + &decrypted_block_info); + } +} + +void ContentDecryptor_Private::DecoderInitializeDone( + PP_DecryptorStreamType decoder_type, + uint32_t request_id, + bool success) { + if (has_interface<PPB_ContentDecryptor_Private>()) { + get_interface<PPB_ContentDecryptor_Private>()->DecoderInitializeDone( + associated_instance_.pp_instance(), + decoder_type, + request_id, + PP_FromBool(success)); + } +} + +void ContentDecryptor_Private::DecoderDeinitializeDone( + PP_DecryptorStreamType decoder_type, + uint32_t request_id) { + if (has_interface<PPB_ContentDecryptor_Private>()) { + get_interface<PPB_ContentDecryptor_Private>()->DecoderDeinitializeDone( + associated_instance_.pp_instance(), + decoder_type, + request_id); + } +} + +void ContentDecryptor_Private::DecoderResetDone( + PP_DecryptorStreamType decoder_type, + uint32_t request_id) { + if (has_interface<PPB_ContentDecryptor_Private>()) { + get_interface<PPB_ContentDecryptor_Private>()->DecoderResetDone( + associated_instance_.pp_instance(), + decoder_type, + request_id); + } +} + +void ContentDecryptor_Private::DeliverFrame( + pp::Buffer_Dev decrypted_frame, + const PP_DecryptedFrameInfo& decrypted_frame_info) { + if (has_interface<PPB_ContentDecryptor_Private>()) { + get_interface<PPB_ContentDecryptor_Private>()->DeliverFrame( + associated_instance_.pp_instance(), + decrypted_frame.pp_resource(), + &decrypted_frame_info); + } +} + +void ContentDecryptor_Private::DeliverSamples( + pp::Buffer_Dev audio_frames, + const PP_DecryptedBlockInfo& decrypted_block_info) { + if (has_interface<PPB_ContentDecryptor_Private>()) { + get_interface<PPB_ContentDecryptor_Private>()->DeliverSamples( + associated_instance_.pp_instance(), + audio_frames.pp_resource(), + &decrypted_block_info); + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/content_decryptor_private.h b/chromium/ppapi/cpp/private/content_decryptor_private.h new file mode 100644 index 00000000000..477c6de5c25 --- /dev/null +++ b/chromium/ppapi/cpp/private/content_decryptor_private.h @@ -0,0 +1,107 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_CONTENT_DECRYPTOR_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_CONTENT_DECRYPTOR_PRIVATE_H_ + +#include "ppapi/c/private/pp_content_decryptor.h" +#include "ppapi/c/private/ppb_content_decryptor_private.h" +#include "ppapi/c/private/ppp_content_decryptor_private.h" + +#include "ppapi/cpp/dev/buffer_dev.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/var_array_buffer.h" + +namespace pp { + +class Instance; + +// TODO(tomfinegan): Remove redundant pp:: usage, and pass VarArrayBuffers as +// const references. + +class ContentDecryptor_Private { + public: + explicit ContentDecryptor_Private(Instance* instance); + virtual ~ContentDecryptor_Private(); + + // PPP_ContentDecryptor_Private functions exposed as virtual functions + // for you to override. + // TODO(tomfinegan): This could be optimized to pass pp::Var instead of + // strings. The change would allow the CDM wrapper to reuse vars when + // replying to the browser. + virtual void GenerateKeyRequest(const std::string& key_system, + const std::string& type, + pp::VarArrayBuffer init_data) = 0; + virtual void AddKey(const std::string& session_id, + pp::VarArrayBuffer key, + pp::VarArrayBuffer init_data) = 0; + virtual void CancelKeyRequest(const std::string& session_id) = 0; + virtual void Decrypt(pp::Buffer_Dev encrypted_buffer, + const PP_EncryptedBlockInfo& encrypted_block_info) = 0; + virtual void InitializeAudioDecoder( + const PP_AudioDecoderConfig& decoder_config, + pp::Buffer_Dev extra_data_resource) = 0; + virtual void InitializeVideoDecoder( + const PP_VideoDecoderConfig& decoder_config, + pp::Buffer_Dev extra_data_resource) = 0; + virtual void DeinitializeDecoder(PP_DecryptorStreamType decoder_type, + uint32_t request_id) = 0; + virtual void ResetDecoder(PP_DecryptorStreamType decoder_type, + uint32_t request_id) = 0; + // Null |encrypted_frame| means end-of-stream buffer. + virtual void DecryptAndDecode( + PP_DecryptorStreamType decoder_type, + pp::Buffer_Dev encrypted_buffer, + const PP_EncryptedBlockInfo& encrypted_block_info) = 0; + + // PPB_ContentDecryptor_Private methods for passing data from the decryptor + // to the browser. + void NeedKey(const std::string& key_system, + const std::string& session_id, + pp::VarArrayBuffer init_data); + void KeyAdded(const std::string& key_system, + const std::string& session_id); + void KeyMessage(const std::string& key_system, + const std::string& session_id, + pp::VarArrayBuffer message, + const std::string& default_url); + void KeyError(const std::string& key_system, + const std::string& session_id, + int32_t media_error, + int32_t system_code); + + // The plugin must not hold a reference to the encrypted buffer resource + // provided to Decrypt() when it calls this method. The browser will reuse + // the buffer in a subsequent Decrypt() call. + void DeliverBlock(pp::Buffer_Dev decrypted_block, + const PP_DecryptedBlockInfo& decrypted_block_info); + + void DecoderInitializeDone(PP_DecryptorStreamType decoder_type, + uint32_t request_id, + bool status); + void DecoderDeinitializeDone(PP_DecryptorStreamType decoder_type, + uint32_t request_id); + void DecoderResetDone(PP_DecryptorStreamType decoder_type, + uint32_t request_id); + + // The plugin must not hold a reference to the encrypted buffer resource + // provided to DecryptAndDecode() when it calls this method. The browser will + // reuse the buffer in a subsequent DecryptAndDecode() call. + void DeliverFrame(pp::Buffer_Dev decrypted_frame, + const PP_DecryptedFrameInfo& decrypted_frame_info); + + // The plugin must not hold a reference to the encrypted buffer resource + // provided to DecryptAndDecode() when it calls this method. The browser will + // reuse the buffer in a subsequent DecryptAndDecode() call. + void DeliverSamples(pp::Buffer_Dev audio_frames, + const PP_DecryptedBlockInfo& decrypted_block_info); + + private: + InstanceHandle associated_instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_CONTENT_DECRYPTOR_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/ext_crx_file_system_private.cc b/chromium/ppapi/cpp/private/ext_crx_file_system_private.cc new file mode 100644 index 00000000000..87752b94d0b --- /dev/null +++ b/chromium/ppapi/cpp/private/ext_crx_file_system_private.cc @@ -0,0 +1,38 @@ +// Copyright (c) 2013 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 "ppapi/cpp/private/ext_crx_file_system_private.h" + +#include "ppapi/c/private/ppb_ext_crx_file_system_private.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Ext_CrxFileSystem_Private_0_1>() { + return PPB_EXT_CRXFILESYSTEM_PRIVATE_INTERFACE_0_1; +} + +} // namespace + +ExtCrxFileSystemPrivate::ExtCrxFileSystemPrivate() { +} + +ExtCrxFileSystemPrivate::ExtCrxFileSystemPrivate( + const InstanceHandle& instance) : instance_(instance.pp_instance()) { +} + +ExtCrxFileSystemPrivate::~ExtCrxFileSystemPrivate() { +} + +int32_t ExtCrxFileSystemPrivate::Open( + const CompletionCallbackWithOutput<pp::FileSystem>& cc) { + if (!has_interface<PPB_Ext_CrxFileSystem_Private_0_1>()) + return cc.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_Ext_CrxFileSystem_Private_0_1>()-> + Open(instance_, cc.output(), cc.pp_completion_callback()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/ext_crx_file_system_private.h b/chromium/ppapi/cpp/private/ext_crx_file_system_private.h new file mode 100644 index 00000000000..e307f91f0e8 --- /dev/null +++ b/chromium/ppapi/cpp/private/ext_crx_file_system_private.h @@ -0,0 +1,31 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_PRIVATE_EXTENSION_CRX_FILE_SYSTEM_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_EXTENSION_CRX_FILE_SYSTEM_PRIVATE_H_ + +#include "ppapi/c/pp_instance.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/file_system.h" +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +class CompletionCallback; + +class ExtCrxFileSystemPrivate { + public: + ExtCrxFileSystemPrivate(); + explicit ExtCrxFileSystemPrivate(const InstanceHandle& instance); + virtual ~ExtCrxFileSystemPrivate(); + + int32_t Open(const CompletionCallbackWithOutput<pp::FileSystem>& cc); + + private: + PP_Instance instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_EXTENSION_CRX_FILE_SYSTEM_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/file_io_private.cc b/chromium/ppapi/cpp/private/file_io_private.cc new file mode 100644 index 00000000000..b0f5a00f075 --- /dev/null +++ b/chromium/ppapi/cpp/private/file_io_private.cc @@ -0,0 +1,40 @@ +// Copyright (c) 2013 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 "ppapi/cpp/private/file_io_private.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/private/ppb_file_io_private.h" +#include "ppapi/cpp/file_io.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_FileIO_Private>() { + return PPB_FILEIO_PRIVATE_INTERFACE_0_1; +} + +} // namespace + +FileIO_Private::FileIO_Private() + : FileIO() { +} + +FileIO_Private::FileIO_Private(const InstanceHandle& instance) + : FileIO(instance) { +} + +int32_t FileIO_Private::RequestOSFileHandle( + const CompletionCallbackWithOutput<PassFileHandle>& cc) { + if (has_interface<PPB_FileIO_Private>()) + return get_interface<PPB_FileIO_Private>()->RequestOSFileHandle( + pp_resource(), + cc.output(), + cc.pp_completion_callback()); + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/file_io_private.h b/chromium/ppapi/cpp/private/file_io_private.h new file mode 100644 index 00000000000..6f0d06d454a --- /dev/null +++ b/chromium/ppapi/cpp/private/file_io_private.h @@ -0,0 +1,29 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_PRIVATE_FILE_IO_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_FILE_IO_PRIVATE_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/private/pp_file_handle.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/file_io.h" +#include "ppapi/cpp/private/pass_file_handle.h" + +namespace pp { + +class FileIO; + +class FileIO_Private : public FileIO { + public: + FileIO_Private(); + explicit FileIO_Private(const InstanceHandle& instance); + + int32_t RequestOSFileHandle( + const CompletionCallbackWithOutput<PassFileHandle>& cc); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FILE_IO_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/flash.cc b/chromium/ppapi/cpp/private/flash.cc new file mode 100644 index 00000000000..757dbecbdbd --- /dev/null +++ b/chromium/ppapi/cpp/private/flash.cc @@ -0,0 +1,308 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/flash.h" + +#include <string.h> + +#include "ppapi/c/pp_bool.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/dev/device_ref_dev.h" +#include "ppapi/cpp/dev/video_capture_dev.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/rect.h" +#include "ppapi/cpp/trusted/browser_font_trusted.h" +#include "ppapi/cpp/url_request_info.h" +#include "ppapi/cpp/var.h" +#include "ppapi/c/private/ppb_flash.h" +#include "ppapi/c/private/ppb_flash_print.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Flash_13_0>() { + return PPB_FLASH_INTERFACE_13_0; +} + +template <> const char* interface_name<PPB_Flash_12_6>() { + return PPB_FLASH_INTERFACE_12_6; +} + +template <> const char* interface_name<PPB_Flash_12_5>() { + return PPB_FLASH_INTERFACE_12_5; +} + +template <> const char* interface_name<PPB_Flash_12_4>() { + return PPB_FLASH_INTERFACE_12_4; +} + +template <> const char* interface_name<PPB_Flash_Print_1_0>() { + return PPB_FLASH_PRINT_INTERFACE_1_0; +} + +// The combined Flash interface is all Flash v12.* interfaces. All v12 +// interfaces just append one or more functions to the previous one, so we can +// have this meta one at the most recent version. Function pointers will be +// null if they're not supported on the current Chrome version. +bool initialized_combined_interface = false; +PPB_Flash_12_6 flash_12_combined_interface; + +// Makes sure that the most recent version is loaded into the combined +// interface struct above. Any unsupported functions will be NULL. If there +// is no Flash interface supported, all functions will be NULL. +void InitializeCombinedInterface() { + if (initialized_combined_interface) + return; + if (has_interface<PPB_Flash_12_6>()) { + memcpy(&flash_12_combined_interface, get_interface<PPB_Flash_12_6>(), + sizeof(PPB_Flash_12_6)); + } else if (has_interface<PPB_Flash_12_5>()) { + memcpy(&flash_12_combined_interface, get_interface<PPB_Flash_12_5>(), + sizeof(PPB_Flash_12_5)); + } else if (has_interface<PPB_Flash_12_4>()) { + memcpy(&flash_12_combined_interface, get_interface<PPB_Flash_12_4>(), + sizeof(PPB_Flash_12_4)); + } + initialized_combined_interface = true; +} + +} // namespace + +namespace flash { + +// static +bool Flash::IsAvailable() { + return has_interface<PPB_Flash_13_0>() || + has_interface<PPB_Flash_12_6>() || + has_interface<PPB_Flash_12_5>() || + has_interface<PPB_Flash_12_4>(); +} + +// static +void Flash::SetInstanceAlwaysOnTop(const InstanceHandle& instance, + bool on_top) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + get_interface<PPB_Flash_13_0>()->SetInstanceAlwaysOnTop( + instance.pp_instance(), PP_FromBool(on_top)); + } else if (flash_12_combined_interface.SetInstanceAlwaysOnTop) { + flash_12_combined_interface.SetInstanceAlwaysOnTop( + instance.pp_instance(), PP_FromBool(on_top)); + } +} + +// static +bool Flash::DrawGlyphs(const InstanceHandle& instance, + ImageData* image, + const BrowserFontDescription& font_desc, + uint32_t color, + const Point& position, + const Rect& clip, + const float transformation[3][3], + bool allow_subpixel_aa, + uint32_t glyph_count, + const uint16_t glyph_indices[], + const PP_Point glyph_advances[]) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + return PP_ToBool(get_interface<PPB_Flash_13_0>()->DrawGlyphs( + instance.pp_instance(), + image->pp_resource(), + &font_desc.pp_font_description(), + color, + &position.pp_point(), + &clip.pp_rect(), + transformation, + PP_FromBool(allow_subpixel_aa), + glyph_count, + glyph_indices, + glyph_advances)); + } + if (flash_12_combined_interface.DrawGlyphs) { + return PP_ToBool(flash_12_combined_interface.DrawGlyphs( + instance.pp_instance(), + image->pp_resource(), + &font_desc.pp_font_description(), + color, + &position.pp_point(), + &clip.pp_rect(), + transformation, + PP_FromBool(allow_subpixel_aa), + glyph_count, + glyph_indices, + glyph_advances)); + } + return false; +} + +// static +Var Flash::GetProxyForURL(const InstanceHandle& instance, + const std::string& url) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + return Var(PASS_REF, get_interface<PPB_Flash_13_0>()->GetProxyForURL( + instance.pp_instance(), url.c_str())); + } + if (flash_12_combined_interface.GetProxyForURL) { + return Var(PASS_REF, flash_12_combined_interface.GetProxyForURL( + instance.pp_instance(), url.c_str())); + } + return Var(); +} + +// static +int32_t Flash::Navigate(const URLRequestInfo& request_info, + const std::string& target, + bool from_user_action) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + return get_interface<PPB_Flash_13_0>()->Navigate( + request_info.pp_resource(), + target.c_str(), + PP_FromBool(from_user_action)); + } + if (flash_12_combined_interface.Navigate) { + return flash_12_combined_interface.Navigate( + request_info.pp_resource(), + target.c_str(), + PP_FromBool(from_user_action)); + } + return PP_ERROR_FAILED; +} + +// static +double Flash::GetLocalTimeZoneOffset(const InstanceHandle& instance, + PP_Time t) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + return get_interface<PPB_Flash_13_0>()->GetLocalTimeZoneOffset( + instance.pp_instance(), t); + } + if (flash_12_combined_interface.GetLocalTimeZoneOffset) { + return flash_12_combined_interface.GetLocalTimeZoneOffset( + instance.pp_instance(), t); + } + return 0.0; +} + +// static +Var Flash::GetCommandLineArgs(Module* module) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + return Var(PASS_REF, get_interface<PPB_Flash_13_0>()->GetCommandLineArgs( + module->pp_module())); + } + if (flash_12_combined_interface.GetCommandLineArgs) { + return Var( + PASS_REF, + flash_12_combined_interface.GetCommandLineArgs(module->pp_module())); + } + return Var(); +} + +// static +void Flash::PreloadFontWin(const void* logfontw) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) + return get_interface<PPB_Flash_13_0>()->PreloadFontWin(logfontw); + if (flash_12_combined_interface.PreloadFontWin) + return flash_12_combined_interface.PreloadFontWin(logfontw); +} + +// static +bool Flash::IsRectTopmost(const InstanceHandle& instance, const Rect& rect) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + return PP_ToBool(get_interface<PPB_Flash_13_0>()->IsRectTopmost( + instance.pp_instance(), &rect.pp_rect())); + } + if (flash_12_combined_interface.IsRectTopmost) { + return PP_ToBool(flash_12_combined_interface.IsRectTopmost( + instance.pp_instance(), &rect.pp_rect())); + } + return false; +} + +// static +void Flash::UpdateActivity(const InstanceHandle& instance) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) + get_interface<PPB_Flash_13_0>()->UpdateActivity(instance.pp_instance()); + else if (flash_12_combined_interface.UpdateActivity) + flash_12_combined_interface.UpdateActivity(instance.pp_instance()); +} + +// static +Var Flash::GetSetting(const InstanceHandle& instance, PP_FlashSetting setting) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + return Var(PASS_REF, get_interface<PPB_Flash_13_0>()->GetSetting( + instance.pp_instance(), setting)); + } + if (flash_12_combined_interface.GetSetting) { + return Var(PASS_REF, + flash_12_combined_interface.GetSetting(instance.pp_instance(), + setting)); + } + + return Var(); +} + +// static +bool Flash::SetCrashData(const InstanceHandle& instance, + PP_FlashCrashKey key, + const pp::Var& value) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + return PP_ToBool(get_interface<PPB_Flash_13_0>()->SetCrashData( + instance.pp_instance(), key, value.pp_var())); + } + if (flash_12_combined_interface.SetCrashData) { + return PP_ToBool( + flash_12_combined_interface.SetCrashData(instance.pp_instance(), + key, value.pp_var())); + } + return false; +} + +// static +int32_t Flash::EnumerateVideoCaptureDevices( + const InstanceHandle& instance, + const VideoCapture_Dev& video_capture, + std::vector<DeviceRef_Dev>* devices_out) { + InitializeCombinedInterface(); + if (has_interface<PPB_Flash_13_0>()) { + ResourceArrayOutputAdapter<DeviceRef_Dev> adapter(devices_out); + return get_interface<PPB_Flash_13_0>()->EnumerateVideoCaptureDevices( + instance.pp_instance(), + video_capture.pp_resource(), + adapter.pp_array_output()); + } + if (flash_12_combined_interface.EnumerateVideoCaptureDevices) { + ResourceArrayOutputAdapter<DeviceRef_Dev> adapter(devices_out); + return flash_12_combined_interface.EnumerateVideoCaptureDevices( + instance.pp_instance(), + video_capture.pp_resource(), + adapter.pp_array_output()); + } + return PP_ERROR_FAILED; +} + +// static +bool Flash::InvokePrinting(const InstanceHandle& instance) { + if (has_interface<PPB_Flash_Print_1_0>()) { + get_interface<PPB_Flash_Print_1_0>()->InvokePrinting( + instance.pp_instance()); + return true; + } + return false; +} + +} // namespace flash +} // namespace pp diff --git a/chromium/ppapi/cpp/private/flash.h b/chromium/ppapi/cpp/private/flash.h new file mode 100644 index 00000000000..6a6b7c311aa --- /dev/null +++ b/chromium/ppapi/cpp/private/flash.h @@ -0,0 +1,80 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_FLASH_H_ +#define PPAPI_CPP_PRIVATE_FLASH_H_ + +#include <string> +#include <vector> + +#include "ppapi/c/private/ppb_flash.h" +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/pp_time.h" + +struct PP_Point; + +namespace pp { + +class BrowserFontDescription; +class DeviceRef_Dev; +class ImageData; +class InstanceHandle; +class Module; +class Point; +class Rect; +class URLRequestInfo; +class Var; +class VideoCapture_Dev; + +namespace flash { + +class Flash { + public: + // Returns true if the required interface is available. + static bool IsAvailable(); + + static void SetInstanceAlwaysOnTop(const InstanceHandle& instance, + bool on_top); + static bool DrawGlyphs(const InstanceHandle& instance, + ImageData* image, + const BrowserFontDescription& font_desc, + uint32_t color, + const Point& position, + const Rect& clip, + const float transformation[3][3], + bool allow_subpixel_aa, + uint32_t glyph_count, + const uint16_t glyph_indices[], + const PP_Point glyph_advances[]); + static Var GetProxyForURL(const InstanceHandle& instance, + const std::string& url); + static int32_t Navigate(const URLRequestInfo& request_info, + const std::string& target, + bool from_user_action); + static void RunMessageLoop(const InstanceHandle& instance); + static void QuitMessageLoop(const InstanceHandle& instance); + static double GetLocalTimeZoneOffset(const InstanceHandle& instance, + PP_Time t); + static Var GetCommandLineArgs(Module* module); + static void PreloadFontWin(const void* logfontw); + static bool IsRectTopmost(const InstanceHandle& instance, const Rect& rect); + static void UpdateActivity(const InstanceHandle& instance); + static Var GetDeviceID(const InstanceHandle& instance); + static Var GetSetting(const InstanceHandle& instance, + PP_FlashSetting setting); + static bool SetCrashData(const InstanceHandle& instance, + PP_FlashCrashKey key, + const pp::Var& value); + static int32_t EnumerateVideoCaptureDevices(const InstanceHandle& instance, + const VideoCapture_Dev& video_capture, + std::vector<DeviceRef_Dev>* devices_out); + + // PPB_Flash_Print. + static bool InvokePrinting(const InstanceHandle& instance); +}; + +} // namespace flash +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FLASH_H_ diff --git a/chromium/ppapi/cpp/private/flash_clipboard.cc b/chromium/ppapi/cpp/private/flash_clipboard.cc new file mode 100644 index 00000000000..c63f747bcc0 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_clipboard.cc @@ -0,0 +1,152 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/flash_clipboard.h" + +#include <vector> + +#include "ppapi/c/pp_bool.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Flash_Clipboard_4_0>() { + return PPB_FLASH_CLIPBOARD_INTERFACE_4_0; +} + +template <> const char* interface_name<PPB_Flash_Clipboard_5_0>() { + return PPB_FLASH_CLIPBOARD_INTERFACE_5_0; +} + +} // namespace + +namespace flash { + +// static +bool Clipboard::IsAvailable() { + return has_interface<PPB_Flash_Clipboard_5_0>() || + has_interface<PPB_Flash_Clipboard_4_0>() ; +} + +// static +uint32_t Clipboard::RegisterCustomFormat(const InstanceHandle& instance, + const std::string& format_name) { + uint32_t rv = PP_FLASH_CLIPBOARD_FORMAT_INVALID; + if (has_interface<PPB_Flash_Clipboard_5_0>()) { + rv = get_interface<PPB_Flash_Clipboard_5_0>()->RegisterCustomFormat( + instance.pp_instance(), format_name.c_str()); + } + return rv; +} + +// static +bool Clipboard::IsFormatAvailable(const InstanceHandle& instance, + PP_Flash_Clipboard_Type clipboard_type, + uint32_t format) { + bool rv = false; + if (has_interface<PPB_Flash_Clipboard_5_0>()) { + rv = PP_ToBool(get_interface<PPB_Flash_Clipboard_5_0>()->IsFormatAvailable( + instance.pp_instance(), clipboard_type, format)); + } else if (has_interface<PPB_Flash_Clipboard_4_0>()) { + rv = PP_ToBool(get_interface<PPB_Flash_Clipboard_4_0>()->IsFormatAvailable( + instance.pp_instance(), clipboard_type, + static_cast<PP_Flash_Clipboard_Format>(format))); + } + return rv; +} + +// static +bool Clipboard::ReadData( + const InstanceHandle& instance, + PP_Flash_Clipboard_Type clipboard_type, + uint32_t format, + Var* out) { + bool rv = false; + if (has_interface<PPB_Flash_Clipboard_5_0>()) { + PP_Var result = get_interface<PPB_Flash_Clipboard_5_0>()->ReadData( + instance.pp_instance(), + clipboard_type, + format); + *out = Var(PASS_REF, result); + rv = true; + } else if (has_interface<PPB_Flash_Clipboard_4_0>()) { + PP_Var result = get_interface<PPB_Flash_Clipboard_4_0>()->ReadData( + instance.pp_instance(), + clipboard_type, + static_cast<PP_Flash_Clipboard_Format>(format)); + *out = Var(PASS_REF, result); + rv = true; + } + return rv; +} + +// static +bool Clipboard::WriteData( + const InstanceHandle& instance, + PP_Flash_Clipboard_Type clipboard_type, + const std::vector<uint32_t>& formats, + const std::vector<Var>& data_items) { + if (formats.size() != data_items.size()) + return false; + + bool rv = false; + if (has_interface<PPB_Flash_Clipboard_5_0>()) { + // Convert vector of pp::Var into a vector of PP_Var. + std::vector<PP_Var> data_items_vector; + for (uint32_t i = 0; i < data_items.size(); ++i) + data_items_vector.push_back(data_items[i].pp_var()); + + // Ensure that we don't dereference the memory in empty vectors. We still + // want to call WriteData because it has the effect of clearing the + // clipboard. + const uint32_t* formats_ptr(NULL); + const PP_Var* data_items_ptr(NULL); + if (data_items.size() > 0) { + formats_ptr = &formats[0]; + data_items_ptr = &data_items_vector[0]; + } + + rv = (get_interface<PPB_Flash_Clipboard_5_0>()->WriteData( + instance.pp_instance(), + clipboard_type, + data_items.size(), + formats_ptr, + data_items_ptr) == PP_OK); + } else if (has_interface<PPB_Flash_Clipboard_4_0>()) { + // Convert vector of pp::Var into a vector of PP_Var. + std::vector<PP_Var> data_items_vector; + std::vector<PP_Flash_Clipboard_Format> old_formats; + for (uint32_t i = 0; i < data_items.size(); ++i) { + data_items_vector.push_back(data_items[i].pp_var()); + old_formats.push_back(static_cast<PP_Flash_Clipboard_Format>(formats[i])); + } + + // Ensure that we don't dereference the memory in empty vectors. We still + // want to call WriteData because it has the effect of clearing the + // clipboard. + const PP_Flash_Clipboard_Format* formats_ptr(NULL); + const PP_Var* data_items_ptr(NULL); + if (data_items.size() > 0) { + formats_ptr = &old_formats[0]; + data_items_ptr = &data_items_vector[0]; + } + + rv = (get_interface<PPB_Flash_Clipboard_4_0>()->WriteData( + instance.pp_instance(), + clipboard_type, + data_items.size(), + formats_ptr, + data_items_ptr) == PP_OK); + } + + return rv; +} + +} // namespace flash +} // namespace pp diff --git a/chromium/ppapi/cpp/private/flash_clipboard.h b/chromium/ppapi/cpp/private/flash_clipboard.h new file mode 100644 index 00000000000..aab06efb1e9 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_clipboard.h @@ -0,0 +1,53 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_FLASH_CLIPBOARD_H_ +#define PPAPI_CPP_PRIVATE_FLASH_CLIPBOARD_H_ + +#include <string> +#include <vector> + +#include "ppapi/c/private/ppb_flash_clipboard.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +class InstanceHandle; + +namespace flash { + +class Clipboard { + public: + // Returns true if the required interface is available. + static bool IsAvailable(); + + // Returns a format ID on success or PP_FLASH_CLIPBOARD_FORMAT_INVALID on + // failure. + static uint32_t RegisterCustomFormat(const InstanceHandle& instance, + const std::string& format_name); + + // Returns true if the given format is available from the given clipboard. + static bool IsFormatAvailable(const InstanceHandle& instance, + PP_Flash_Clipboard_Type clipboard_type, + uint32_t format); + + // Returns true on success, in which case |out| will be filled with + // data read from the given clipboard in the given format. + static bool ReadData(const InstanceHandle& instance, + PP_Flash_Clipboard_Type clipboard_type, + uint32_t clipboard_format, + Var* out); + + // Returns true on success in which case all of |data| will be written to + // the clipboard. Otherwise nothing will be written. + static bool WriteData(const InstanceHandle& instance, + PP_Flash_Clipboard_Type clipboard_type, + const std::vector<uint32_t>& formats, + const std::vector<Var>& data_items); +}; + +} // namespace flash +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FLASH_CLIPBOARD_H_ diff --git a/chromium/ppapi/cpp/private/flash_device_id.cc b/chromium/ppapi/cpp/private/flash_device_id.cc new file mode 100644 index 00000000000..6ed893573ec --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_device_id.cc @@ -0,0 +1,45 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/flash_device_id.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/private/ppb_flash_device_id.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Flash_DeviceID_1_0>() { + return PPB_FLASH_DEVICEID_INTERFACE_1_0; +} + +} // namespace + +namespace flash { + +DeviceID::DeviceID() { +} + +DeviceID::DeviceID(const InstanceHandle& instance) : Resource() { + if (has_interface<PPB_Flash_DeviceID_1_0>()) { + PassRefFromConstructor(get_interface<PPB_Flash_DeviceID_1_0>()->Create( + instance.pp_instance())); + } +} + +int32_t DeviceID::GetDeviceID( + const CompletionCallbackWithOutput<Var>& callback) { + if (has_interface<PPB_Flash_DeviceID_1_0>()) { + return get_interface<PPB_Flash_DeviceID_1_0>()->GetDeviceID( + pp_resource(), + callback.output(), + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +} // namespace flash +} // namespace pp diff --git a/chromium/ppapi/cpp/private/flash_device_id.h b/chromium/ppapi/cpp/private/flash_device_id.h new file mode 100644 index 00000000000..33c5e55652f --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_device_id.h @@ -0,0 +1,26 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_FLASH_DEVICE_ID_H_ +#define PPAPI_CPP_PRIVATE_FLASH_DEVICE_ID_H_ + +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/resource.h" + +namespace pp { +namespace flash { + +class DeviceID : public Resource { + public: + DeviceID(); + DeviceID(const InstanceHandle& instance); + + // On success, returns a string var. + int32_t GetDeviceID(const CompletionCallbackWithOutput<Var>& callback); +}; + +} // namespace flash +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FLASH_DEVICE_ID_H_ diff --git a/chromium/ppapi/cpp/private/flash_drm.cc b/chromium/ppapi/cpp/private/flash_drm.cc new file mode 100644 index 00000000000..44887abc207 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_drm.cc @@ -0,0 +1,78 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/flash_drm.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/private/ppb_flash_device_id.h" +#include "ppapi/c/private/ppb_flash_drm.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Flash_DRM_1_0>() { + return PPB_FLASH_DRM_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_Flash_DeviceID_1_0>() { + return PPB_FLASH_DEVICEID_INTERFACE_1_0; +} + +} // namespace + +namespace flash { + +DRM::DRM() { +} + +DRM::DRM(const InstanceHandle& instance) : Resource() { + if (has_interface<PPB_Flash_DRM_1_0>()) { + PassRefFromConstructor(get_interface<PPB_Flash_DRM_1_0>()->Create( + instance.pp_instance())); + } else if (has_interface<PPB_Flash_DeviceID_1_0>()) { + PassRefFromConstructor(get_interface<PPB_Flash_DeviceID_1_0>()->Create( + instance.pp_instance())); + } +} + +int32_t DRM::GetDeviceID(const CompletionCallbackWithOutput<Var>& callback) { + if (has_interface<PPB_Flash_DRM_1_0>()) { + return get_interface<PPB_Flash_DRM_1_0>()->GetDeviceID( + pp_resource(), + callback.output(), + callback.pp_completion_callback()); + } + if (has_interface<PPB_Flash_DeviceID_1_0>()) { + return get_interface<PPB_Flash_DeviceID_1_0>()->GetDeviceID( + pp_resource(), + callback.output(), + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +bool DRM::GetHmonitor(int64_t* hmonitor) { + if (has_interface<PPB_Flash_DRM_1_0>()) { + return PP_ToBool(get_interface<PPB_Flash_DRM_1_0>()->GetHmonitor( + pp_resource(), + hmonitor)); + } + return 0; +} + +int32_t DRM::GetVoucherFile( + const CompletionCallbackWithOutput<FileRef>& callback) { + if (has_interface<PPB_Flash_DRM_1_0>()) { + return get_interface<PPB_Flash_DRM_1_0>()->GetVoucherFile( + pp_resource(), + callback.output(), + callback.pp_completion_callback()); + } + return PP_ERROR_FAILED; +} + +} // namespace flash +} // namespace pp diff --git a/chromium/ppapi/cpp/private/flash_drm.h b/chromium/ppapi/cpp/private/flash_drm.h new file mode 100644 index 00000000000..45ecde8b9a4 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_drm.h @@ -0,0 +1,35 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_FLASH_DRM_H_ +#define PPAPI_CPP_PRIVATE_FLASH_DRM_H_ + +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class FileRef; + +namespace flash { + +class DRM : public Resource { + public: + DRM(); + explicit DRM(const InstanceHandle& instance); + + // On success, returns a string var. + int32_t GetDeviceID(const CompletionCallbackWithOutput<Var>& callback); + // Outputs the HMONITOR associated with the current plugin instance in + // |hmonitor|. True is returned upon success. + bool GetHmonitor(int64_t* hmonitor); + // Returns the voucher file as a FileRef or an invalid resource on failure. + int32_t GetVoucherFile(const CompletionCallbackWithOutput<FileRef>& callback); +}; + +} // namespace flash +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FLASH_DRM_H_ diff --git a/chromium/ppapi/cpp/private/flash_file.cc b/chromium/ppapi/cpp/private/flash_file.cc new file mode 100644 index 00000000000..7004b985b1a --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_file.cc @@ -0,0 +1,178 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/flash_file.h" + +#include "ppapi/c/pp_bool.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +// FileModuleLocal ------------------------------------------------------------- + +namespace { + +template <> const char* interface_name<PPB_Flash_File_ModuleLocal_3_0>() { + return PPB_FLASH_FILE_MODULELOCAL_INTERFACE_3_0; +} + +} // namespace + +namespace flash { + +static FileModuleLocal::DirEntry ConvertDirEntry(const PP_DirEntry_Dev& entry) { + FileModuleLocal::DirEntry rv = { entry.name, PP_ToBool(entry.is_dir) }; + return rv; +} + +// static +bool FileModuleLocal::IsAvailable() { + return has_interface<PPB_Flash_File_ModuleLocal_3_0>(); +} + +// static +PP_FileHandle FileModuleLocal::OpenFile(const InstanceHandle& instance, + const std::string& path, + int32_t mode) { + PP_FileHandle file_handle = PP_kInvalidFileHandle; + int32_t result = PP_ERROR_FAILED; + if (has_interface<PPB_Flash_File_ModuleLocal_3_0>()) { + result = get_interface<PPB_Flash_File_ModuleLocal_3_0>()-> + OpenFile(instance.pp_instance(), path.c_str(), mode, &file_handle); + } + return (result == PP_OK) ? file_handle : PP_kInvalidFileHandle; +} + +// static +bool FileModuleLocal::RenameFile(const InstanceHandle& instance, + const std::string& path_from, + const std::string& path_to) { + int32_t result = PP_ERROR_FAILED; + if (has_interface<PPB_Flash_File_ModuleLocal_3_0>()) { + result = get_interface<PPB_Flash_File_ModuleLocal_3_0>()-> + RenameFile(instance.pp_instance(), path_from.c_str(), path_to.c_str()); + } + return result == PP_OK; +} + +// static +bool FileModuleLocal::DeleteFileOrDir(const InstanceHandle& instance, + const std::string& path, + bool recursive) { + int32_t result = PP_ERROR_FAILED; + if (has_interface<PPB_Flash_File_ModuleLocal_3_0>()) { + result = get_interface<PPB_Flash_File_ModuleLocal_3_0>()-> + DeleteFileOrDir(instance.pp_instance(), path.c_str(), + PP_FromBool(recursive)); + } + return result == PP_OK; +} + +// static +bool FileModuleLocal::CreateDir(const InstanceHandle& instance, + const std::string& path) { + int32_t result = PP_ERROR_FAILED; + if (has_interface<PPB_Flash_File_ModuleLocal_3_0>()) { + result = get_interface<PPB_Flash_File_ModuleLocal_3_0>()-> + CreateDir(instance.pp_instance(), path.c_str()); + } + return result == PP_OK; +} + +// static +bool FileModuleLocal::QueryFile(const InstanceHandle& instance, + const std::string& path, + PP_FileInfo* info) { + int32_t result = PP_ERROR_FAILED; + if (has_interface<PPB_Flash_File_ModuleLocal_3_0>()) { + result = get_interface<PPB_Flash_File_ModuleLocal_3_0>()-> + QueryFile(instance.pp_instance(), path.c_str(), info); + } + return result == PP_OK; +} + +// static +bool FileModuleLocal::GetDirContents( + const InstanceHandle& instance, + const std::string& path, + std::vector<DirEntry>* dir_contents) { + dir_contents->clear(); + + int32_t result = PP_ERROR_FAILED; + if (has_interface<PPB_Flash_File_ModuleLocal_3_0>()) { + PP_DirContents_Dev* contents = NULL; + result = get_interface<PPB_Flash_File_ModuleLocal_3_0>()-> + GetDirContents(instance.pp_instance(), path.c_str(), &contents); + if (result == PP_OK && contents) { + for (int32_t i = 0; i < contents->count; i++) + dir_contents->push_back(ConvertDirEntry(contents->entries[i])); + } + if (contents) { + get_interface<PPB_Flash_File_ModuleLocal_3_0>()-> + FreeDirContents(instance.pp_instance(), contents); + } + } + return result == PP_OK; +} + +// static +PP_FileHandle FileModuleLocal::CreateTemporaryFile( + const InstanceHandle& instance) { + PP_FileHandle file_handle = PP_kInvalidFileHandle; + int32_t result = PP_ERROR_FAILED; + if (has_interface<PPB_Flash_File_ModuleLocal_3_0>()) { + result = get_interface<PPB_Flash_File_ModuleLocal_3_0>()-> + CreateTemporaryFile(instance.pp_instance(), &file_handle); + } + return (result == PP_OK) ? file_handle : PP_kInvalidFileHandle; +} + +} // namespace flash + +// FileFileRef ----------------------------------------------------------------- + +namespace { + +template <> const char* interface_name<PPB_Flash_File_FileRef>() { + return PPB_FLASH_FILE_FILEREF_INTERFACE; +} + +} // namespace + +namespace flash { + +// static +bool FileFileRef::IsAvailable() { + return has_interface<PPB_Flash_File_FileRef>(); +} + +// static +PP_FileHandle FileFileRef::OpenFile(const pp::FileRef& resource, + int32_t mode) { + PP_FileHandle file_handle = PP_kInvalidFileHandle; + int32_t result = PP_ERROR_FAILED; + if (has_interface<PPB_Flash_File_FileRef>()) { + result = get_interface<PPB_Flash_File_FileRef>()-> + OpenFile(resource.pp_resource(), mode, &file_handle); + } + return (result == PP_OK) ? file_handle : PP_kInvalidFileHandle; +} + +// static +bool FileFileRef::QueryFile(const pp::FileRef& resource, + PP_FileInfo* info) { + int32_t result = PP_ERROR_FAILED; + if (has_interface<PPB_Flash_File_FileRef>()) { + result = get_interface<PPB_Flash_File_FileRef>()-> + QueryFile(resource.pp_resource(), info); + } + return result == PP_OK; +} + +} // namespace flash + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/flash_file.h b/chromium/ppapi/cpp/private/flash_file.h new file mode 100644 index 00000000000..04ab195eeb3 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_file.h @@ -0,0 +1,72 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_FLASH_FILE_H_ +#define PPAPI_CPP_PRIVATE_FLASH_FILE_H_ + +#include <string> +#include <vector> + +#include "ppapi/c/private/ppb_flash_file.h" + +namespace pp { + +class FileRef; +class InstanceHandle; + +namespace flash { + +// FileModuleLocal ------------------------------------------------------------- + +class FileModuleLocal { + public: + // Returns true if the required interface is available. + static bool IsAvailable(); + + // Returns |PP_kInvalidFileHandle| on error. + static PP_FileHandle OpenFile(const InstanceHandle& instance, + const std::string& path, + int32_t mode); + static bool RenameFile(const InstanceHandle& instance, + const std::string& path_from, + const std::string& path_to); + static bool DeleteFileOrDir(const InstanceHandle& instance, + const std::string& path, + bool recursive); + static bool CreateDir(const InstanceHandle& instance, + const std::string& path); + static bool QueryFile(const InstanceHandle& instance, + const std::string& path, + PP_FileInfo* info); + // Note that, unlike the C interface, no |FreeDirContents()| is needed. + struct DirEntry { + std::string name; + bool is_dir; + }; + static bool GetDirContents(const InstanceHandle& instance, + const std::string& path, + std::vector<DirEntry>* dir_contents); + + // Returns |PP_kInvalidFileHandle| on error. + static PP_FileHandle CreateTemporaryFile(const InstanceHandle& instance); +}; + +// FileFileRef ----------------------------------------------------------------- + +class FileFileRef { + public: + // Returns true if the required interface is available. + static bool IsAvailable(); + + // Returns |PP_kInvalidFileHandle| on error. + static PP_FileHandle OpenFile(const pp::FileRef& resource, + int32_t mode); + static bool QueryFile(const pp::FileRef& resource, + PP_FileInfo* info); +}; + +} // namespace flash +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FLASH_FILE_H_ diff --git a/chromium/ppapi/cpp/private/flash_font_file.cc b/chromium/ppapi/cpp/private/flash_font_file.cc new file mode 100644 index 00000000000..df11f57d741 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_font_file.cc @@ -0,0 +1,56 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/flash_font_file.h" + +#include "ppapi/c/dev/ppb_font_dev.h" +#include "ppapi/c/private/ppb_flash_font_file.h" +#include "ppapi/c/trusted/ppb_browser_font_trusted.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Flash_FontFile_0_1>() { + return PPB_FLASH_FONTFILE_INTERFACE_0_1; +} + +} // namespace + +namespace flash { + +FontFile::FontFile() { +} + +FontFile::FontFile(const InstanceHandle& instance, + const PP_BrowserFont_Trusted_Description* description, + PP_PrivateFontCharset charset) { + if (has_interface<PPB_Flash_FontFile_0_1>()) { + PassRefFromConstructor(get_interface<PPB_Flash_FontFile_0_1>()->Create( + instance.pp_instance(), description, charset)); + } +} + +FontFile::~FontFile() { +} + +// static +bool FontFile::IsAvailable() { + return has_interface<PPB_Flash_FontFile_0_1>(); +} + +bool FontFile::GetFontTable(uint32_t table, + void* output, + uint32_t* output_length) { + if (has_interface<PPB_Flash_FontFile_0_1>()) { + return !!get_interface<PPB_Flash_FontFile_0_1>()-> + GetFontTable(pp_resource(), table, output, output_length); + } + return false; +} + +} // namespace flash +} // namespace pp diff --git a/chromium/ppapi/cpp/private/flash_font_file.h b/chromium/ppapi/cpp/private/flash_font_file.h new file mode 100644 index 00000000000..053fca25789 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_font_file.h @@ -0,0 +1,37 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_FLASH_FONT_FILE_H_ +#define PPAPI_CPP_PRIVATE_FLASH_FONT_FILE_H_ + +#include "ppapi/c/private/pp_private_font_charset.h" +#include "ppapi/cpp/resource.h" + +struct PP_BrowserFont_Trusted_Description; + +namespace pp { + +class InstanceHandle; + +namespace flash { + +class FontFile : public Resource { + public: + // Default constructor for making an is_null() FontFile resource. + FontFile(); + FontFile(const InstanceHandle& instance, + const PP_BrowserFont_Trusted_Description* description, + PP_PrivateFontCharset charset); + virtual ~FontFile(); + + // Returns true if the required interface is available. + static bool IsAvailable(); + + bool GetFontTable(uint32_t table, void* output, uint32_t* output_length); +}; + +} // namespace flash +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FLASH_FONT_FILE_H_ diff --git a/chromium/ppapi/cpp/private/flash_fullscreen.cc b/chromium/ppapi/cpp/private/flash_fullscreen.cc new file mode 100644 index 00000000000..8d33b5f0f7f --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_fullscreen.cc @@ -0,0 +1,74 @@ +// Copyright (c) 2011 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 "ppapi/cpp/private/flash_fullscreen.h" + +#include "ppapi/c/private/ppb_flash_fullscreen.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/size.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_FlashFullscreen_0_1>() { + return PPB_FLASHFULLSCREEN_INTERFACE_0_1; +} + +template <> const char* interface_name<PPB_FlashFullscreen_1_0>() { + return PPB_FLASHFULLSCREEN_INTERFACE_1_0; +} + +} // namespace + +FlashFullscreen::FlashFullscreen(const InstanceHandle& instance) + : instance_(instance) { +} + +FlashFullscreen::~FlashFullscreen() { +} + +bool FlashFullscreen::IsFullscreen() { + if (has_interface<PPB_FlashFullscreen_1_0>()) { + return PP_ToBool(get_interface<PPB_FlashFullscreen_1_0>()->IsFullscreen( + instance_.pp_instance())); + } + if (has_interface<PPB_FlashFullscreen_0_1>()) { + return PP_ToBool(get_interface<PPB_FlashFullscreen_0_1>()->IsFullscreen( + instance_.pp_instance())); + } + return false; +} + +bool FlashFullscreen::SetFullscreen(bool fullscreen) { + if (has_interface<PPB_FlashFullscreen_1_0>()) { + return PP_ToBool(get_interface<PPB_FlashFullscreen_1_0>()->SetFullscreen( + instance_.pp_instance(), PP_FromBool(fullscreen))); + } + if (has_interface<PPB_FlashFullscreen_0_1>()) { + return PP_ToBool(get_interface<PPB_FlashFullscreen_0_1>()->SetFullscreen( + instance_.pp_instance(), PP_FromBool(fullscreen))); + } + return false; +} + +bool FlashFullscreen::GetScreenSize(Size* size) { + if (has_interface<PPB_FlashFullscreen_1_0>()) { + return PP_ToBool(get_interface<PPB_FlashFullscreen_1_0>()->GetScreenSize( + instance_.pp_instance(), &size->pp_size())); + } + if (has_interface<PPB_FlashFullscreen_0_1>()) { + return PP_ToBool(get_interface<PPB_FlashFullscreen_0_1>()->GetScreenSize( + instance_.pp_instance(), &size->pp_size())); + } + return false; +} + +bool FlashFullscreen::MustRecreateContexts() { + return !get_interface<PPB_FlashFullscreen_1_0>(); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/flash_fullscreen.h b/chromium/ppapi/cpp/private/flash_fullscreen.h new file mode 100644 index 00000000000..48e4ffd9091 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_fullscreen.h @@ -0,0 +1,32 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_FLASH_FULLSCREEN_H_ +#define PPAPI_CPP_PRIVATE_FLASH_FULLSCREEN_H_ + +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +class Size; + +class FlashFullscreen { + public: + FlashFullscreen(const InstanceHandle& instance); + virtual ~FlashFullscreen(); + + // PPB_FlashFullscreen methods. + bool IsFullscreen(); + bool SetFullscreen(bool fullscreen); + bool GetScreenSize(Size* size); + + bool MustRecreateContexts(); + + private: + InstanceHandle instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FLASH_FULLSCREEN_H_ diff --git a/chromium/ppapi/cpp/private/flash_menu.cc b/chromium/ppapi/cpp/private/flash_menu.cc new file mode 100644 index 00000000000..e77021b1a5b --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_menu.cc @@ -0,0 +1,47 @@ +// Copyright (c) 2011 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 "ppapi/cpp/private/flash_menu.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/point.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Flash_Menu>() { + return PPB_FLASH_MENU_INTERFACE; +} + +} // namespace + +namespace flash { + +Menu::Menu(const InstanceHandle& instance, + const struct PP_Flash_Menu* menu_data) { + if (has_interface<PPB_Flash_Menu>()) { + PassRefFromConstructor(get_interface<PPB_Flash_Menu>()->Create( + instance.pp_instance(), menu_data)); + } +} + +int32_t Menu::Show(const Point& location, + int32_t* selected_id, + const CompletionCallback& cc) { + if (!has_interface<PPB_Flash_Menu>()) + return cc.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_Flash_Menu>()->Show( + pp_resource(), + &location.pp_point(), + selected_id, + cc.pp_completion_callback()); +} + +} // namespace flash +} // namespace pp diff --git a/chromium/ppapi/cpp/private/flash_menu.h b/chromium/ppapi/cpp/private/flash_menu.h new file mode 100644 index 00000000000..a0a7499a636 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_menu.h @@ -0,0 +1,32 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_PRIVATE_FLASH_MENU_H_ +#define PPAPI_CPP_PRIVATE_FLASH_MENU_H_ + +#include "ppapi/c/private/ppb_flash_menu.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class CompletionCallback; +class InstanceHandle; +class Point; + +namespace flash { + +class Menu : public Resource { + public: + // TODO(viettrungluu): Write a proper C++ wrapper of |PP_Flash_Menu|. + Menu(const InstanceHandle& instance, const struct PP_Flash_Menu* menu_data); + + int32_t Show(const Point& location, + int32_t* selected_id, + const CompletionCallback& cc); +}; + +} // namespace flash +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FLASH_H_ diff --git a/chromium/ppapi/cpp/private/flash_message_loop.cc b/chromium/ppapi/cpp/private/flash_message_loop.cc new file mode 100644 index 00000000000..7f254382177 --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_message_loop.cc @@ -0,0 +1,51 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/flash_message_loop.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/private/ppb_flash_message_loop.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Flash_MessageLoop>() { + return PPB_FLASH_MESSAGELOOP_INTERFACE; +} + +} // namespace + +namespace flash { + +MessageLoop::MessageLoop(const InstanceHandle& instance) { + if (has_interface<PPB_Flash_MessageLoop>()) { + PassRefFromConstructor(get_interface<PPB_Flash_MessageLoop>()->Create( + instance.pp_instance())); + } +} + +MessageLoop::~MessageLoop() { +} + +// static +bool MessageLoop::IsAvailable() { + return has_interface<PPB_Flash_MessageLoop>(); +} + +int32_t MessageLoop::Run() { + if (!has_interface<PPB_Flash_MessageLoop>()) + return PP_ERROR_NOINTERFACE; + return get_interface<PPB_Flash_MessageLoop>()->Run(pp_resource()); +} + +void MessageLoop::Quit() { + if (has_interface<PPB_Flash_MessageLoop>()) + get_interface<PPB_Flash_MessageLoop>()->Quit(pp_resource()); +} + +} // namespace flash +} // namespace pp diff --git a/chromium/ppapi/cpp/private/flash_message_loop.h b/chromium/ppapi/cpp/private/flash_message_loop.h new file mode 100644 index 00000000000..fecb2d6b42d --- /dev/null +++ b/chromium/ppapi/cpp/private/flash_message_loop.h @@ -0,0 +1,31 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_FLASH_MESSAGE_LOOP_H_ +#define PPAPI_CPP_PRIVATE_FLASH_MESSAGE_LOOP_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class InstanceHandle; + +namespace flash { + +class MessageLoop : public Resource { + public: + explicit MessageLoop(const InstanceHandle& instance); + virtual ~MessageLoop(); + + static bool IsAvailable(); + + int32_t Run(); + void Quit(); +}; + +} // namespace flash +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_FLASH_MESSAGE_LOOP_H_ diff --git a/chromium/ppapi/cpp/private/host_resolver_private.cc b/chromium/ppapi/cpp/private/host_resolver_private.cc new file mode 100644 index 00000000000..92a344eda7e --- /dev/null +++ b/chromium/ppapi/cpp/private/host_resolver_private.cc @@ -0,0 +1,77 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/host_resolver_private.h" + +#include "ppapi/c/pp_bool.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/pass_ref.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_HostResolver_Private_0_1>() { + return PPB_HOSTRESOLVER_PRIVATE_INTERFACE_0_1; +} + +} // namespace + +HostResolverPrivate::HostResolverPrivate(const InstanceHandle& instance) { + if (has_interface<PPB_HostResolver_Private_0_1>()) { + PassRefFromConstructor( + get_interface<PPB_HostResolver_Private_0_1>()->Create( + instance.pp_instance())); + } +} + +// static +bool HostResolverPrivate::IsAvailable() { + return has_interface<PPB_HostResolver_Private_0_1>(); +} + +int32_t HostResolverPrivate::Resolve(const std::string& host, + uint16_t port, + const PP_HostResolver_Private_Hint& hint, + const CompletionCallback& callback) { + if (!has_interface<PPB_HostResolver_Private_0_1>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_HostResolver_Private_0_1>()->Resolve( + pp_resource(), + host.c_str(), + port, + &hint, + callback.pp_completion_callback()); +} + +Var HostResolverPrivate::GetCanonicalName() { + if (!has_interface<PPB_HostResolver_Private_0_1>()) + return Var(Var::Null()); + + PP_Var pp_canonical_name = + get_interface<PPB_HostResolver_Private_0_1>()->GetCanonicalName( + pp_resource()); + return Var(PASS_REF, pp_canonical_name); +} + +uint32_t HostResolverPrivate::GetSize() { + if (!has_interface<PPB_HostResolver_Private_0_1>()) + return 0; + return get_interface<PPB_HostResolver_Private_0_1>()->GetSize(pp_resource()); +} + +bool HostResolverPrivate::GetNetAddress(uint32_t index, + PP_NetAddress_Private* address) { + if (!has_interface<PPB_HostResolver_Private_0_1>()) + return false; + PP_Bool result = get_interface<PPB_HostResolver_Private_0_1>()->GetNetAddress( + pp_resource(), index, address); + return PP_ToBool(result); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/host_resolver_private.h b/chromium/ppapi/cpp/private/host_resolver_private.h new file mode 100644 index 00000000000..2e4b08e6b4f --- /dev/null +++ b/chromium/ppapi/cpp/private/host_resolver_private.h @@ -0,0 +1,40 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_HOST_RESOLVER_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_HOST_RESOLVER_PRIVATE_H_ + +#include <string> + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/private/ppb_host_resolver_private.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" + +struct PP_NetAddress_Private; + +namespace pp { + +class CompletionCallback; +class InstanceHandle; + +class HostResolverPrivate : public Resource { + public: + explicit HostResolverPrivate(const InstanceHandle& instance); + + // Returns true if the required interface is available. + static bool IsAvailable(); + + int32_t Resolve(const std::string& host, + uint16_t port, + const PP_HostResolver_Private_Hint& hint, + const CompletionCallback& callback); + Var GetCanonicalName(); + uint32_t GetSize(); + bool GetNetAddress(uint32_t index, PP_NetAddress_Private* address); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_HOST_RESOLVER_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/instance_private.cc b/chromium/ppapi/cpp/private/instance_private.cc new file mode 100644 index 00000000000..c55408a28cb --- /dev/null +++ b/chromium/ppapi/cpp/private/instance_private.cc @@ -0,0 +1,75 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/instance_private.h" + +#include "ppapi/c/private/ppb_instance_private.h" +#include "ppapi/c/private/ppp_instance_private.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/private/var_private.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Instance_Private>() { + return PPB_INSTANCE_PRIVATE_INTERFACE; +} + +PP_Var GetInstanceObject(PP_Instance pp_instance) { + Module* module_singleton = Module::Get(); + if (!module_singleton) + return Var().Detach(); + InstancePrivate* instance_private = static_cast<InstancePrivate*>( + module_singleton->InstanceForPPInstance(pp_instance)); + if (!instance_private) + return Var().Detach(); + return instance_private->GetInstanceObject().Detach(); +} + +const PPP_Instance_Private ppp_instance_private = { + &GetInstanceObject +}; + +} // namespace + +InstancePrivate::InstancePrivate(PP_Instance instance) : Instance(instance) { + // If at least 1 InstancePrivate is created, register the PPP_INSTANCE_PRIVATE + // interface. + Module::Get()->AddPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE, + &ppp_instance_private); +} + +InstancePrivate::~InstancePrivate() {} + +Var InstancePrivate::GetInstanceObject() { + return Var(); +} + +VarPrivate InstancePrivate::GetWindowObject() { + if (!has_interface<PPB_Instance_Private>()) + return VarPrivate(); + return VarPrivate(PASS_REF, + get_interface<PPB_Instance_Private>()->GetWindowObject(pp_instance())); +} + +VarPrivate InstancePrivate::GetOwnerElementObject() { + if (!has_interface<PPB_Instance_Private>()) + return VarPrivate(); + return VarPrivate(PASS_REF, + get_interface<PPB_Instance_Private>()->GetOwnerElementObject( + pp_instance())); +} + +VarPrivate InstancePrivate::ExecuteScript(const Var& script, Var* exception) { + if (!has_interface<PPB_Instance_Private>()) + return VarPrivate(); + return VarPrivate(PASS_REF, + get_interface<PPB_Instance_Private>()->ExecuteScript( + pp_instance(), + script.pp_var(), + VarPrivate::OutException(exception).get())); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/instance_private.h b/chromium/ppapi/cpp/private/instance_private.h new file mode 100644 index 00000000000..58254698995 --- /dev/null +++ b/chromium/ppapi/cpp/private/instance_private.h @@ -0,0 +1,59 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_INSTANCE_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_INSTANCE_PRIVATE_H_ + +/** + * @file + * Defines the API ... + * + * @addtogroup CPP + * @{ + */ + +#include "ppapi/c/ppb_console.h" +#include "ppapi/cpp/instance.h" + +/** The C++ interface to the Pepper API. */ +namespace pp { + +class Var; +class VarPrivate; + +class InstancePrivate : public Instance { + public: + explicit InstancePrivate(PP_Instance instance); + virtual ~InstancePrivate(); + + // @{ + /// @name PPP_Instance_Private methods for the plugin to override: + + /// See PPP_Instance_Private.GetInstanceObject. + virtual Var GetInstanceObject(); + + // @} + + // @{ + /// @name PPB_Instance_Private methods for querying the browser: + + /// See PPB_Instance_Private.GetWindowObject. + VarPrivate GetWindowObject(); + + /// See PPB_Instance_Private.GetOwnerElementObject. + VarPrivate GetOwnerElementObject(); + + /// See PPB_Instance.ExecuteScript. + VarPrivate ExecuteScript(const Var& script, Var* exception = NULL); + + // @} +}; + +} // namespace pp + +/** + * @} + * End addtogroup CPP + */ +#endif // PPAPI_CPP_PRIVATE_INSTANCE_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/net_address_private.cc b/chromium/ppapi/cpp/private/net_address_private.cc new file mode 100644 index 00000000000..3a32827639a --- /dev/null +++ b/chromium/ppapi/cpp/private/net_address_private.cc @@ -0,0 +1,218 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/net_address_private.h" + +#include "ppapi/c/pp_bool.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_NetAddress_Private_1_1>() { + return PPB_NETADDRESS_PRIVATE_INTERFACE_1_1; +} + +template <> const char* interface_name<PPB_NetAddress_Private_1_0>() { + return PPB_NETADDRESS_PRIVATE_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_NetAddress_Private_0_1>() { + return PPB_NETADDRESS_PRIVATE_INTERFACE_0_1; +} + +} // namespace + +// static +bool NetAddressPrivate::IsAvailable() { + return has_interface<PPB_NetAddress_Private_1_1>() || + has_interface<PPB_NetAddress_Private_1_0>() || + has_interface<PPB_NetAddress_Private_0_1>(); +} + +// static +bool NetAddressPrivate::AreEqual(const PP_NetAddress_Private& addr1, + const PP_NetAddress_Private& addr2) { + if (has_interface<PPB_NetAddress_Private_1_1>()) { + return !!get_interface<PPB_NetAddress_Private_1_1>()->AreEqual(&addr1, + &addr2); + } + if (has_interface<PPB_NetAddress_Private_1_0>()) { + return !!get_interface<PPB_NetAddress_Private_1_0>()->AreEqual(&addr1, + &addr2); + } + if (has_interface<PPB_NetAddress_Private_0_1>()) { + return !!get_interface<PPB_NetAddress_Private_0_1>()->AreEqual(&addr1, + &addr2); + } + return false; +} + +// static +bool NetAddressPrivate::AreHostsEqual(const PP_NetAddress_Private& addr1, + const PP_NetAddress_Private& addr2) { + if (has_interface<PPB_NetAddress_Private_1_1>()) { + return !!get_interface<PPB_NetAddress_Private_1_1>()->AreHostsEqual(&addr1, + &addr2); + } + if (has_interface<PPB_NetAddress_Private_1_0>()) { + return !!get_interface<PPB_NetAddress_Private_1_0>()->AreHostsEqual(&addr1, + &addr2); + } + if (has_interface<PPB_NetAddress_Private_0_1>()) { + return !!get_interface<PPB_NetAddress_Private_0_1>()->AreHostsEqual(&addr1, + &addr2); + } + return false; +} + +// static +std::string NetAddressPrivate::Describe(const PP_NetAddress_Private& addr, + bool include_port) { + Module* module = Module::Get(); + if (!module) + return std::string(); + + PP_Var result_pp_var = PP_MakeUndefined(); + if (has_interface<PPB_NetAddress_Private_1_1>()) { + result_pp_var = get_interface<PPB_NetAddress_Private_1_1>()->Describe( + module->pp_module(), + &addr, + PP_FromBool(include_port)); + } else if (has_interface<PPB_NetAddress_Private_1_0>()) { + result_pp_var = get_interface<PPB_NetAddress_Private_1_0>()->Describe( + module->pp_module(), + &addr, + PP_FromBool(include_port)); + } else if (has_interface<PPB_NetAddress_Private_0_1>()) { + result_pp_var = get_interface<PPB_NetAddress_Private_0_1>()->Describe( + module->pp_module(), + &addr, + PP_FromBool(include_port)); + } + + Var result(PASS_REF, result_pp_var); + return result.is_string() ? result.AsString() : std::string(); +} + +// static +bool NetAddressPrivate::ReplacePort(const PP_NetAddress_Private& addr_in, + uint16_t port, + PP_NetAddress_Private* addr_out) { + if (has_interface<PPB_NetAddress_Private_1_1>()) { + return !!get_interface<PPB_NetAddress_Private_1_1>()->ReplacePort(&addr_in, + port, + addr_out); + } + if (has_interface<PPB_NetAddress_Private_1_0>()) { + return !!get_interface<PPB_NetAddress_Private_1_0>()->ReplacePort(&addr_in, + port, + addr_out); + } + if (has_interface<PPB_NetAddress_Private_0_1>()) { + return !!get_interface<PPB_NetAddress_Private_0_1>()->ReplacePort(&addr_in, + port, + addr_out); + } + return false; +} + +// static +bool NetAddressPrivate::GetAnyAddress(bool is_ipv6, + PP_NetAddress_Private* addr) { + if (has_interface<PPB_NetAddress_Private_1_1>()) { + get_interface<PPB_NetAddress_Private_1_1>()->GetAnyAddress( + PP_FromBool(is_ipv6), + addr); + return true; + } else if (has_interface<PPB_NetAddress_Private_1_0>()) { + get_interface<PPB_NetAddress_Private_1_0>()->GetAnyAddress( + PP_FromBool(is_ipv6), + addr); + return true; + } else if (has_interface<PPB_NetAddress_Private_0_1>()) { + get_interface<PPB_NetAddress_Private_0_1>()->GetAnyAddress( + PP_FromBool(is_ipv6), + addr); + return true; + } + return false; +} + +// static +PP_NetAddressFamily_Private NetAddressPrivate::GetFamily( + const PP_NetAddress_Private& addr) { + if (has_interface<PPB_NetAddress_Private_1_1>()) + return get_interface<PPB_NetAddress_Private_1_1>()->GetFamily(&addr); + if (has_interface<PPB_NetAddress_Private_1_0>()) + return get_interface<PPB_NetAddress_Private_1_0>()->GetFamily(&addr); + return PP_NETADDRESSFAMILY_PRIVATE_UNSPECIFIED; +} + +// static +uint16_t NetAddressPrivate::GetPort(const PP_NetAddress_Private& addr) { + if (has_interface<PPB_NetAddress_Private_1_1>()) + return get_interface<PPB_NetAddress_Private_1_1>()->GetPort(&addr); + if (has_interface<PPB_NetAddress_Private_1_0>()) + return get_interface<PPB_NetAddress_Private_1_0>()->GetPort(&addr); + return 0; +} + +// static +bool NetAddressPrivate::GetAddress(const PP_NetAddress_Private& addr, + void* address, + uint16_t address_size) { + if (has_interface<PPB_NetAddress_Private_1_1>()) { + return PP_ToBool(get_interface<PPB_NetAddress_Private_1_1>()->GetAddress( + &addr, + address, + address_size)); + } + if (has_interface<PPB_NetAddress_Private_1_0>()) { + return PP_ToBool(get_interface<PPB_NetAddress_Private_1_0>()->GetAddress( + &addr, + address, + address_size)); + } + return false; +} + +// static +uint32_t NetAddressPrivate::GetScopeID(const PP_NetAddress_Private& addr) { + if (has_interface<PPB_NetAddress_Private_1_1>()) + return get_interface<PPB_NetAddress_Private_1_1>()->GetScopeID(&addr); + return 0; +} + +// static +bool NetAddressPrivate::CreateFromIPv4Address( + const uint8_t ip[4], + uint16_t port, + struct PP_NetAddress_Private* addr_out) { + if (has_interface<PPB_NetAddress_Private_1_1>()) { + get_interface<PPB_NetAddress_Private_1_1>()->CreateFromIPv4Address( + ip, port, addr_out); + return true; + } + return false; +} + +// static +bool NetAddressPrivate::CreateFromIPv6Address( + const uint8_t ip[16], + uint32_t scope_id, + uint16_t port, + struct PP_NetAddress_Private* addr_out) { + if (has_interface<PPB_NetAddress_Private_1_1>()) { + get_interface<PPB_NetAddress_Private_1_1>()->CreateFromIPv6Address( + ip, scope_id, port, addr_out); + return true; + } + return false; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/net_address_private.h b/chromium/ppapi/cpp/private/net_address_private.h new file mode 100644 index 00000000000..5ad50d736e8 --- /dev/null +++ b/chromium/ppapi/cpp/private/net_address_private.h @@ -0,0 +1,48 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_NET_ADDRESS_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_NET_ADDRESS_PRIVATE_H_ + +#include <string> + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/private/ppb_net_address_private.h" + +namespace pp { + +class NetAddressPrivate { + public: + // Returns true if the required interface is available. + static bool IsAvailable(); + + static bool AreEqual(const PP_NetAddress_Private& addr1, + const PP_NetAddress_Private& addr2); + static bool AreHostsEqual(const PP_NetAddress_Private& addr1, + const PP_NetAddress_Private& addr2); + static std::string Describe(const PP_NetAddress_Private& addr, + bool include_port); + static bool ReplacePort(const PP_NetAddress_Private& addr_in, + uint16_t port, + PP_NetAddress_Private* addr_out); + static bool GetAnyAddress(bool is_ipv6, PP_NetAddress_Private* addr); + static PP_NetAddressFamily_Private GetFamily( + const PP_NetAddress_Private& addr); + static uint16_t GetPort(const PP_NetAddress_Private& addr); + static bool GetAddress(const PP_NetAddress_Private& addr, + void* address, + uint16_t address_size); + static uint32_t GetScopeID(const PP_NetAddress_Private& addr); + static bool CreateFromIPv4Address(const uint8_t ip[4], + uint16_t port, + struct PP_NetAddress_Private* addr_out); + static bool CreateFromIPv6Address(const uint8_t ip[16], + uint32_t scope_id, + uint16_t port, + struct PP_NetAddress_Private* addr_out); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_NET_ADDRESS_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/network_list_private.cc b/chromium/ppapi/cpp/private/network_list_private.cc new file mode 100644 index 00000000000..1297aa3a09c --- /dev/null +++ b/chromium/ppapi/cpp/private/network_list_private.cc @@ -0,0 +1,110 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/network_list_private.h" + +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_NetworkList_Private>() { + return PPB_NETWORKLIST_PRIVATE_INTERFACE; +} + +} // namespace + +NetworkListPrivate::NetworkListPrivate() { +} + +NetworkListPrivate::NetworkListPrivate(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +// static +bool NetworkListPrivate::IsAvailable() { + return has_interface<PPB_NetworkList_Private>(); +} + +uint32_t NetworkListPrivate::GetCount() const { + if (!has_interface<PPB_NetworkList_Private>()) + return 0; + return get_interface<PPB_NetworkList_Private>()->GetCount(pp_resource()); +} + +std::string NetworkListPrivate::GetName(uint32_t index) const { + if (!has_interface<PPB_NetworkList_Private>()) + return std::string(); + Var result(PASS_REF, + get_interface<PPB_NetworkList_Private>()->GetName( + pp_resource(), index)); + return result.is_string() ? result.AsString() : std::string(); +} + +PP_NetworkListType_Private NetworkListPrivate::GetType(uint32_t index) const { + if (!has_interface<PPB_NetworkList_Private>()) + return PP_NETWORKLIST_ETHERNET; + return get_interface<PPB_NetworkList_Private>()->GetType( + pp_resource(), index); +} + +PP_NetworkListState_Private NetworkListPrivate::GetState(uint32_t index) const { + if (!has_interface<PPB_NetworkList_Private>()) + return PP_NETWORKLIST_DOWN; + return get_interface<PPB_NetworkList_Private>()->GetState( + pp_resource(), index); +} + +void NetworkListPrivate::GetIpAddresses( + uint32_t index, + std::vector<PP_NetAddress_Private>* addresses) const { + if (!has_interface<PPB_NetworkList_Private>()) + return; + + // Most network interfaces don't have more than 3 network + // interfaces. + addresses->resize(3); + + int32_t result = get_interface<PPB_NetworkList_Private>()->GetIpAddresses( + pp_resource(), index, &addresses->front(), addresses->size()); + + if (result < 0) { + addresses->resize(0); + return; + } + + if (result <= static_cast<int32_t>(addresses->size())) { + addresses->resize(result); + return; + } + + addresses->resize(result); + result = get_interface<PPB_NetworkList_Private>()->GetIpAddresses( + pp_resource(), index, &addresses->front(), addresses->size()); + if (result < 0) { + addresses->resize(0); + } else if (result < static_cast<int32_t>(addresses->size())) { + addresses->resize(result); + } +} + +std::string NetworkListPrivate::GetDisplayName(uint32_t index) const { + if (!has_interface<PPB_NetworkList_Private>()) + return std::string(); + Var result(PASS_REF, + get_interface<PPB_NetworkList_Private>()->GetDisplayName( + pp_resource(), index)); + return result.is_string() ? result.AsString() : std::string(); +} + +uint32_t NetworkListPrivate::GetMTU(uint32_t index) const { + if (!has_interface<PPB_NetworkList_Private>()) + return 0; + return get_interface<PPB_NetworkList_Private>()->GetMTU( + pp_resource(), index); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/network_list_private.h b/chromium/ppapi/cpp/private/network_list_private.h new file mode 100644 index 00000000000..31cd9b598b8 --- /dev/null +++ b/chromium/ppapi/cpp/private/network_list_private.h @@ -0,0 +1,58 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_NETWORK_LIST_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_NETWORK_LIST_PRIVATE_H_ + +#include <string> +#include <vector> + +#include "ppapi/c/private/ppb_network_list_private.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class NetworkListPrivate : public Resource { + public: + NetworkListPrivate(); + NetworkListPrivate(PassRef, PP_Resource resource); + + /// Returns true if the required interface is available. + static bool IsAvailable(); + + /// @return Returns the number of available network interfaces or 0 + /// if the list has never been updated. + uint32_t GetCount() const; + + /// @return Returns the name for the network interface with the + /// specified <code>index</code>. + std::string GetName(uint32_t index) const; + + /// @return Returns the type of the network interface with the + /// specified <code>index</code>. + PP_NetworkListType_Private GetType(uint32_t index) const; + + /// @return Returns the current state of the network interface with + /// the specified <code>index</code>. + PP_NetworkListState_Private GetState(uint32_t index) const; + + /// Gets the list of IP addresses for the network interface with the + /// specified <code>index</code> and stores them in + /// <code>addresses</code>. + void GetIpAddresses(uint32_t index, + std::vector<PP_NetAddress_Private>* addresses) const; + + /// @return Returns the display name for the network interface with + /// the specified <code>index</code>. + std::string GetDisplayName(uint32_t index) const; + + /// @return Returns the MTU for the network interface with the + /// specified <code>index</code>. + uint32_t GetMTU(uint32_t index) const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_NETWORK_LIST_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/network_monitor_private.cc b/chromium/ppapi/cpp/private/network_monitor_private.cc new file mode 100644 index 00000000000..2f931ea4288 --- /dev/null +++ b/chromium/ppapi/cpp/private/network_monitor_private.cc @@ -0,0 +1,35 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/network_monitor_private.h" + +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_NetworkMonitor_Private>() { + return PPB_NETWORKMONITOR_PRIVATE_INTERFACE; +} + +} // namespace + +NetworkMonitorPrivate::NetworkMonitorPrivate( + const InstanceHandle& instance, + PPB_NetworkMonitor_Callback callback, + void* user_data) { + if (has_interface<PPB_NetworkMonitor_Private>()) { + PassRefFromConstructor(get_interface<PPB_NetworkMonitor_Private>()->Create( + instance.pp_instance(), callback, user_data)); + } +} + +// static +bool NetworkMonitorPrivate::IsAvailable() { + return has_interface<PPB_NetworkMonitor_Private>(); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/network_monitor_private.h b/chromium/ppapi/cpp/private/network_monitor_private.h new file mode 100644 index 00000000000..693bbcdc7fb --- /dev/null +++ b/chromium/ppapi/cpp/private/network_monitor_private.h @@ -0,0 +1,28 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_NETWORK_MONITOR_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_NETWORK_MONITOR_PRIVATE_H_ + +#include "ppapi/c/private/ppb_network_monitor_private.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/instance_handle.h" + +namespace pp { + +class Instance; + +class NetworkMonitorPrivate : public Resource { + public: + NetworkMonitorPrivate(const InstanceHandle& instance, + PPB_NetworkMonitor_Callback callback, + void* user_data); + + // Returns true if the required interface is available. + static bool IsAvailable(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_NETWORK_MONITOR_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/pass_file_handle.cc b/chromium/ppapi/cpp/private/pass_file_handle.cc new file mode 100644 index 00000000000..5735d33a71f --- /dev/null +++ b/chromium/ppapi/cpp/private/pass_file_handle.cc @@ -0,0 +1,48 @@ +// Copyright (c) 2013 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 "ppapi/cpp/private/pass_file_handle.h" + +#ifdef _WIN32 +# include <windows.h> +#else +# include <unistd.h> +#endif + +namespace pp { + +PassFileHandle::PassFileHandle() + : handle_(PP_kInvalidFileHandle) { +} + +PassFileHandle::PassFileHandle(PP_FileHandle handle) + : handle_(handle) { +} + +PassFileHandle::PassFileHandle(PassFileHandle& handle) + : handle_(handle.Release()) { +} + +PassFileHandle::~PassFileHandle() { + Close(); +} + +PP_FileHandle PassFileHandle::Release() { + PP_FileHandle released = handle_; + handle_ = PP_kInvalidFileHandle; + return released; +} + +void PassFileHandle::Close() { + if (handle_ != PP_kInvalidFileHandle) { +#ifdef _WIN32 + CloseHandle(handle_); +#else + close(handle_); +#endif + handle_ = PP_kInvalidFileHandle; + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/pass_file_handle.h b/chromium/ppapi/cpp/private/pass_file_handle.h new file mode 100644 index 00000000000..c25353b4838 --- /dev/null +++ b/chromium/ppapi/cpp/private/pass_file_handle.h @@ -0,0 +1,81 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_PRIVATE_PASS_FILE_HANDLE_H_ +#define PPAPI_CPP_PRIVATE_PASS_FILE_HANDLE_H_ + +#include <string.h> + +#include "ppapi/c/private/pp_file_handle.h" +#include "ppapi/cpp/output_traits.h" + +namespace pp { + +// A wrapper class for PP_FileHandle to make sure a file handle is +// closed. This object takes the ownership of the file handle when it +// is constructed. This loses the ownership when this object is +// assigned to another object, just like auto_ptr. +class PassFileHandle { + public: + PassFileHandle(); + // This constructor takes the ownership of |handle|. + explicit PassFileHandle(PP_FileHandle handle); + // Moves the ownership of |handle| to this object. + PassFileHandle(PassFileHandle& handle); + ~PassFileHandle(); + + // Releases |handle_|. The caller must close the file handle returned. + PP_FileHandle Release(); + + private: + // PassFileHandleRef allows users to return PassFileHandle as a + // value. This technique is also used by auto_ptr_ref. + struct PassFileHandleRef { + PP_FileHandle handle; + explicit PassFileHandleRef(PP_FileHandle h) + : handle(h) { + } + }; + + public: + PassFileHandle(PassFileHandleRef ref) + : handle_(ref.handle) { + } + + operator PassFileHandleRef() { + return PassFileHandleRef(Release()); + } + + private: + void operator=(const PassFileHandle&); + + void Close(); + + PP_FileHandle handle_; +}; + +namespace internal { + +template<> +struct CallbackOutputTraits<PassFileHandle> { + typedef PP_FileHandle* APIArgType; + typedef PP_FileHandle StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return &t; + } + + static inline PassFileHandle StorageToPluginArg(StorageType& t) { + return PassFileHandle(t); + } + + static inline void Initialize(StorageType* t) { + memset(t, 0, sizeof(*t)); + } +}; + +} // namespace internal +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_PASS_FILE_HANDLE_H_ diff --git a/chromium/ppapi/cpp/private/pdf.cc b/chromium/ppapi/cpp/private/pdf.cc new file mode 100644 index 00000000000..753613c18a3 --- /dev/null +++ b/chromium/ppapi/cpp/private/pdf.cc @@ -0,0 +1,187 @@ +// Copyright (c) 2013 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 "ppapi/cpp/private/pdf.h" + +#include "ppapi/c/trusted/ppb_browser_font_trusted.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_PDF>() { + return PPB_PDF_INTERFACE; +} + +} // namespace + +// static +bool PDF::IsAvailable() { + return has_interface<PPB_PDF>(); +} + +// static +Var PDF::GetLocalizedString(const InstanceHandle& instance, + PP_ResourceString string_id) { + if (has_interface<PPB_PDF>()) { + return Var(PASS_REF, + get_interface<PPB_PDF>()->GetLocalizedString( + instance.pp_instance(), string_id)); + } + return Var(); +} + +// static +ImageData PDF::GetResourceImage(const InstanceHandle& instance, + PP_ResourceImage image_id) { + if (has_interface<PPB_PDF>()) { + return ImageData(PASS_REF, + get_interface<PPB_PDF>()->GetResourceImage( + instance.pp_instance(), image_id)); + } + return ImageData(); +} + +// static +PP_Resource PDF::GetFontFileWithFallback( + const InstanceHandle& instance, + const PP_FontDescription_Dev* description, + PP_PrivateFontCharset charset) { + if (has_interface<PPB_PDF>()) { + PP_BrowserFont_Trusted_Description converted_desc; + converted_desc.face = description->face; + converted_desc.family = static_cast<PP_BrowserFont_Trusted_Family>( + description->family); + converted_desc.size = description->size; + converted_desc.weight = static_cast<PP_BrowserFont_Trusted_Weight>( + description->weight); + converted_desc.italic = description->italic; + converted_desc.small_caps = description->small_caps; + converted_desc.letter_spacing = description->letter_spacing; + converted_desc.word_spacing = description->word_spacing; + return get_interface<PPB_PDF>()->GetFontFileWithFallback( + instance.pp_instance(), &converted_desc, charset); + } + return 0; +} + +// static +PP_Resource PDF::GetFontFileWithFallback( + const InstanceHandle& instance, + const PP_BrowserFont_Trusted_Description* description, + PP_PrivateFontCharset charset) { + if (has_interface<PPB_PDF>()) { + return get_interface<PPB_PDF>()->GetFontFileWithFallback( + instance.pp_instance(), description, charset); + } + return 0; +} + +// static +bool PDF::GetFontTableForPrivateFontFile(PP_Resource font_file, + uint32_t table, + void* output, + uint32_t* output_length) { + if (has_interface<PPB_PDF>()) { + return get_interface<PPB_PDF>()->GetFontTableForPrivateFontFile(font_file, + table, output, output_length); + } + return false; +} + +// static +void PDF::SearchString(const InstanceHandle& instance, + const unsigned short* string, + const unsigned short* term, + bool case_sensitive, + PP_PrivateFindResult** results, + int* count) { + if (has_interface<PPB_PDF>()) { + get_interface<PPB_PDF>()->SearchString(instance.pp_instance(), string, + term, case_sensitive, results, count); + } +} + +// static +void PDF::DidStartLoading(const InstanceHandle& instance) { + if (has_interface<PPB_PDF>()) + get_interface<PPB_PDF>()->DidStartLoading(instance.pp_instance()); +} + +// static +void PDF::DidStopLoading(const InstanceHandle& instance) { + if (has_interface<PPB_PDF>()) + get_interface<PPB_PDF>()->DidStopLoading(instance.pp_instance()); +} + +// static +void PDF::SetContentRestriction(const InstanceHandle& instance, + int restrictions) { + if (has_interface<PPB_PDF>()) { + get_interface<PPB_PDF>()->SetContentRestriction(instance.pp_instance(), + restrictions); + } +} + +// static +void PDF::HistogramPDFPageCount(const InstanceHandle& instance, + int count) { + if (has_interface<PPB_PDF>()) + get_interface<PPB_PDF>()->HistogramPDFPageCount(instance.pp_instance(), + count); +} + +// static +void PDF::UserMetricsRecordAction(const InstanceHandle& instance, + const Var& action) { + if (has_interface<PPB_PDF>()) { + get_interface<PPB_PDF>()->UserMetricsRecordAction(instance.pp_instance(), + action.pp_var()); + } +} + +// static +void PDF::HasUnsupportedFeature(const InstanceHandle& instance) { + if (has_interface<PPB_PDF>()) + get_interface<PPB_PDF>()->HasUnsupportedFeature(instance.pp_instance()); +} + +// static +void PDF::SaveAs(const InstanceHandle& instance) { + if (has_interface<PPB_PDF>()) + get_interface<PPB_PDF>()->SaveAs(instance.pp_instance()); +} + +// static +void PDF::Print(const InstanceHandle& instance) { + if (has_interface<PPB_PDF>()) + get_interface<PPB_PDF>()->Print(instance.pp_instance()); +} + +// static +bool PDF::IsFeatureEnabled(const InstanceHandle& instance, + PP_PDFFeature feature) { + if (has_interface<PPB_PDF>()) + return PP_ToBool(get_interface<PPB_PDF>()->IsFeatureEnabled( + instance.pp_instance(), feature)); + return false; +} + +// static +ImageData PDF::GetResourceImageForScale(const InstanceHandle& instance, + PP_ResourceImage image_id, + float scale) { + if (has_interface<PPB_PDF>()) { + return ImageData(PASS_REF, + get_interface<PPB_PDF>()->GetResourceImageForScale( + instance.pp_instance(), image_id, scale)); + } + return ImageData(); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/pdf.h b/chromium/ppapi/cpp/private/pdf.h new file mode 100644 index 00000000000..893f9e3f279 --- /dev/null +++ b/chromium/ppapi/cpp/private/pdf.h @@ -0,0 +1,69 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_PRIVATE_PDF_H_ +#define PPAPI_CPP_PRIVATE_PDF_H_ + +#include <string> + +#include "ppapi/c/private/ppb_pdf.h" + +struct PP_BrowserFont_Trusted_Description; + +namespace pp { + +class ImageData; +class InstanceHandle; +class Var; + +class PDF { + public: + // Returns true if the required interface is available. + static bool IsAvailable(); + + static Var GetLocalizedString(const InstanceHandle& instance, + PP_ResourceString string_id); + static ImageData GetResourceImage(const InstanceHandle& instance, + PP_ResourceImage image_id); + // TODO(raymes): Remove this version when the PDF code is changed to use + // PP_BrowserFont_Trusted_Description. + static PP_Resource GetFontFileWithFallback( + const InstanceHandle& instance, + const PP_FontDescription_Dev* description, + PP_PrivateFontCharset charset); + static PP_Resource GetFontFileWithFallback( + const InstanceHandle& instance, + const PP_BrowserFont_Trusted_Description* description, + PP_PrivateFontCharset charset); + static bool GetFontTableForPrivateFontFile(PP_Resource font_file, + uint32_t table, + void* output, + uint32_t* output_length); + static void SearchString(const InstanceHandle& instance, + const unsigned short* string, + const unsigned short* term, + bool case_sensitive, + PP_PrivateFindResult** results, + int* count); + static void DidStartLoading(const InstanceHandle& instance); + static void DidStopLoading(const InstanceHandle& instance); + static void SetContentRestriction(const InstanceHandle& instance, + int restrictions); + static void HistogramPDFPageCount(const InstanceHandle& instance, + int count); + static void UserMetricsRecordAction(const InstanceHandle& instance, + const Var& action); + static void HasUnsupportedFeature(const InstanceHandle& instance); + static void SaveAs(const InstanceHandle& instance); + static void Print(const InstanceHandle& instance); + static bool IsFeatureEnabled(const InstanceHandle& instance, + PP_PDFFeature feature); + static ImageData GetResourceImageForScale(const InstanceHandle& instance, + PP_ResourceImage image_id, + float scale); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_PDF_H_ diff --git a/chromium/ppapi/cpp/private/tcp_server_socket_private.cc b/chromium/ppapi/cpp/private/tcp_server_socket_private.cc new file mode 100644 index 00000000000..50adcc126a6 --- /dev/null +++ b/chromium/ppapi/cpp/private/tcp_server_socket_private.cc @@ -0,0 +1,91 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/tcp_server_socket_private.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_TCPServerSocket_Private_0_2>() { + return PPB_TCPSERVERSOCKET_PRIVATE_INTERFACE_0_2; +} + +template <> const char* interface_name<PPB_TCPServerSocket_Private_0_1>() { + return PPB_TCPSERVERSOCKET_PRIVATE_INTERFACE_0_1; +} + +} // namespace + +TCPServerSocketPrivate::TCPServerSocketPrivate(const InstanceHandle& instance) { + if (has_interface<PPB_TCPServerSocket_Private_0_2>()) { + PassRefFromConstructor( + get_interface<PPB_TCPServerSocket_Private_0_2>()->Create( + instance.pp_instance())); + } else if (has_interface<PPB_TCPServerSocket_Private_0_1>()) { + PassRefFromConstructor( + get_interface<PPB_TCPServerSocket_Private_0_1>()->Create( + instance.pp_instance())); + } +} + +// static +bool TCPServerSocketPrivate::IsAvailable() { + return has_interface<PPB_TCPServerSocket_Private_0_2>() || + has_interface<PPB_TCPServerSocket_Private_0_1>(); +} + +int32_t TCPServerSocketPrivate::Listen(const PP_NetAddress_Private* addr, + int32_t backlog, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPServerSocket_Private_0_2>()) { + return get_interface<PPB_TCPServerSocket_Private_0_2>()->Listen( + pp_resource(), addr, backlog, callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPServerSocket_Private_0_1>()) { + return get_interface<PPB_TCPServerSocket_Private_0_1>()->Listen( + pp_resource(), addr, backlog, callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t TCPServerSocketPrivate::Accept(PP_Resource* tcp_socket, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPServerSocket_Private_0_2>()) { + return get_interface<PPB_TCPServerSocket_Private_0_2>()->Accept( + pp_resource(), tcp_socket, callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPServerSocket_Private_0_1>()) { + return get_interface<PPB_TCPServerSocket_Private_0_1>()->Accept( + pp_resource(), tcp_socket, callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t TCPServerSocketPrivate::GetLocalAddress(PP_NetAddress_Private* addr) { + if (has_interface<PPB_TCPServerSocket_Private_0_2>()) { + return get_interface<PPB_TCPServerSocket_Private_0_2>()->GetLocalAddress( + pp_resource(), addr); + } + return PP_ERROR_NOINTERFACE; +} + +void TCPServerSocketPrivate::StopListening() { + if (has_interface<PPB_TCPServerSocket_Private_0_2>()) { + return get_interface<PPB_TCPServerSocket_Private_0_2>()->StopListening( + pp_resource()); + } + if (has_interface<PPB_TCPServerSocket_Private_0_1>()) { + return get_interface<PPB_TCPServerSocket_Private_0_1>()->StopListening( + pp_resource()); + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/tcp_server_socket_private.h b/chromium/ppapi/cpp/private/tcp_server_socket_private.h new file mode 100644 index 00000000000..d6a1942fc2e --- /dev/null +++ b/chromium/ppapi/cpp/private/tcp_server_socket_private.h @@ -0,0 +1,39 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_TCP_SERVER_SOCKET_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_TCP_SERVER_SOCKET_PRIVATE_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/private/ppb_tcp_server_socket_private.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class CompletionCallback; +class InstanceHandle; + +class TCPServerSocketPrivate : public Resource { + public: + explicit TCPServerSocketPrivate(const InstanceHandle& instance); + + // Returns true if the required interface is available. + static bool IsAvailable(); + + int32_t Listen(const PP_NetAddress_Private* addr, + int32_t backlog, + const CompletionCallback& callback); + // Accepts incoming connection and stores resource of accepted + // socket into |socket|. If Accept returns PP_OK_COMPLETIONPENDING, + // the memory pointed by |socket| should stay valid until the + // |callback| is called or StopListening method is called. + int32_t Accept(PP_Resource* socket, + const CompletionCallback& callback); + int32_t GetLocalAddress(PP_NetAddress_Private* addr); + void StopListening(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_TCP_SERVER_SOCKET_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/tcp_socket_private.cc b/chromium/ppapi/cpp/private/tcp_socket_private.cc new file mode 100644 index 00000000000..996e0a0f513 --- /dev/null +++ b/chromium/ppapi/cpp/private/tcp_socket_private.cc @@ -0,0 +1,248 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/tcp_socket_private.h" + +#include "ppapi/c/pp_bool.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_TCPSocket_Private_0_5>() { + return PPB_TCPSOCKET_PRIVATE_INTERFACE_0_5; +} + +template <> const char* interface_name<PPB_TCPSocket_Private_0_4>() { + return PPB_TCPSOCKET_PRIVATE_INTERFACE_0_4; +} + +template <> const char* interface_name<PPB_TCPSocket_Private_0_3>() { + return PPB_TCPSOCKET_PRIVATE_INTERFACE_0_3; +} + +} // namespace + +TCPSocketPrivate::TCPSocketPrivate(const InstanceHandle& instance) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + PassRefFromConstructor(get_interface<PPB_TCPSocket_Private_0_5>()->Create( + instance.pp_instance())); + } else if (has_interface<PPB_TCPSocket_Private_0_4>()) { + PassRefFromConstructor(get_interface<PPB_TCPSocket_Private_0_4>()->Create( + instance.pp_instance())); + } else if (has_interface<PPB_TCPSocket_Private_0_3>()) { + PassRefFromConstructor(get_interface<PPB_TCPSocket_Private_0_3>()->Create( + instance.pp_instance())); + } +} + +TCPSocketPrivate::TCPSocketPrivate(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +// static +bool TCPSocketPrivate::IsAvailable() { + return has_interface<PPB_TCPSocket_Private_0_5>() || + has_interface<PPB_TCPSocket_Private_0_4>() || + has_interface<PPB_TCPSocket_Private_0_3>(); +} + +int32_t TCPSocketPrivate::Connect(const char* host, + uint16_t port, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + return get_interface<PPB_TCPSocket_Private_0_5>()->Connect( + pp_resource(), host, port, callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + return get_interface<PPB_TCPSocket_Private_0_4>()->Connect( + pp_resource(), host, port, callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_3>()) { + return get_interface<PPB_TCPSocket_Private_0_3>()->Connect( + pp_resource(), host, port, callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t TCPSocketPrivate::ConnectWithNetAddress( + const PP_NetAddress_Private* addr, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + return get_interface<PPB_TCPSocket_Private_0_5>()->ConnectWithNetAddress( + pp_resource(), addr, callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + return get_interface<PPB_TCPSocket_Private_0_4>()->ConnectWithNetAddress( + pp_resource(), addr, callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_3>()) { + return get_interface<PPB_TCPSocket_Private_0_3>()->ConnectWithNetAddress( + pp_resource(), addr, callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +bool TCPSocketPrivate::GetLocalAddress(PP_NetAddress_Private* local_addr) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + PP_Bool result = get_interface<PPB_TCPSocket_Private_0_5>()-> + GetLocalAddress(pp_resource(), local_addr); + return PP_ToBool(result); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + PP_Bool result = get_interface<PPB_TCPSocket_Private_0_4>()-> + GetLocalAddress(pp_resource(), local_addr); + return PP_ToBool(result); + } + if (has_interface<PPB_TCPSocket_Private_0_3>()) { + PP_Bool result = get_interface<PPB_TCPSocket_Private_0_3>()-> + GetLocalAddress(pp_resource(), local_addr); + return PP_ToBool(result); + } + return false; +} + +bool TCPSocketPrivate::GetRemoteAddress(PP_NetAddress_Private* remote_addr) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + PP_Bool result = get_interface<PPB_TCPSocket_Private_0_5>()-> + GetRemoteAddress(pp_resource(), remote_addr); + return PP_ToBool(result); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + PP_Bool result = get_interface<PPB_TCPSocket_Private_0_4>()-> + GetRemoteAddress(pp_resource(), remote_addr); + return PP_ToBool(result); + } + if (has_interface<PPB_TCPSocket_Private_0_3>()) { + PP_Bool result = get_interface<PPB_TCPSocket_Private_0_3>()-> + GetRemoteAddress(pp_resource(), remote_addr); + return PP_ToBool(result); + } + return false; +} + +int32_t TCPSocketPrivate::SSLHandshake(const char* server_name, + uint16_t server_port, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + return get_interface<PPB_TCPSocket_Private_0_5>()->SSLHandshake( + pp_resource(), server_name, server_port, + callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + return get_interface<PPB_TCPSocket_Private_0_4>()->SSLHandshake( + pp_resource(), server_name, server_port, + callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_3>()) { + return get_interface<PPB_TCPSocket_Private_0_3>()->SSLHandshake( + pp_resource(), server_name, server_port, + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +X509CertificatePrivate TCPSocketPrivate::GetServerCertificate() { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + return X509CertificatePrivate(PASS_REF, + get_interface<PPB_TCPSocket_Private_0_5>()->GetServerCertificate( + pp_resource())); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + return X509CertificatePrivate(PASS_REF, + get_interface<PPB_TCPSocket_Private_0_4>()->GetServerCertificate( + pp_resource())); + } + return X509CertificatePrivate(); +} + +bool TCPSocketPrivate::AddChainBuildingCertificate( + const X509CertificatePrivate& cert, + bool trusted) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + return PP_ToBool(get_interface<PPB_TCPSocket_Private_0_5>()-> + AddChainBuildingCertificate(pp_resource(), cert.pp_resource(), + PP_FromBool(trusted))); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + return PP_ToBool(get_interface<PPB_TCPSocket_Private_0_4>()-> + AddChainBuildingCertificate(pp_resource(), cert.pp_resource(), + PP_FromBool(trusted))); + } + return false; +} + +int32_t TCPSocketPrivate::Read(char* buffer, + int32_t bytes_to_read, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + return get_interface<PPB_TCPSocket_Private_0_5>()->Read( + pp_resource(), buffer, bytes_to_read, + callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + return get_interface<PPB_TCPSocket_Private_0_4>()->Read( + pp_resource(), buffer, bytes_to_read, + callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_3>()) { + return get_interface<PPB_TCPSocket_Private_0_3>()->Read( + pp_resource(), buffer, bytes_to_read, + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t TCPSocketPrivate::Write(const char* buffer, + int32_t bytes_to_write, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + return get_interface<PPB_TCPSocket_Private_0_5>()->Write( + pp_resource(), buffer, bytes_to_write, + callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + return get_interface<PPB_TCPSocket_Private_0_4>()->Write( + pp_resource(), buffer, bytes_to_write, + callback.pp_completion_callback()); + } + if (has_interface<PPB_TCPSocket_Private_0_3>()) { + return get_interface<PPB_TCPSocket_Private_0_3>()->Write( + pp_resource(), buffer, bytes_to_write, + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +void TCPSocketPrivate::Disconnect() { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + return get_interface<PPB_TCPSocket_Private_0_5>()->Disconnect( + pp_resource()); + } + if (has_interface<PPB_TCPSocket_Private_0_4>()) { + return get_interface<PPB_TCPSocket_Private_0_4>()->Disconnect( + pp_resource()); + } + if (has_interface<PPB_TCPSocket_Private_0_3>()) { + return get_interface<PPB_TCPSocket_Private_0_3>()->Disconnect( + pp_resource()); + } +} + +int32_t TCPSocketPrivate::SetOption(PP_TCPSocketOption_Private name, + const Var& value, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_Private_0_5>()) { + return get_interface<PPB_TCPSocket_Private_0_5>()->SetOption( + pp_resource(), name, value.pp_var(), callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/tcp_socket_private.h b/chromium/ppapi/cpp/private/tcp_socket_private.h new file mode 100644 index 00000000000..12e435e5895 --- /dev/null +++ b/chromium/ppapi/cpp/private/tcp_socket_private.h @@ -0,0 +1,56 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_TCP_SOCKET_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_TCP_SOCKET_PRIVATE_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/private/ppb_tcp_socket_private.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/private/x509_certificate_private.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class CompletionCallback; +class InstanceHandle; + +class TCPSocketPrivate : public Resource { + public: + explicit TCPSocketPrivate(const InstanceHandle& instance); + + TCPSocketPrivate(PassRef, PP_Resource resource); + + // Returns true if the required interface is available. + static bool IsAvailable(); + + int32_t Connect(const char* host, + uint16_t port, + const CompletionCallback& callback); + int32_t ConnectWithNetAddress(const PP_NetAddress_Private* addr, + const CompletionCallback& callback); + bool GetLocalAddress(PP_NetAddress_Private* local_addr); + bool GetRemoteAddress(PP_NetAddress_Private* remote_addr); + int32_t SSLHandshake(const char* server_name, + uint16_t server_port, + const CompletionCallback& callback); + X509CertificatePrivate GetServerCertificate(); + bool AddChainBuildingCertificate(const X509CertificatePrivate& cert, + bool trusted); + + int32_t Read(char* buffer, + int32_t bytes_to_read, + const CompletionCallback& callback); + int32_t Write(const char* buffer, + int32_t bytes_to_write, + const CompletionCallback& callback); + void Disconnect(); + int32_t SetOption(PP_TCPSocketOption_Private name, + const Var& value, + const CompletionCallback& callback); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_TCP_SOCKET_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/udp_socket_private.cc b/chromium/ppapi/cpp/private/udp_socket_private.cc new file mode 100644 index 00000000000..c100924fc23 --- /dev/null +++ b/chromium/ppapi/cpp/private/udp_socket_private.cc @@ -0,0 +1,137 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/udp_socket_private.h" + +#include "ppapi/c/pp_bool.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_UDPSocket_Private_0_4>() { + return PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4; +} + +template <> const char* interface_name<PPB_UDPSocket_Private_0_3>() { + return PPB_UDPSOCKET_PRIVATE_INTERFACE_0_3; +} + +} // namespace + +UDPSocketPrivate::UDPSocketPrivate(const InstanceHandle& instance) { + if (has_interface<PPB_UDPSocket_Private_0_4>()) { + PassRefFromConstructor(get_interface<PPB_UDPSocket_Private_0_4>()->Create( + instance.pp_instance())); + } else if (has_interface<PPB_UDPSocket_Private_0_3>()) { + PassRefFromConstructor(get_interface<PPB_UDPSocket_Private_0_3>()->Create( + instance.pp_instance())); + } +} + +// static +bool UDPSocketPrivate::IsAvailable() { + return has_interface<PPB_UDPSocket_Private_0_4>() || + has_interface<PPB_UDPSocket_Private_0_3>(); +} + +int32_t UDPSocketPrivate::SetSocketFeature(PP_UDPSocketFeature_Private name, + const Var& value) { + if (has_interface<PPB_UDPSocket_Private_0_4>()) { + return get_interface<PPB_UDPSocket_Private_0_4>()->SetSocketFeature( + pp_resource(), name, value.pp_var()); + } + return PP_ERROR_NOINTERFACE; +} + +int32_t UDPSocketPrivate::Bind(const PP_NetAddress_Private* addr, + const CompletionCallback& callback) { + if (has_interface<PPB_UDPSocket_Private_0_4>()) { + return get_interface<PPB_UDPSocket_Private_0_4>()->Bind( + pp_resource(), addr, callback.pp_completion_callback()); + } + if (has_interface<PPB_UDPSocket_Private_0_3>()) { + return get_interface<PPB_UDPSocket_Private_0_3>()->Bind( + pp_resource(), addr, callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +bool UDPSocketPrivate::GetBoundAddress(PP_NetAddress_Private* addr) { + if (has_interface<PPB_UDPSocket_Private_0_4>()) { + PP_Bool result = + get_interface<PPB_UDPSocket_Private_0_4>()->GetBoundAddress( + pp_resource(), addr); + return PP_ToBool(result); + } + if (has_interface<PPB_UDPSocket_Private_0_3>()) { + PP_Bool result = + get_interface<PPB_UDPSocket_Private_0_3>()->GetBoundAddress( + pp_resource(), addr); + return PP_ToBool(result); + } + return false; +} + +int32_t UDPSocketPrivate::RecvFrom(char* buffer, + int32_t num_bytes, + const CompletionCallback& callback) { + if (has_interface<PPB_UDPSocket_Private_0_4>()) { + return get_interface<PPB_UDPSocket_Private_0_4>()->RecvFrom( + pp_resource(), buffer, num_bytes, callback.pp_completion_callback()); + } + if (has_interface<PPB_UDPSocket_Private_0_3>()) { + return get_interface<PPB_UDPSocket_Private_0_3>()->RecvFrom( + pp_resource(), buffer, num_bytes, callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +bool UDPSocketPrivate::GetRecvFromAddress(PP_NetAddress_Private* addr) { + if (has_interface<PPB_UDPSocket_Private_0_4>()) { + PP_Bool result = + get_interface<PPB_UDPSocket_Private_0_4>()->GetRecvFromAddress( + pp_resource(), addr); + return PP_ToBool(result); + } + if (has_interface<PPB_UDPSocket_Private_0_3>()) { + PP_Bool result = + get_interface<PPB_UDPSocket_Private_0_3>()->GetRecvFromAddress( + pp_resource(), addr); + return PP_ToBool(result); + } + return false; +} + +int32_t UDPSocketPrivate::SendTo(const char* buffer, + int32_t num_bytes, + const PP_NetAddress_Private* addr, + const CompletionCallback& callback) { + if (has_interface<PPB_UDPSocket_Private_0_4>()) { + return get_interface<PPB_UDPSocket_Private_0_4>()->SendTo( + pp_resource(), buffer, num_bytes, addr, + callback.pp_completion_callback()); + } + if (has_interface<PPB_UDPSocket_Private_0_3>()) { + return get_interface<PPB_UDPSocket_Private_0_3>()->SendTo( + pp_resource(), buffer, num_bytes, addr, + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +void UDPSocketPrivate::Close() { + if (has_interface<PPB_UDPSocket_Private_0_4>()) + return get_interface<PPB_UDPSocket_Private_0_4>()->Close(pp_resource()); + if (has_interface<PPB_UDPSocket_Private_0_3>()) + return get_interface<PPB_UDPSocket_Private_0_3>()->Close(pp_resource()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/udp_socket_private.h b/chromium/ppapi/cpp/private/udp_socket_private.h new file mode 100644 index 00000000000..34e06a906a0 --- /dev/null +++ b/chromium/ppapi/cpp/private/udp_socket_private.h @@ -0,0 +1,42 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_UDP_SOCKET_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_UDP_SOCKET_PRIVATE_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/private/ppb_udp_socket_private.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class CompletionCallback; +class InstanceHandle; +class Var; + +class UDPSocketPrivate : public Resource { + public: + explicit UDPSocketPrivate(const InstanceHandle& instance); + + // Returns true if the required interface is available. + static bool IsAvailable(); + + int32_t SetSocketFeature(PP_UDPSocketFeature_Private name, const Var& value); + int32_t Bind(const PP_NetAddress_Private* addr, + const CompletionCallback& callback); + bool GetBoundAddress(PP_NetAddress_Private* addr); + int32_t RecvFrom(char* buffer, + int32_t num_bytes, + const CompletionCallback& callback); + bool GetRecvFromAddress(PP_NetAddress_Private* addr); + int32_t SendTo(const char* buffer, + int32_t num_bytes, + const PP_NetAddress_Private* addr, + const CompletionCallback& callback); + void Close(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_UDP_SOCKET_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/var_private.cc b/chromium/ppapi/cpp/private/var_private.cc new file mode 100644 index 00000000000..ff61226d582 --- /dev/null +++ b/chromium/ppapi/cpp/private/var_private.cc @@ -0,0 +1,190 @@ +// Copyright (c) 2011 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 "ppapi/cpp/private/var_private.h" + +#include "ppapi/c/dev/ppb_memory_dev.h" +#include "ppapi/c/dev/ppb_var_deprecated.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/private/instance_private.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/dev/scriptable_object_deprecated.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Var_Deprecated>() { + return PPB_VAR_DEPRECATED_INTERFACE; +} + +} // namespace + +using namespace deprecated; + +VarPrivate::VarPrivate(const InstanceHandle& instance, + ScriptableObject* object) { + if (has_interface<PPB_Var_Deprecated>()) { + var_ = get_interface<PPB_Var_Deprecated>()->CreateObject( + instance.pp_instance(), object->GetClass(), object); + } else { + var_.type = PP_VARTYPE_NULL; + var_.padding = 0; + } + is_managed_ = true; +} + +ScriptableObject* VarPrivate::AsScriptableObject() const { + if (!is_object()) { + PP_NOTREACHED(); + } else if (has_interface<PPB_Var_Deprecated>()) { + void* object = NULL; + if (get_interface<PPB_Var_Deprecated>()->IsInstanceOf( + var_, ScriptableObject::GetClass(), &object)) { + return reinterpret_cast<ScriptableObject*>(object); + } + } + return NULL; +} + +bool VarPrivate::HasProperty(const Var& name, Var* exception) const { + if (!has_interface<PPB_Var_Deprecated>()) + return false; + return get_interface<PPB_Var_Deprecated>()->HasProperty( + var_, name.pp_var(), OutException(exception).get()); +} + +bool VarPrivate::HasMethod(const Var& name, Var* exception) const { + if (!has_interface<PPB_Var_Deprecated>()) + return false; + return get_interface<PPB_Var_Deprecated>()->HasMethod( + var_, name.pp_var(), OutException(exception).get()); +} + +VarPrivate VarPrivate::GetProperty(const Var& name, Var* exception) const { + if (!has_interface<PPB_Var_Deprecated>()) + return Var(); + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->GetProperty( + var_, name.pp_var(), OutException(exception).get())); +} + +void VarPrivate::GetAllPropertyNames(std::vector<Var>* properties, + Var* exception) const { + if (!has_interface<PPB_Var_Deprecated>()) + return; + PP_Var* props = NULL; + uint32_t prop_count = 0; + get_interface<PPB_Var_Deprecated>()->GetAllPropertyNames( + var_, &prop_count, &props, OutException(exception).get()); + if (!prop_count) + return; + properties->resize(prop_count); + for (uint32_t i = 0; i < prop_count; ++i) { + Var temp(PassRef(), props[i]); + (*properties)[i] = temp; + } + const PPB_Memory_Dev* memory_if = static_cast<const PPB_Memory_Dev*>( + pp::Module::Get()->GetBrowserInterface(PPB_MEMORY_DEV_INTERFACE)); + memory_if->MemFree(props); +} + +void VarPrivate::SetProperty(const Var& name, const Var& value, + Var* exception) { + if (!has_interface<PPB_Var_Deprecated>()) + return; + get_interface<PPB_Var_Deprecated>()->SetProperty( + var_, name.pp_var(), value.pp_var(), OutException(exception).get()); +} + +void VarPrivate::RemoveProperty(const Var& name, Var* exception) { + if (!has_interface<PPB_Var_Deprecated>()) + return; + get_interface<PPB_Var_Deprecated>()->RemoveProperty( + var_, name.pp_var(), OutException(exception).get()); +} + +VarPrivate VarPrivate::Call(const Var& method_name, uint32_t argc, Var* argv, + Var* exception) { + if (!has_interface<PPB_Var_Deprecated>()) + return Var(); + if (argc > 0) { + std::vector<PP_Var> args; + args.reserve(argc); + for (size_t i = 0; i < argc; i++) + args.push_back(argv[i].pp_var()); + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( + var_, method_name.pp_var(), argc, &args[0], + OutException(exception).get())); + } else { + // Don't try to get the address of a vector if it's empty. + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( + var_, method_name.pp_var(), 0, NULL, + OutException(exception).get())); + } +} + +VarPrivate VarPrivate::Construct(uint32_t argc, Var* argv, + Var* exception) const { + if (!has_interface<PPB_Var_Deprecated>()) + return Var(); + if (argc > 0) { + std::vector<PP_Var> args; + args.reserve(argc); + for (size_t i = 0; i < argc; i++) + args.push_back(argv[i].pp_var()); + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Construct( + var_, argc, &args[0], OutException(exception).get())); + } else { + // Don't try to get the address of a vector if it's empty. + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Construct( + var_, 0, NULL, OutException(exception).get())); + } +} + +VarPrivate VarPrivate::Call(const Var& method_name, Var* exception) { + if (!has_interface<PPB_Var_Deprecated>()) + return Var(); + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( + var_, method_name.pp_var(), 0, NULL, OutException(exception).get())); +} + +VarPrivate VarPrivate::Call(const Var& method_name, const Var& arg1, + Var* exception) { + if (!has_interface<PPB_Var_Deprecated>()) + return Var(); + PP_Var args[1] = {arg1.pp_var()}; + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( + var_, method_name.pp_var(), 1, args, OutException(exception).get())); +} + +VarPrivate VarPrivate::Call(const Var& method_name, const Var& arg1, + const Var& arg2, Var* exception) { + if (!has_interface<PPB_Var_Deprecated>()) + return Var(); + PP_Var args[2] = {arg1.pp_var(), arg2.pp_var()}; + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( + var_, method_name.pp_var(), 2, args, OutException(exception).get())); +} + +VarPrivate VarPrivate::Call(const Var& method_name, const Var& arg1, + const Var& arg2, const Var& arg3, Var* exception) { + if (!has_interface<PPB_Var_Deprecated>()) + return Var(); + PP_Var args[3] = {arg1.pp_var(), arg2.pp_var(), arg3.pp_var()}; + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( + var_, method_name.pp_var(), 3, args, OutException(exception).get())); +} + +VarPrivate VarPrivate::Call(const Var& method_name, const Var& arg1, + const Var& arg2, const Var& arg3, const Var& arg4, + Var* exception) { + if (!has_interface<PPB_Var_Deprecated>()) + return Var(); + PP_Var args[4] = {arg1.pp_var(), arg2.pp_var(), arg3.pp_var(), arg4.pp_var()}; + return Var(PassRef(), get_interface<PPB_Var_Deprecated>()->Call( + var_, method_name.pp_var(), 4, args, OutException(exception).get())); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/var_private.h b/chromium/ppapi/cpp/private/var_private.h new file mode 100644 index 00000000000..7cc0e31dccf --- /dev/null +++ b/chromium/ppapi/cpp/private/var_private.h @@ -0,0 +1,124 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_PRIVATE_VAR_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_VAR_PRIVATE_H_ + +#include "ppapi/cpp/var.h" + +namespace pp { + +class InstanceHandle; + +namespace deprecated { +class ScriptableObject; +} + +// VarPrivate is a version of Var that exposes the private scripting API. +// It's designed to be mostly interchangeable with Var since most callers will +// be dealing with Vars from various places. +class VarPrivate : public Var { + public: + VarPrivate() : Var() {} + VarPrivate(Null) : Var(Null()) {} + VarPrivate(bool b) : Var(b) {} + VarPrivate(int32_t i) : Var(i) {} + VarPrivate(double d) : Var(d) {} + VarPrivate(const char* utf8_str) : Var(utf8_str) {} + VarPrivate(const std::string& utf8_str) : Var(utf8_str) {} + VarPrivate(PassRef, PP_Var var) : Var(PassRef(), var) {} + VarPrivate(DontManage, PP_Var var) : Var(DontManage(), var) {} + VarPrivate(const InstanceHandle& instance, + deprecated::ScriptableObject* object); + VarPrivate(const Var& other) : Var(other) {} + + virtual ~VarPrivate() {} + + // This assumes the object is of type object. If it's not, it will assert in + // debug mode. If it is not an object or not a ScriptableObject type, returns + // NULL. + deprecated::ScriptableObject* AsScriptableObject() const; + + bool HasProperty(const Var& name, Var* exception = NULL) const; + bool HasMethod(const Var& name, Var* exception = NULL) const; + VarPrivate GetProperty(const Var& name, Var* exception = NULL) const; + void GetAllPropertyNames(std::vector<Var>* properties, + Var* exception = NULL) const; + void SetProperty(const Var& name, const Var& value, Var* exception = NULL); + void RemoveProperty(const Var& name, Var* exception = NULL); + VarPrivate Call(const Var& method_name, uint32_t argc, Var* argv, + Var* exception = NULL); + VarPrivate Construct(uint32_t argc, Var* argv, Var* exception = NULL) const; + + // Convenience functions for calling functions with small # of args. + VarPrivate Call(const Var& method_name, Var* exception = NULL); + VarPrivate Call(const Var& method_name, const Var& arg1, + Var* exception = NULL); + VarPrivate Call(const Var& method_name, const Var& arg1, const Var& arg2, + Var* exception = NULL); + VarPrivate Call(const Var& method_name, const Var& arg1, const Var& arg2, + const Var& arg3, Var* exception = NULL); + VarPrivate Call(const Var& method_name, const Var& arg1, const Var& arg2, + const Var& arg3, const Var& arg4, Var* exception = NULL); + + // For use when calling the raw C PPAPI when using the C++ Var as a possibly + // NULL exception. This will handle getting the address of the internal value + // out if it's non-NULL and fixing up the reference count. + // + // Danger: this will only work for things with exception semantics, i.e. that + // the value will not be changed if it's a non-undefined exception. Otherwise, + // this class will mess up the refcounting. + // + // This is a bit subtle: + // - If NULL is passed, we return NULL from get() and do nothing. + // + // - If a undefined value is passed, we return the address of a undefined var + // from get and have the output value take ownership of that var. + // + // - If a non-undefined value is passed, we return the address of that var + // from get, and nothing else should change. + // + // Example: + // void FooBar(a, b, Var* exception = NULL) { + // foo_interface->Bar(a, b, VarPrivate::OutException(exception).get()); + // } + class OutException { + public: + OutException(Var* v) + : output_(v), + originally_had_exception_(v && !v->is_undefined()) { + if (output_) { + temp_ = output_->pp_var(); + } else { + temp_.padding = 0; + temp_.type = PP_VARTYPE_UNDEFINED; + } + } + ~OutException() { + if (output_ && !originally_had_exception_) + *output_ = Var(PassRef(), temp_); + } + + PP_Var* get() { + if (output_) + return &temp_; + return NULL; + } + + private: + Var* output_; + bool originally_had_exception_; + PP_Var temp_; + }; + + private: + // Prevent an arbitrary pointer argument from being implicitly converted to + // a bool at Var construction. If somebody makes such a mistake, (s)he will + // get a compilation error. + VarPrivate(void* non_scriptable_object_pointer); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_VAR_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/video_destination_private.cc b/chromium/ppapi/cpp/private/video_destination_private.cc new file mode 100644 index 00000000000..5233b5f09ee --- /dev/null +++ b/chromium/ppapi/cpp/private/video_destination_private.cc @@ -0,0 +1,76 @@ +// Copyright (c) 2013 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 "ppapi/cpp/private/video_destination_private.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/private/ppb_video_destination_private.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/private/video_frame_private.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_VideoDestination_Private_0_1>() { + return PPB_VIDEODESTINATION_PRIVATE_INTERFACE_0_1; +} + +} // namespace + +VideoDestination_Private::VideoDestination_Private() { +} + +VideoDestination_Private::VideoDestination_Private( + const InstanceHandle& instance) { + if (!has_interface<PPB_VideoDestination_Private_0_1>()) + return; + PassRefFromConstructor( + get_interface<PPB_VideoDestination_Private_0_1>()->Create( + instance.pp_instance())); +} + +VideoDestination_Private::VideoDestination_Private( + const VideoDestination_Private& other) + : Resource(other) { +} + +VideoDestination_Private::VideoDestination_Private(PassRef, + PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +int32_t VideoDestination_Private::Open(const Var& stream_url, + const CompletionCallback& cc) { + if (has_interface<PPB_VideoDestination_Private_0_1>()) { + int32_t result = + get_interface<PPB_VideoDestination_Private_0_1>()->Open( + pp_resource(), + stream_url.pp_var(), + cc.pp_completion_callback()); + return result; + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t VideoDestination_Private::PutFrame( + const VideoFrame_Private& frame) { + if (has_interface<PPB_VideoDestination_Private_0_1>()) { + return get_interface<PPB_VideoDestination_Private_0_1>()->PutFrame( + pp_resource(), + &frame.pp_video_frame()); + } + return PP_ERROR_NOINTERFACE; +} + +void VideoDestination_Private::Close() { + if (has_interface<PPB_VideoDestination_Private_0_1>()) { + get_interface<PPB_VideoDestination_Private_0_1>()->Close(pp_resource()); + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/video_destination_private.h b/chromium/ppapi/cpp/private/video_destination_private.h new file mode 100644 index 00000000000..a9364850901 --- /dev/null +++ b/chromium/ppapi/cpp/private/video_destination_private.h @@ -0,0 +1,87 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_PRIVATE_VIDEO_DESTINATION_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_VIDEO_DESTINATION_PRIVATE_H_ + +#include <string> + +#include "ppapi/c/pp_time.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the <code>PPB_VideoDestination_Private</code> interface +/// for a video destination resource, which sends video frames to a MediaStream +/// video track in the browser. + +namespace pp { + +class InstanceHandle; +class VideoFrame_Private; + +/// The <code>VideoDestination_Private</code> class contains methods for +/// creating video destination resources and using them to send video frames to +/// a MediaStream video track in the browser. +class VideoDestination_Private : public Resource { + public: + /// Default constructor for creating a <code>VideoDestination_Private</code> + /// object. + VideoDestination_Private(); + + /// Constructor for creating a <code>VideoDestination_Private</code> for an + /// instance. + explicit VideoDestination_Private(const InstanceHandle& instance); + + /// The copy constructor for <code>VideoDestination_Private</code>. + /// + /// @param[in] other A reference to a <code>VideoDestination_Private</code>. + VideoDestination_Private(const VideoDestination_Private& other); + + /// A constructor used when you have received a PP_Resource as a return + /// value that has had its reference count incremented for you. + /// + /// @param[in] resource A PP_Resource corresponding to a video destination. + VideoDestination_Private(PassRef, PP_Resource resource); + + /// Opens a video destination for putting frames. + /// + /// @param[in] stream_url A <code>Var</code> string holding a URL identifying + /// a MediaStream. + /// @param[in] callback A <code>CompletionCallback</code> to be + /// called upon completion of Open(). + /// + /// @return An int32_t containing a result code from <code>pp_errors.h</code>. + /// Returns PP_ERROR_BADRESOURCE if destination isn't a valid video + /// destination. + /// Returns PP_ERROR_INPROGRESS if destination is already open. + /// Returns PP_ERROR_FAILED if the MediaStream doesn't exist or if there is + /// some other browser error. + int32_t Open(const Var& stream_url, const CompletionCallback& cc); + + /// Puts a frame to the video destination. + /// + /// After this call, you should take care to release your references to the + /// image embedded in the video frame. If you paint to the image after + /// PutFrame(), there is the possibility of artifacts because the browser may + /// still be copying the frame to the stream. + /// + /// @param[in] frame A <code>VideoFrame_Private</code> holding the video + /// frame to send to the destination. + /// + /// @return An int32_t containing a result code from <code>pp_errors.h</code>. + /// Returns PP_ERROR_BADRESOURCE if destination isn't a valid video + /// destination. + /// Returns PP_ERROR_FAILED if destination is not open, if the video frame has + /// an invalid image data resource, or if some other browser error occurs. + int32_t PutFrame(const VideoFrame_Private& frame); + + /// Closes the video destination. + void Close(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_VIDEO_DESTINATION_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/video_frame_private.cc b/chromium/ppapi/cpp/private/video_frame_private.cc new file mode 100644 index 00000000000..9976647d5b3 --- /dev/null +++ b/chromium/ppapi/cpp/private/video_frame_private.cc @@ -0,0 +1,49 @@ +// Copyright (c) 2013 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 "ppapi/cpp/private/video_frame_private.h" + +namespace pp { + +VideoFrame_Private::VideoFrame_Private() + : video_frame_() { + video_frame_.image_data = image_data_.pp_resource(); +} + +VideoFrame_Private::VideoFrame_Private(const ImageData& image_data, + PP_TimeTicks timestamp) + : image_data_(image_data), video_frame_() { + video_frame_.timestamp = timestamp; + video_frame_.image_data = image_data_.pp_resource(); +} + +VideoFrame_Private::VideoFrame_Private( + PassRef, + const PP_VideoFrame_Private& pp_video_frame) + : video_frame_(pp_video_frame) { + // Take over the image_data resource in the frame. + image_data_ = ImageData(PASS_REF, video_frame_.image_data); +} + +VideoFrame_Private::VideoFrame_Private(const VideoFrame_Private& other) + : video_frame_() { + set_image_data(other.image_data()); + set_timestamp(other.timestamp()); +} + +VideoFrame_Private::~VideoFrame_Private() { +} + +VideoFrame_Private& VideoFrame_Private::operator=( + const VideoFrame_Private& other) { + if (this == &other) + return *this; + + set_image_data(other.image_data()); + set_timestamp(other.timestamp()); + + return *this; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/video_frame_private.h b/chromium/ppapi/cpp/private/video_frame_private.h new file mode 100644 index 00000000000..7413876e7d6 --- /dev/null +++ b/chromium/ppapi/cpp/private/video_frame_private.h @@ -0,0 +1,103 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_PRIVATE_VIDEO_FRAME_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_VIDEO_FRAME_PRIVATE_H_ + +#include <string.h> + +#include "ppapi/c/pp_time.h" +#include "ppapi/c/private/pp_video_frame_private.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/pass_ref.h" + +/// @file +/// This file defines the struct used to hold a video frame. + +namespace pp { + +/// The <code>PP_VideoFrame_Private</code> struct represents a video frame. +/// Video sources and destinations use frames to transfer video to and from +/// the browser. +class VideoFrame_Private { + public: + /// Default constructor for creating a <code>VideoFrame_Private</code> object. + VideoFrame_Private(); + + /// Constructor that takes an existing <code>PP_VideoFrame_Private</code> + /// structure. The 'image_data' PP_Resource field in the structure will be + /// managed by this instance. + VideoFrame_Private(PassRef, const PP_VideoFrame_Private& pp_video_frame); + + /// Constructor that takes an existing <code>ImageData</code> instance and + /// a timestamp. + VideoFrame_Private(const ImageData& image_data, PP_TimeTicks timestamp); + + /// The copy constructor for <code>VideoFrame_Private</code>. + /// + /// @param[in] other A reference to a <code>VideoFrame_Private</code>. + VideoFrame_Private(const VideoFrame_Private& other); + + ~VideoFrame_Private(); + + /// The assignment operator for <code>VideoFrame_Private</code>. + /// + /// @param[in] other A reference to a <code>VideoFrame_Private</code>. + VideoFrame_Private& operator=(const VideoFrame_Private& other); + + const PP_VideoFrame_Private& pp_video_frame() const { + return video_frame_; + } + + ImageData image_data() const { + return image_data_; + } + void set_image_data(const ImageData& image_data) { + image_data_ = image_data; + // The assignment above manages the underlying PP_Resources. Copy the new + // one into our internal video frame struct. + video_frame_.image_data = image_data_.pp_resource(); + } + + PP_TimeTicks timestamp() const { return video_frame_.timestamp; } + void set_timestamp(PP_TimeTicks timestamp) { + video_frame_.timestamp = timestamp; + } + + private: + ImageData image_data_; // This manages the PP_Resource in video_frame_. + PP_VideoFrame_Private video_frame_; +}; + +namespace internal { + +// A specialization of CallbackOutputTraits to provide the callback system the +// information on how to handle pp::VideoFrame_Private. This converts +// PP_VideoFrame_Private to pp::VideoFrame_Private when passing to the plugin, +// and specifically manages the PP_Resource embedded in the video_frame_ field. +template<> +struct CallbackOutputTraits<pp::VideoFrame_Private> { + typedef PP_VideoFrame_Private* APIArgType; + typedef PP_VideoFrame_Private StorageType; + + static inline APIArgType StorageToAPIArg(StorageType& t) { + return &t; + } + + static inline pp::VideoFrame_Private StorageToPluginArg(StorageType& t) { + return pp::VideoFrame_Private(PASS_REF, t); + } + + static inline void Initialize(StorageType* t) { + VideoFrame_Private dummy; + *t = dummy.pp_video_frame(); + } +}; + +} // namespace internal + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_VIDEO_FRAME_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/video_source_private.cc b/chromium/ppapi/cpp/private/video_source_private.cc new file mode 100644 index 00000000000..264c001103c --- /dev/null +++ b/chromium/ppapi/cpp/private/video_source_private.cc @@ -0,0 +1,71 @@ +// Copyright (c) 2013 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 "ppapi/cpp/private/video_source_private.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/private/ppb_video_source_private.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/private/video_frame_private.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_VideoSource_Private_0_1>() { + return PPB_VIDEOSOURCE_PRIVATE_INTERFACE_0_1; +} + +} // namespace + +VideoSource_Private::VideoSource_Private() { +} + +VideoSource_Private::VideoSource_Private(const InstanceHandle& instance) { + if (!has_interface<PPB_VideoSource_Private_0_1>()) + return; + PassRefFromConstructor(get_interface<PPB_VideoSource_Private_0_1>()->Create( + instance.pp_instance())); +} + +VideoSource_Private::VideoSource_Private(const VideoSource_Private& other) + : Resource(other) { +} + +VideoSource_Private::VideoSource_Private(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +int32_t VideoSource_Private::Open(const Var& stream_url, + const CompletionCallback& cc) { + if (has_interface<PPB_VideoSource_Private_0_1>()) { + int32_t result = + get_interface<PPB_VideoSource_Private_0_1>()->Open( + pp_resource(), + stream_url.pp_var(), cc.pp_completion_callback()); + return result; + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t VideoSource_Private::GetFrame( + const CompletionCallbackWithOutput<VideoFrame_Private>& cc) { + if (has_interface<PPB_VideoSource_Private_0_1>()) { + return get_interface<PPB_VideoSource_Private_0_1>()->GetFrame( + pp_resource(), + cc.output(), cc.pp_completion_callback()); + } + return cc.MayForce(PP_ERROR_NOINTERFACE); +} + +void VideoSource_Private::Close() { + if (has_interface<PPB_VideoSource_Private_0_1>()) { + get_interface<PPB_VideoSource_Private_0_1>()->Close(pp_resource()); + } +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/video_source_private.h b/chromium/ppapi/cpp/private/video_source_private.h new file mode 100644 index 00000000000..3d919bfd9ed --- /dev/null +++ b/chromium/ppapi/cpp/private/video_source_private.h @@ -0,0 +1,84 @@ +// Copyright (c) 2013 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. + +#ifndef PPAPI_CPP_PRIVATE_VIDEO_SOURCE_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_VIDEO_SOURCE_PRIVATE_H_ + +#include <string> + +#include "ppapi/c/pp_time.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the <code>PPB_VideoSource_Private</code> interface for a +/// video source resource, which receives video frames from a MediaStream video +/// track in the browser. + +namespace pp { + +class InstanceHandle; +class VideoFrame_Private; + +/// The <code>VideoSource_Private</code> class contains methods for creating +/// video source resources and using them to receive video frames from a +/// MediaStream video track in the browser. +class VideoSource_Private : public Resource { + public: + /// Default constructor for creating a <code>VideoSource_Private</code> + /// object. + VideoSource_Private(); + + /// Constructor for creating a <code>VideoSource_Private</code> for an + /// instance. + explicit VideoSource_Private(const InstanceHandle& instance); + + /// The copy constructor for <code>VideoSource_Private</code>. + /// + /// @param[in] other A reference to a <code>VideoSource_Private</code>. + VideoSource_Private(const VideoSource_Private& other); + + /// A constructor used when you have received a PP_Resource as a return + /// value that has had its reference count incremented for you. + /// + /// @param[in] resource A PP_Resource corresponding to a video source. + VideoSource_Private(PassRef, PP_Resource resource); + + /// Opens a video source for getting frames. + /// + /// @param[in] stream_url A <code>Var</code> string holding a URL identifying + /// a MediaStream. + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion of Open(). + /// + /// @return An int32_t containing a result code from <code>pp_errors.h</code>. + /// Returns PP_ERROR_BADRESOURCE if source isn't a valid video source. + /// Returns PP_ERROR_INPROGRESS if source is already open. + /// Returns PP_ERROR_FAILED if the MediaStream doesn't exist or if there is + /// some other browser error. + int32_t Open(const Var& stream_url, + const CompletionCallback& cc); + + /// Gets a frame from the video source. + /// + /// @param[out] frame A <code>VideoFrame_Private</code> to hold a video + /// frame from the source. + /// @param[in] callback A <code>CompletionCallbackWithOutput</code> to be + /// called upon completion of ReceiveFrame(). + /// + /// @return An int32_t containing a result code from <code>pp_errors.h</code>. + /// Returns PP_ERROR_BADRESOURCE if source isn't a valid video source. + /// Returns PP_ERROR_FAILED if the source is not open, or if some other + /// browser error occurs. + int32_t GetFrame( + const CompletionCallbackWithOutput<VideoFrame_Private>& cc); + + /// Closes the video source. + void Close(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_VIDEO_SOURCE_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/private/x509_certificate_private.cc b/chromium/ppapi/cpp/private/x509_certificate_private.cc new file mode 100644 index 00000000000..ec242b79533 --- /dev/null +++ b/chromium/ppapi/cpp/private/x509_certificate_private.cc @@ -0,0 +1,58 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/private/x509_certificate_private.h" + +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_X509Certificate_Private_0_1>() { + return PPB_X509CERTIFICATE_PRIVATE_INTERFACE_0_1; +} + +} // namespace + +X509CertificatePrivate::X509CertificatePrivate() : Resource() {} + +X509CertificatePrivate::X509CertificatePrivate(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +X509CertificatePrivate::X509CertificatePrivate(const InstanceHandle& instance) { + if (has_interface<PPB_X509Certificate_Private_0_1>()) { + PassRefFromConstructor(get_interface<PPB_X509Certificate_Private_0_1>()-> + Create(instance.pp_instance())); + } +} + +// static +bool X509CertificatePrivate::IsAvailable() { + return has_interface<PPB_X509Certificate_Private_0_1>(); +} + +bool X509CertificatePrivate::Initialize(const char* bytes, uint32_t length) { + if (!has_interface<PPB_X509Certificate_Private_0_1>()) + return false; + PP_Bool result = get_interface<PPB_X509Certificate_Private_0_1>()->Initialize( + pp_resource(), + bytes, + length); + return PP_ToBool(result); +} + +Var X509CertificatePrivate::GetField( + PP_X509Certificate_Private_Field field) const { + if (!has_interface<PPB_X509Certificate_Private_0_1>()) + return Var(); + return Var(PassRef(), + get_interface<PPB_X509Certificate_Private_0_1>()->GetField(pp_resource(), + field)); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/private/x509_certificate_private.h b/chromium/ppapi/cpp/private/x509_certificate_private.h new file mode 100644 index 00000000000..981f581439c --- /dev/null +++ b/chromium/ppapi/cpp/private/x509_certificate_private.h @@ -0,0 +1,35 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_PRIVATE_X509_CERTIFICATE_PRIVATE_H_ +#define PPAPI_CPP_PRIVATE_X509_CERTIFICATE_PRIVATE_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/c/private/ppb_x509_certificate_private.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class Var; + +class X509CertificatePrivate : public Resource { + public: + // Creates an is_null() object. + X509CertificatePrivate(); + X509CertificatePrivate(PassRef, PP_Resource resource); + explicit X509CertificatePrivate(const InstanceHandle& instance); + + // Returns true if the required interface is available. + static bool IsAvailable(); + + // Creates a new certificate from a DER-encoded representation. Returns true + // if the certificate was successfully created. + bool Initialize(const char* bytes, uint32_t length); + // Returns the specified field as a |Var|. + Var GetField(PP_X509Certificate_Private_Field field) const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_PRIVATE_X509_CERTIFICATE_PRIVATE_H_ diff --git a/chromium/ppapi/cpp/rect.cc b/chromium/ppapi/cpp/rect.cc new file mode 100644 index 00000000000..1e9ff05236b --- /dev/null +++ b/chromium/ppapi/cpp/rect.cc @@ -0,0 +1,130 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/rect.h" + +#include <algorithm> + +namespace { + +void AdjustAlongAxis(int32_t dst_origin, int32_t dst_size, + int32_t* origin, int32_t* size) { + if (*origin < dst_origin) { + *origin = dst_origin; + *size = std::min(dst_size, *size); + } else { + *size = std::min(dst_size, *size); + *origin = std::min(dst_origin + dst_size, *origin + *size) - *size; + } +} + +} // namespace + +namespace pp { + +void Rect::Inset(int32_t left, int32_t top, int32_t right, int32_t bottom) { + Offset(left, top); + set_width(std::max<int32_t>(width() - left - right, 0)); + set_height(std::max<int32_t>(height() - top - bottom, 0)); +} + +void Rect::Offset(int32_t horizontal, int32_t vertical) { + rect_.point.x += horizontal; + rect_.point.y += vertical; +} + +bool Rect::Contains(int32_t point_x, int32_t point_y) const { + return (point_x >= x()) && (point_x < right()) && + (point_y >= y()) && (point_y < bottom()); +} + +bool Rect::Contains(const Rect& rect) const { + return (rect.x() >= x() && rect.right() <= right() && + rect.y() >= y() && rect.bottom() <= bottom()); +} + +bool Rect::Intersects(const Rect& rect) const { + return !(rect.x() >= right() || rect.right() <= x() || + rect.y() >= bottom() || rect.bottom() <= y()); +} + +Rect Rect::Intersect(const Rect& rect) const { + int32_t rx = std::max(x(), rect.x()); + int32_t ry = std::max(y(), rect.y()); + int32_t rr = std::min(right(), rect.right()); + int32_t rb = std::min(bottom(), rect.bottom()); + + if (rx >= rr || ry >= rb) + rx = ry = rr = rb = 0; // non-intersecting + + return Rect(rx, ry, rr - rx, rb - ry); +} + +Rect Rect::Union(const Rect& rect) const { + // special case empty rects... + if (IsEmpty()) + return rect; + if (rect.IsEmpty()) + return *this; + + int32_t rx = std::min(x(), rect.x()); + int32_t ry = std::min(y(), rect.y()); + int32_t rr = std::max(right(), rect.right()); + int32_t rb = std::max(bottom(), rect.bottom()); + + return Rect(rx, ry, rr - rx, rb - ry); +} + +Rect Rect::Subtract(const Rect& rect) const { + // boundary cases: + if (!Intersects(rect)) + return *this; + if (rect.Contains(*this)) + return Rect(); + + int32_t rx = x(); + int32_t ry = y(); + int32_t rr = right(); + int32_t rb = bottom(); + + if (rect.y() <= y() && rect.bottom() >= bottom()) { + // complete intersection in the y-direction + if (rect.x() <= x()) { + rx = rect.right(); + } else { + rr = rect.x(); + } + } else if (rect.x() <= x() && rect.right() >= right()) { + // complete intersection in the x-direction + if (rect.y() <= y()) { + ry = rect.bottom(); + } else { + rb = rect.y(); + } + } + return Rect(rx, ry, rr - rx, rb - ry); +} + +Rect Rect::AdjustToFit(const Rect& rect) const { + int32_t new_x = x(); + int32_t new_y = y(); + int32_t new_width = width(); + int32_t new_height = height(); + AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width); + AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height); + return Rect(new_x, new_y, new_width, new_height); +} + +Point Rect::CenterPoint() const { + return Point(x() + (width() + 1) / 2, y() + (height() + 1) / 2); +} + +bool Rect::SharesEdgeWith(const Rect& rect) const { + return (y() == rect.y() && height() == rect.height() && + (x() == rect.right() || right() == rect.x())) || + (x() == rect.x() && width() == rect.width() && + (y() == rect.bottom() || bottom() == rect.y())); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/rect.h b/chromium/ppapi/cpp/rect.h new file mode 100644 index 00000000000..b47226bd707 --- /dev/null +++ b/chromium/ppapi/cpp/rect.h @@ -0,0 +1,427 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_RECT_H_ +#define PPAPI_CPP_RECT_H_ + +#include "ppapi/c/pp_rect.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/size.h" + +/// @file +/// This file defines the APIs for creating a 2 dimensional rectangle. + +namespace pp { + +/// A 2 dimensional rectangle. A rectangle is represented by x and y (which +/// identifies the upper-left corner of the rectangle), width, and height. +class Rect { + public: + + /// The default constructor. Creates a <code>Rect</code> in the upper-left + /// at 0,0 with height and width of 0. + Rect() { + rect_.point.x = 0; + rect_.point.y = 0; + rect_.size.width = 0; + rect_.size.height = 0; + } + + /// A constructor accepting a reference to a <code>PP_Rect and</code> + /// converting the <code>PP_Rect</code> to a <code>Rect</code>. This is an + /// implicit conversion constructor. + /// + /// @param[in] rect A <code>PP_Rect</code>. + Rect(const PP_Rect& rect) { // Implicit. + set_x(rect.point.x); + set_y(rect.point.y); + set_width(rect.size.width); + set_height(rect.size.height); + } + + /// A constructor accepting two int32_t values for width and height and + /// converting them to a <code>Rect</code> in the upper-left starting + /// coordinate of 0,0. + /// + /// @param[in] w An int32_t value representing a width. + /// @param[in] h An int32_t value representing a height. + Rect(int32_t w, int32_t h) { + set_x(0); + set_y(0); + set_width(w); + set_height(h); + } + + /// A constructor accepting four int32_t values for width, height, x, and y. + /// + /// @param[in] x An int32_t value representing a horizontal coordinate + /// of a point, starting with 0 as the left-most coordinate. + /// @param[in] y An int32_t value representing a vertical coordinate + /// of a point, starting with 0 as the top-most coordinate. + /// @param[in] w An int32_t value representing a width. + /// @param[in] h An int32_t value representing a height. + Rect(int32_t x, int32_t y, int32_t w, int32_t h) { + set_x(x); + set_y(y); + set_width(w); + set_height(h); + } + + /// A constructor accepting a pointer to a Size and converting the + /// <code>Size</code> to a <code>Rect</code> in the upper-left starting + /// coordinate of 0,0. + /// + /// @param[in] s A pointer to a <code>Size</code>. + explicit Rect(const Size& s) { + set_x(0); + set_y(0); + set_size(s); + } + + /// A constructor accepting a pointer to a <code>Point</code> representing + /// the origin of the rectangle and a pointer to a <code>Size</code> + /// representing the height and width. + /// + /// @param[in] origin A pointer to a <code>Point</code> representing the + /// upper-left starting coordinate. + /// @param[in] size A pointer to a <code>Size</code> representing the height + /// and width. + Rect(const Point& origin, const Size& size) { + set_point(origin); + set_size(size); + } + + /// Destructor. + ~Rect() { + } + + /// PP_Rect() allows implicit conversion of a <code>Rect</code> to a + /// <code>PP_Rect</code>. + /// + /// @return A <code>Point</code>. + operator PP_Rect() const { + return rect_; + } + + /// Getter function for returning the internal <code>PP_Rect</code> struct. + /// + /// @return A const reference to the internal <code>PP_Rect</code> struct. + const PP_Rect& pp_rect() const { + return rect_; + } + + /// Getter function for returning the internal <code>PP_Rect</code> struct. + /// + /// @return A mutable reference to the <code>PP_Rect</code> struct. + PP_Rect& pp_rect() { + return rect_; + } + + + /// Getter function for returning the value of x. + /// + /// @return The value of x for this <code>Point</code>. + int32_t x() const { + return rect_.point.x; + } + + /// Setter function for setting the value of x. + /// + /// @param[in] in_x A new x value. + void set_x(int32_t in_x) { + rect_.point.x = in_x; + } + + /// Getter function for returning the value of y. + /// + /// @return The value of y for this <code>Point</code>. + int32_t y() const { + return rect_.point.y; + } + + /// Setter function for setting the value of y. + /// + /// @param[in] in_y A new y value. + void set_y(int32_t in_y) { + rect_.point.y = in_y; + } + + /// Getter function for returning the value of width. + /// + /// @return The value of width for this <code>Rect</code>. + int32_t width() const { + return rect_.size.width; + } + + /// Setter function for setting the value of width. + /// + /// @param[in] w A new width value. + void set_width(int32_t w) { + if (w < 0) { + PP_DCHECK(w >= 0); + w = 0; + } + rect_.size.width = w; + } + + /// Getter function for returning the value of height. + /// + /// @return The value of height for this <code>Rect</code>. + int32_t height() const { + return rect_.size.height; + } + + /// Setter function for setting the value of height. + /// + /// @param[in] h A new width height. + void set_height(int32_t h) { + if (h < 0) { + PP_DCHECK(h >= 0); + h = 0; + } + rect_.size.height = h; + } + + /// Getter function for returning the <code>Point</code>. + /// + /// @return A <code>Point</code>. + Point point() const { + return Point(rect_.point); + } + + /// Setter function for setting the value of the <code>Point</code>. + /// + /// @param[in] origin A <code>Point</code> representing the upper-left + /// starting coordinate. + void set_point(const Point& origin) { + rect_.point = origin; + } + + /// Getter function for returning the <code>Size</code>. + /// + /// @return The size of the rectangle. + Size size() const { + return Size(rect_.size); + } + + /// Setter function for setting the <code>Size</code>. + /// + /// @param[in] s A pointer to a <code>Size</code> representing the height + /// and width. + void set_size(const Size& s) { + rect_.size.width = s.width(); + rect_.size.height = s.height(); + } + + /// Getter function to get the upper-bound for the x-coordinates of the + /// rectangle. Note that this coordinate value is one past the highest x + /// value of pixels in the rectangle. This loop will access all the pixels + /// in a horizontal line in the rectangle: + /// <code>for (int32_t x = rect.x(); x < rect.right(); ++x) {}</code> + /// + /// @return The value of x + width for this point. + int32_t right() const { + return x() + width(); + } + + /// Getter function to get the upper-bound for the y-coordinates of the + /// rectangle. Note that this coordinate value is one past the highest xy + /// value of pixels in the rectangle. This loop will access all the pixels + /// in a horizontal line in the rectangle: + /// <code>for (int32_t y = rect.y(); y < rect.bottom(); ++y) {}</code> + /// + /// @return The value of y + height for this point. + int32_t bottom() const { + return y() + height(); + } + + /// Setter function for setting the value of the <code>Rect</code>. + /// + /// @param[in] x A new x value. + /// @param[in] y A new y value. + /// @param[in] w A new width value. + /// @param[in] h A new height value. + void SetRect(int32_t x, int32_t y, int32_t w, int32_t h) { + set_x(x); + set_y(y); + set_width(w); + set_height(h); + } + + /// Setter function for setting the value of the <code>Rect</code>. + /// + /// @param[in] rect A pointer to a <code>PP_Rect</code>. + void SetRect(const PP_Rect& rect) { + rect_ = rect; + } + + /// Inset() shrinks the rectangle by a horizontal and vertical + /// distance on all sides. + /// + /// @param[in] horizontal An int32_t value representing a horizontal + /// shrinking distance. + /// @param[in] vertical An int32_t value representing a vertical + /// shrinking distance. + void Inset(int32_t horizontal, int32_t vertical) { + Inset(horizontal, vertical, horizontal, vertical); + } + + /// Inset() shrinks the rectangle by the specified amount on each + /// side. + /// + /// @param[in] left An int32_t value representing a left + /// shrinking distance. + /// @param[in] top An int32_t value representing a top + /// shrinking distance. + /// @param[in] right An int32_t value representing a right + /// shrinking distance. + /// @param[in] bottom An int32_t value representing a bottom + /// shrinking distance. + void Inset(int32_t left, int32_t top, int32_t right, int32_t bottom); + + /// Offset() moves the rectangle by a horizontal and vertical distance. + /// + /// @param[in] horizontal An int32_t value representing a horizontal + /// move distance. + /// @param[in] vertical An int32_t value representing a vertical + /// move distance. + void Offset(int32_t horizontal, int32_t vertical); + + /// Offset() moves the rectangle by a horizontal and vertical distance. + /// + /// @param[in] point A pointer to a <code>Point</code> representing the + /// horizontal and vertical move distances. + void Offset(const Point& point) { + Offset(point.x(), point.y()); + } + + /// IsEmpty() determines if the area of a rectangle is zero. Returns true if + /// the area of the rectangle is zero. + /// + /// @return true if the area of the rectangle is zero. + bool IsEmpty() const { + return rect_.size.width == 0 && rect_.size.height == 0; + } + + /// Contains() determines if the point identified by point_x and point_y + /// falls inside this rectangle. The point (x, y) is inside the rectangle, + /// but the point (x + width, y + height) is not. + /// + /// @param[in] point_x An int32_t value representing a x value. + /// @param[in] point_y An int32_t value representing a y value. + /// + /// @return true if the point_x and point_y fall inside the rectangle. + bool Contains(int32_t point_x, int32_t point_y) const; + + /// Contains() determines if the specified point is contained by this + /// rectangle. + /// + /// @param[in] point A pointer to a Point representing a 2D coordinate. + /// + /// @return true if the point_x and point_y fall inside the rectangle. + bool Contains(const Point& point) const { + return Contains(point.x(), point.y()); + } + + /// Contains() determines if this rectangle contains the specified rectangle. + /// + /// @param[in] rect A pointer to a <code>Rect</code>. + /// + /// @return true if the rectangle fall inside this rectangle. + bool Contains(const Rect& rect) const; + + /// Intersects() determines if this rectangle intersects the specified + /// rectangle. + /// + /// @param[in] rect A pointer to a <code>Rect</code>. + /// + /// @return true if the rectangle intersects this rectangle. + bool Intersects(const Rect& rect) const; + + /// Intersect() computes the intersection of this rectangle with the given + /// rectangle. + /// + /// @param[in] rect A pointer to a <code>Rect</code>. + /// + /// @return A <code>Rect</code> representing the intersection. + Rect Intersect(const Rect& rect) const; + + /// Union() computes the union of this rectangle with the given rectangle. + /// The union is the smallest rectangle containing both rectangles. + /// + /// @param[in] rect A pointer to a <code>Rect</code>. + /// + /// @return A <code>Rect</code> representing the union. + Rect Union(const Rect& rect) const; + + /// Subtract() computes the rectangle resulting from subtracting + /// <code>rect</code> from this Rect. If <code>rect</code>does not intersect + /// completely in either the x or y direction, then <code>*this</code> is + /// returned. If <code>rect</code> contains <code>this</code>, then an empty + /// <code>Rect</code> is returned. + /// + /// @param[in] rect A pointer to a <code>Rect</code>. + /// + /// @return A <code>Rect</code> representing the subtraction. + Rect Subtract(const Rect& rect) const; + + /// AdjustToFit() fits as much of the receiving rectangle within + /// the supplied rectangle as possible, returning the result. For example, + /// if the receiver had a x-location of 2 and a width of 4, and the supplied + /// rectangle had an x-location of 0 with a width of 5, the returned + /// rectangle would have an x-location of 1 with a width of 4. + /// + /// @param[in] rect A pointer to a <code>Rect</code>. + /// + /// @return A <code>Rect</code> representing the difference between this + /// rectangle and the receiving rectangle. + Rect AdjustToFit(const Rect& rect) const; + + /// CenterPoint() determines the center of this rectangle. + /// + /// @return A <code>Point</code> representing the center of this rectangle. + Point CenterPoint() const; + + /// SharesEdgeWith() determines if this rectangle shares an entire edge + /// (same width or same height) with the given rectangle, and the + /// rectangles do not overlap. + /// + /// @param[in] rect A pointer to a <code>Rect</code>. + /// + /// @return true if this rectangle and supplied rectangle share an edge. + bool SharesEdgeWith(const Rect& rect) const; + + private: + PP_Rect rect_; +}; + +} // namespace pp + +/// This function determines whether the x, y, width, and height values of two +/// rectangles and are equal. +/// +/// @param[in] lhs The <code>Rect</code> on the left-hand side of the equation. +/// @param[in] rhs The <code>Rect</code> on the right-hand side of the equation. +/// +/// @return true if they are equal, false if unequal. +inline bool operator==(const pp::Rect& lhs, const pp::Rect& rhs) { + return lhs.x() == rhs.x() && + lhs.y() == rhs.y() && + lhs.width() == rhs.width() && + lhs.height() == rhs.height(); +} + +/// This function determines whether two Rects are not equal. +/// +/// @param[in] lhs The <code>Rect</code> on the left-hand side of the equation. +/// @param[in] rhs The <code>Rect</code> on the right-hand side of the +/// equation. +/// +/// @return true if the given Rects are equal, otherwise false. +inline bool operator!=(const pp::Rect& lhs, const pp::Rect& rhs) { + return !(lhs == rhs); +} + +#endif + diff --git a/chromium/ppapi/cpp/resource.cc b/chromium/ppapi/cpp/resource.cc new file mode 100644 index 00000000000..3ccc198b3b1 --- /dev/null +++ b/chromium/ppapi/cpp/resource.cc @@ -0,0 +1,55 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/resource.h" + +#include <algorithm> + +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module.h" + +namespace pp { + +Resource::Resource() : pp_resource_(0) { +} + +Resource::Resource(const Resource& other) : pp_resource_(other.pp_resource_) { + if (!is_null()) + Module::Get()->core()->AddRefResource(pp_resource_); +} + +Resource::~Resource() { + if (!is_null()) + Module::Get()->core()->ReleaseResource(pp_resource_); +} + +Resource& Resource::operator=(const Resource& other) { + if (!other.is_null()) + Module::Get()->core()->AddRefResource(other.pp_resource_); + if (!is_null()) + Module::Get()->core()->ReleaseResource(pp_resource_); + pp_resource_ = other.pp_resource_; + return *this; +} + +PP_Resource Resource::detach() { + PP_Resource ret = pp_resource_; + pp_resource_ = 0; + return ret; +} + +Resource::Resource(PP_Resource resource) : pp_resource_(resource) { + if (!is_null()) + Module::Get()->core()->AddRefResource(pp_resource_); +} + +Resource::Resource(PassRef, PP_Resource resource) : pp_resource_(resource) { +} + +void Resource::PassRefFromConstructor(PP_Resource resource) { + PP_DCHECK(!pp_resource_); + pp_resource_ = resource; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/resource.h b/chromium/ppapi/cpp/resource.h new file mode 100644 index 00000000000..8f5a92d2e12 --- /dev/null +++ b/chromium/ppapi/cpp/resource.h @@ -0,0 +1,98 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_RESOURCE_H_ +#define PPAPI_CPP_RESOURCE_H_ + +#include "ppapi/c/pp_resource.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/pass_ref.h" + +/// @file +/// This file defines a <code>Resource</code> type representing data associated +/// with the module. +namespace pp { + +/// A reference counted module resource. +class Resource { + public: + /// The default constructor. + Resource(); + + /// A constructor for copying a resource. + /// + /// @param[in] other A <code>Resource</code>. + Resource(const Resource& other); + + /// Destructor. + virtual ~Resource(); + + /// This function assigns one <code>Resource</code> to another + /// <code>Resource</code>. + /// + /// @param[in] other A Resource. + /// + /// @return A Resource containing the assigned Resource. + Resource& operator=(const Resource& other); + + /// This functions determines if this resource is invalid or + /// uninitialized. + /// + /// @return true if this resource is invalid or uninitialized. + bool is_null() const { return !pp_resource_; } + + PP_Resource pp_resource() const { return pp_resource_; } + + /// This function releases ownership of this resource and returns it to the + /// caller. + /// + /// Note that the reference count on the resource is unchanged and the caller + /// needs to release the resource. + /// + /// @return The detached <code>PP_Resource</code>. + PP_Resource detach(); + + protected: + /// A constructor used when a <code>PP_Resource</code> is provided as a + /// return value whose reference count we need to increment. + /// + /// @param[in] resource A <code>PP_Resource</code> corresponding to a + /// resource. + explicit Resource(PP_Resource resource); + + /// Constructor used when a <code>PP_Resource</code> already has a ref count + /// assigned. Add additional refcount is not taken. + Resource(PassRef, PP_Resource resource); + + /// PassRefFromConstructor is called by derived class' constructors to + /// initialize this <code>Resource</code> with a <code>PP_Resource</code> + /// that has already had its reference count incremented by + /// <code>Core::AddRefResource</code>. It also assumes this object has no + /// current resource. + /// + /// The intended usage of this function that the derived class constructor + /// will call the default <code>Resource</code> constructor, then make a call + /// to create a resource. It then wants to assign the new resource (which, + /// since it was returned by the browser, already had its reference count + /// increased). + /// + /// @param[in] resource A <code>PP_Resource</code> corresponding to a + /// resource. + void PassRefFromConstructor(PP_Resource resource); + + private: + PP_Resource pp_resource_; +}; + +} // namespace pp + +inline bool operator==(const pp::Resource& lhs, const pp::Resource& rhs) { + return lhs.pp_resource() == rhs.pp_resource(); +} + +inline bool operator!=(const pp::Resource& lhs, const pp::Resource& rhs) { + return !(lhs == rhs); +} + +#endif // PPAPI_CPP_RESOURCE_H_ diff --git a/chromium/ppapi/cpp/size.h b/chromium/ppapi/cpp/size.h new file mode 100644 index 00000000000..6c935615192 --- /dev/null +++ b/chromium/ppapi/cpp/size.h @@ -0,0 +1,174 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_SIZE_H_ +#define PPAPI_CPP_SIZE_H_ + +#include "ppapi/c/pp_size.h" +#include "ppapi/cpp/logging.h" + +/// @file +/// This file defines the API to create a size based on width +/// and height. + +namespace pp { + +/// A size of an object based on width and height. +class Size { + public: + + /// The default constructor. Initializes the width and height to 0. + Size() { + size_.width = 0; + size_.height = 0; + } + + /// A constructor accepting a pointer to a <code>PP_Size</code> and + /// converting the <code>PP_Size</code> to a <code>Size</code>. This is an + /// implicit conversion constructor. + /// + /// @param[in] s A pointer to a <code>PP_Size</code>. + Size(const PP_Size& s) { // Implicit. + // Want the >= 0 checking of the setter. + set_width(s.width); + set_height(s.height); + } + + /// A constructor accepting two int values for width and height and + /// converting them to a <code>Size</code>. + /// + /// @param[in] w An int value representing a width. + /// @param[in] h An int value representing a height. + Size(int w, int h) { + // Want the >= 0 checking of the setter. + set_width(w); + set_height(h); + } + + /// Destructor. + ~Size() { + } + + /// PP_Size() allows implicit conversion of a <code>Size</code> to a + /// <code>PP_Size</code>. + /// + /// @return A Size. + operator PP_Size() { + return size_; + } + + /// Getter function for returning the internal <code>PP_Size</code> struct. + /// + /// @return A const reference to the internal <code>PP_Size</code> struct. + const PP_Size& pp_size() const { + return size_; + } + + /// Getter function for returning the internal <code>PP_Size</code> struct. + /// + /// @return A mutable reference to the <code>PP_Size</code> struct. + PP_Size& pp_size() { + return size_; + } + + /// Getter function for returning the value of width. + /// + /// @return The value of width for this <code>Size</code>. + int width() const { + return size_.width; + } + + /// Setter function for setting the value of width. + /// + /// @param[in] w A new width value. + void set_width(int w) { + if (w < 0) { + PP_DCHECK(w >= 0); + w = 0; + } + size_.width = w; + } + + /// Getter function for returning the value of height. + /// + /// @return The value of height for this <code>Size</code>. + int height() const { + return size_.height; + } + + /// Setter function for setting the value of height. + /// + /// @param[in] h A new height value. + void set_height(int h) { + if (h < 0) { + PP_DCHECK(h >= 0); + h = 0; + } + size_.height = h; + } + + /// GetArea() determines the area (width * height). + /// + /// @return The area. + int GetArea() const { + return width() * height(); + } + + /// SetSize() sets the value of width and height. + /// + /// @param[in] w A new width value. + /// @param[in] h A new height value. + void SetSize(int w, int h) { + set_width(w); + set_height(h); + } + + /// Enlarge() enlarges the size of an object. + /// + /// @param[in] w A width to add the current width. + /// @param[in] h A height to add to the current height. + void Enlarge(int w, int h) { + set_width(width() + w); + set_height(height() + h); + } + + /// IsEmpty() determines if the size is zero. + /// + /// @return true if the size is zero. + bool IsEmpty() const { + // Size doesn't allow negative dimensions, so testing for 0 is enough. + return (width() == 0) || (height() == 0); + } + + private: + PP_Size size_; +}; + +} // namespace pp + +/// This function determines whether the width and height values of two sizes +/// are equal. +/// +/// @param[in] lhs The <code>Size</code> on the left-hand side of the equation. +/// @param[in] rhs The <code>Size</code> on the right-hand side of the +/// equation. +/// +/// @return true if they are equal, false if unequal. +inline bool operator==(const pp::Size& lhs, const pp::Size& rhs) { + return lhs.width() == rhs.width() && lhs.height() == rhs.height(); +} + +/// This function determines whether two <code>Sizes</code> are not equal. +/// +/// @param[in] lhs The <code>Size</code> on the left-hand side of the equation. +/// @param[in] rhs The <code>Size</code> on the right-hand side of the equation. +/// +/// @return true if the <code>Size</code> of lhs are equal to the +/// <code>Size</code> of rhs, otherwise false. +inline bool operator!=(const pp::Size& lhs, const pp::Size& rhs) { + return !(lhs == rhs); +} + +#endif // PPAPI_CPP_SIZE_H_ + diff --git a/chromium/ppapi/cpp/tcp_socket.cc b/chromium/ppapi/cpp/tcp_socket.cc new file mode 100644 index 00000000000..f0002fa5545 --- /dev/null +++ b/chromium/ppapi/cpp/tcp_socket.cc @@ -0,0 +1,116 @@ +// Copyright 2013 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 "ppapi/cpp/tcp_socket.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_TCPSocket_1_0>() { + return PPB_TCPSOCKET_INTERFACE_1_0; +} + +} // namespace + +TCPSocket::TCPSocket() { +} + +TCPSocket::TCPSocket(const InstanceHandle& instance) { + if (has_interface<PPB_TCPSocket_1_0>()) { + PassRefFromConstructor(get_interface<PPB_TCPSocket_1_0>()->Create( + instance.pp_instance())); + } +} + +TCPSocket::TCPSocket(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +TCPSocket::TCPSocket(const TCPSocket& other) : Resource(other) { +} + +TCPSocket::~TCPSocket() { +} + +TCPSocket& TCPSocket::operator=(const TCPSocket& other) { + Resource::operator=(other); + return *this; +} + +// static +bool TCPSocket::IsAvailable() { + return has_interface<PPB_TCPSocket_1_0>(); +} + +int32_t TCPSocket::Connect(const NetAddress& addr, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_1_0>()) { + return get_interface<PPB_TCPSocket_1_0>()->Connect( + pp_resource(), addr.pp_resource(), callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +NetAddress TCPSocket::GetLocalAddress() const { + if (has_interface<PPB_TCPSocket_1_0>()) { + return NetAddress( + PASS_REF, + get_interface<PPB_TCPSocket_1_0>()->GetLocalAddress(pp_resource())); + } + return NetAddress(); +} + +NetAddress TCPSocket::GetRemoteAddress() const { + if (has_interface<PPB_TCPSocket_1_0>()) { + return NetAddress( + PASS_REF, + get_interface<PPB_TCPSocket_1_0>()->GetRemoteAddress(pp_resource())); + } + return NetAddress(); +} + +int32_t TCPSocket::Read(char* buffer, + int32_t bytes_to_read, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_1_0>()) { + return get_interface<PPB_TCPSocket_1_0>()->Read( + pp_resource(), buffer, bytes_to_read, + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t TCPSocket::Write(const char* buffer, + int32_t bytes_to_write, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_1_0>()) { + return get_interface<PPB_TCPSocket_1_0>()->Write( + pp_resource(), buffer, bytes_to_write, + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +void TCPSocket::Close() { + if (has_interface<PPB_TCPSocket_1_0>()) + get_interface<PPB_TCPSocket_1_0>()->Close(pp_resource()); +} + +int32_t TCPSocket::SetOption(PP_TCPSocket_Option name, + const Var& value, + const CompletionCallback& callback) { + if (has_interface<PPB_TCPSocket_1_0>()) { + return get_interface<PPB_TCPSocket_1_0>()->SetOption( + pp_resource(), name, value.pp_var(), callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/tcp_socket.h b/chromium/ppapi/cpp/tcp_socket.h new file mode 100644 index 00000000000..5a5e0f4149e --- /dev/null +++ b/chromium/ppapi/cpp/tcp_socket.h @@ -0,0 +1,166 @@ +// Copyright 2013 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. + +#ifndef PPAPI_CPP_TCP_SOCKET_H_ +#define PPAPI_CPP_TCP_SOCKET_H_ + +#include "ppapi/c/ppb_tcp_socket.h" +#include "ppapi/cpp/net_address.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class CompletionCallback; +class InstanceHandle; + +/// The <code>TCPSocket</code> class provides TCP socket operations. +/// +/// Permissions: Apps permission <code>socket</code> with subrule +/// <code>tcp-connect</code> is required for <code>Connect()</code>. +/// For more details about network communication permissions, please see: +/// http://developer.chrome.com/apps/app_network.html +class TCPSocket : public Resource { + public: + /// Default constructor for creating an is_null() <code>TCPSocket</code> + /// object. + TCPSocket(); + + /// A constructor used to create a <code>TCPSocket</code> object. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit TCPSocket(const InstanceHandle& instance); + + /// A constructor used when you have received a <code>PP_Resource</code> as a + /// return value that has had 1 ref added for you. + /// + /// @param[in] resource A <code>PPB_TCPSocket</code> resource. + TCPSocket(PassRef, PP_Resource resource); + + /// The copy constructor for <code>TCPSocket</code>. + /// + /// @param[in] other A reference to another <code>TCPSocket</code>. + TCPSocket(const TCPSocket& other); + + /// The destructor. + virtual ~TCPSocket(); + + /// The assignment operator for <code>TCPSocket</code>. + /// + /// @param[in] other A reference to another <code>TCPSocket</code>. + /// + /// @return A reference to this <code>TCPSocket</code> object. + TCPSocket& operator=(const TCPSocket& other); + + /// Static function for determining whether the browser supports the + /// <code>PPB_TCPSocket</code> interface. + /// + /// @return true if the interface is available, false otherwise. + static bool IsAvailable(); + + /// Connects the socket to the given address. + /// + /// @param[in] addr A <code>NetAddress</code> object. + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion. + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>, + /// including (but not limited to): + /// - <code>PP_ERROR_NOACCESS</code>: the caller doesn't have required + /// permissions. + /// - <code>PP_ERROR_ADDRESS_UNREACHABLE</code>: <code>addr</code> is + /// unreachable. + /// - <code>PP_ERROR_CONNECTION_REFUSED</code>: the connection attempt was + /// refused. + /// - <code>PP_ERROR_CONNECTION_FAILED</code>: the connection attempt failed. + /// - <code>PP_ERROR_CONNECTION_TIMEDOUT</code>: the connection attempt timed + /// out. + int32_t Connect(const NetAddress& addr, + const CompletionCallback& callback); + + /// Gets the local address of the socket, if it is connected. + /// + /// @return A <code>NetAddress</code> object. The object will be null + /// (i.e., is_null() returns true) on failure. + NetAddress GetLocalAddress() const; + + /// Gets the remote address of the socket, if it is connected. + /// + /// @return A <code>NetAddress</code> object. The object will be null + /// (i.e., is_null() returns true) on failure. + NetAddress GetRemoteAddress() const; + + /// Reads data from the socket. The socket must be connected. It may perform a + /// partial read. + /// + /// <strong>Caveat:</strong> You should be careful about the lifetime of + /// <code>buffer</code>. Typically you will use a + /// <code>CompletionCallbackFactory</code> to scope callbacks to the lifetime + /// of your class. When your class goes out of scope, the callback factory + /// will not actually cancel the operation, but will rather just skip issuing + /// the callback on your class. This means that if the underlying + /// <code>PPB_TCPSocket</code> resource outlives your class, the browser + /// will still try to write into your buffer when the operation completes. + /// The buffer must be kept valid until then to avoid memory corruption. + /// If you want to release the buffer while the <code>Read()</code> call is + /// still pending, you should call <code>Close()</code> to ensure that the + /// buffer won't be accessed in the future. + /// + /// @param[out] buffer The buffer to store the received data on success. It + /// must be at least as large as <code>bytes_to_read</code>. + /// @param[in] bytes_to_read The number of bytes to read. + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion. + /// + /// @return A non-negative number on success to indicate how many bytes have + /// been read, 0 means that end-of-file was reached; otherwise, an error code + /// from <code>pp_errors.h</code>. + int32_t Read(char* buffer, + int32_t bytes_to_read, + const CompletionCallback& callback); + + /// Writes data to the socket. The socket must be connected. It may perform a + /// partial write. + /// + /// @param[in] buffer The buffer containing the data to write. + /// @param[in] bytes_to_write The number of bytes to write. + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion. + /// + /// @return A non-negative number on success to indicate how many bytes have + /// been written; otherwise, an error code from <code>pp_errors.h</code>. + int32_t Write(const char* buffer, + int32_t bytes_to_write, + const CompletionCallback& callback); + + /// Cancels all pending reads and writes and disconnects the socket. Any + /// pending callbacks will still run, reporting <code>PP_ERROR_ABORTED</code> + /// if pending IO was interrupted. After a call to this method, no output + /// buffer pointers passed into previous <code>Read()</code> calls will be + /// accessed. It is not valid to call <code>Connect()</code> again. + /// + /// The socket is implicitly closed if it is destroyed, so you are not + /// required to call this method. + void Close(); + + /// Sets a socket option on the TCP socket. + /// Please see the <code>PP_TCPSocket_Option</code> description for option + /// names, value types and allowed values. + /// + /// @param[in] name The option to set. + /// @param[in] value The option value to set. + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion. + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + //// + int32_t SetOption(PP_TCPSocket_Option name, + const Var& value, + const CompletionCallback& callback); +}; + +} // namespace pp + +#endif // PPAPI_CPP_TCP_SOCKET_H_ diff --git a/chromium/ppapi/cpp/text_input_controller.cc b/chromium/ppapi/cpp/text_input_controller.cc new file mode 100644 index 00000000000..59850d31be0 --- /dev/null +++ b/chromium/ppapi/cpp/text_input_controller.cc @@ -0,0 +1,63 @@ +// Copyright 2013 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 "ppapi/cpp/text_input_controller.h" + +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/rect.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_TextInputController_1_0>() { + return PPB_TEXTINPUTCONTROLLER_INTERFACE_1_0; +} + +} // namespace + + +TextInputController::TextInputController(const InstanceHandle& instance) + : instance_(instance) { +} + +TextInputController::~TextInputController() { +} + +void TextInputController::SetTextInputType(PP_TextInput_Type type) { + if (has_interface<PPB_TextInputController_1_0>()) { + get_interface<PPB_TextInputController_1_0>()->SetTextInputType( + instance_.pp_instance(), type); + } +} + +void TextInputController::UpdateCaretPosition(const Rect& caret) { + if (has_interface<PPB_TextInputController_1_0>()) { + get_interface<PPB_TextInputController_1_0>()->UpdateCaretPosition( + instance_.pp_instance(), &caret.pp_rect()); + } +} + +void TextInputController::CancelCompositionText() { + if (has_interface<PPB_TextInputController_1_0>()) { + get_interface<PPB_TextInputController_1_0>()->CancelCompositionText( + instance_.pp_instance()); + } +} + +void TextInputController::UpdateSurroundingText(const Var& text, + uint32_t caret, + uint32_t anchor) { + if (has_interface<PPB_TextInputController_1_0>()) { + get_interface<PPB_TextInputController_1_0>()->UpdateSurroundingText( + instance_.pp_instance(), + text.pp_var(), + caret, + anchor); + } +} + + +} // namespace pp diff --git a/chromium/ppapi/cpp/text_input_controller.h b/chromium/ppapi/cpp/text_input_controller.h new file mode 100644 index 00000000000..8843bd362f2 --- /dev/null +++ b/chromium/ppapi/cpp/text_input_controller.h @@ -0,0 +1,73 @@ +// Copyright 2013 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. + +#ifndef PPAPI_CPP_TEXT_INPUT_CONTROLLER_H_ +#define PPAPI_CPP_TEXT_INPUT_CONTROLLER_H_ + +#include <string> + +#include "ppapi/c/ppb_text_input_controller.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/var.h" + +/// @file +/// This file defines the APIs for text input handling. + +namespace pp { + +class Rect; +class Instance; + +/// This class can be used for giving hints to the browser about the text input +/// status of plugins. +class TextInputController { + public: + /// A constructor for creating a <code>TextInputController</code>. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit TextInputController(const InstanceHandle& instance); + + /// Destructor. + ~TextInputController(); + + /// SetTextInputType() informs the browser about the current text input mode + /// of the plugin. + /// + /// @param[in] type The type of text input type. + void SetTextInputType(PP_TextInput_Type type); + + /// UpdateCaretPosition() informs the browser about the coordinates of the + /// text input caret area. + /// + /// @param[in] caret A rectangle indicating the caret area. + void UpdateCaretPosition(const Rect& caret); + + /// CancelCompositionText() informs the browser that the current composition + /// text is cancelled by the plugin. + void CancelCompositionText(); + + /// UpdateSurroundingText() informs the browser about the current text + /// selection and surrounding text. + /// + /// @param[in] text A UTF-8 sting indicating string buffer of current input + /// context. + /// + /// @param[in] caret A integer indicating the byte index of caret location in + /// <code>text</code>. + /// + /// @param[in] caret A integer indicating the byte index of anchor location in + /// <code>text</code>. If there is no selection, this value should be equal to + /// <code>caret</code>. + void UpdateSurroundingText(const Var& text, + uint32_t caret, + uint32_t anchor); + + private: + InstanceHandle instance_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_TEXT_INPUT_CONTROLLER_H_ diff --git a/chromium/ppapi/cpp/touch_point.h b/chromium/ppapi/cpp/touch_point.h new file mode 100644 index 00000000000..0868061d2e4 --- /dev/null +++ b/chromium/ppapi/cpp/touch_point.h @@ -0,0 +1,54 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_TOUCH_POINT_H_ +#define PPAPI_CPP_TOUCH_POINT_H_ + +#include "ppapi/c/ppb_input_event.h" +#include "ppapi/cpp/input_event.h" +#include "ppapi/cpp/point.h" + +namespace pp { + +/// Wrapper class for PP_TouchPoint. +class TouchPoint { + public: + TouchPoint() : touch_point_(PP_MakeTouchPoint()) {} + + TouchPoint(const PP_TouchPoint& point) : touch_point_(point) {} + + /// @return The identifier for this TouchPoint. This corresponds to the order + /// in which the points were pressed. For example, the first point to be + /// pressed has an id of 0, the second has an id of 1, and so on. An id can be + /// reused when a touch point is released. For example, if two fingers are + /// down, with id 0 and 1, and finger 0 releases, the next finger to be + /// pressed can be assigned to id 0. + uint32_t id() const { return touch_point_.id; } + + /// @return The x-y coordinates of this TouchPoint, in DOM coordinate space. + FloatPoint position() const { + return pp::FloatPoint(touch_point_.position); + } + + /// @return The elliptical radii, in screen pixels, in the x and y direction + /// of this TouchPoint. + FloatPoint radii() const { return pp::FloatPoint(touch_point_.radius); } + + /// @return The angle of rotation of the elliptical model of this TouchPoint + /// from the y-axis. + float rotation_angle() const { return touch_point_.rotation_angle; } + + /// @return The pressure applied to this TouchPoint. This is typically a + /// value between 0 and 1, with 0 indicating no pressure and 1 indicating + /// some maximum pressure, but scaling differs depending on the hardware and + /// the value is not guaranteed to stay within that range. + float pressure() const { return touch_point_.pressure; } + + private: + PP_TouchPoint touch_point_; +}; + +} // namespace pp + +#endif /* PPAPI_CPP_TOUCH_POINT_H_ */ diff --git a/chromium/ppapi/cpp/trusted/DEPS b/chromium/ppapi/cpp/trusted/DEPS new file mode 100644 index 00000000000..52d9c47e4f6 --- /dev/null +++ b/chromium/ppapi/cpp/trusted/DEPS @@ -0,0 +1,5 @@ +include_rules = [ + "+ppapi/c/private", + "+ppapi/c/trusted", + "+ppapi/cpp/private", +] diff --git a/chromium/ppapi/cpp/trusted/browser_font_trusted.cc b/chromium/ppapi/cpp/trusted/browser_font_trusted.cc new file mode 100644 index 00000000000..5d474699825 --- /dev/null +++ b/chromium/ppapi/cpp/trusted/browser_font_trusted.cc @@ -0,0 +1,278 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/trusted/browser_font_trusted.h" + +#include <algorithm> + +#include "ppapi/c/dev/ppb_font_dev.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/rect.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_BrowserFont_Trusted_1_0>() { + return PPB_BROWSERFONT_TRUSTED_INTERFACE_1_0; +} +template <> const char* interface_name<PPB_Font_Dev_0_6>() { + return PPB_FONT_DEV_INTERFACE_0_6; +} + +// This class provides backwards compat for PPB_Font, which is binary +// compatible with the BrowserFont interface. +// TODO(brettw) remove PPB_Font altogether when Flash is updated. +const PP_FontDescription_Dev* BrowserFontDescToFontDesc( + const PP_BrowserFont_Trusted_Description* desc) { + return reinterpret_cast<const PP_FontDescription_Dev*>(desc); +} +PP_FontDescription_Dev* BrowserFontDescToFontDesc( + PP_BrowserFont_Trusted_Description* desc) { + return reinterpret_cast<PP_FontDescription_Dev*>(desc); +} +PP_FontMetrics_Dev* BrowserFontMetricsToFontMetrics( + PP_BrowserFont_Trusted_Metrics* metrics) { + return reinterpret_cast<PP_FontMetrics_Dev*>(metrics); +} +const PP_TextRun_Dev* BrowserFontTextRunToFontTextRun( + const PP_BrowserFont_Trusted_TextRun* run) { + return reinterpret_cast<const PP_TextRun_Dev*>(run); +} + +} // namespace + +// BrowserFontDescription ------------------------------------------------------ + +BrowserFontDescription::BrowserFontDescription() { + pp_font_description_.face = face_.pp_var(); + set_family(PP_BROWSERFONT_TRUSTED_FAMILY_DEFAULT); + set_size(0); + set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_NORMAL); + set_italic(false); + set_small_caps(false); + set_letter_spacing(0); + set_word_spacing(0); +} + +BrowserFontDescription::BrowserFontDescription( + const BrowserFontDescription& other) { + set_face(other.face()); + set_family(other.family()); + set_size(other.size()); + set_weight(other.weight()); + set_italic(other.italic()); + set_small_caps(other.small_caps()); + set_letter_spacing(other.letter_spacing()); + set_word_spacing(other.word_spacing()); +} + +BrowserFontDescription::~BrowserFontDescription() { +} + +BrowserFontDescription& BrowserFontDescription::operator=( + const BrowserFontDescription& other) { + pp_font_description_ = other.pp_font_description_; + + // Be careful about the refcount of the string, the copy that operator= made + // above didn't copy a ref. + pp_font_description_.face = PP_MakeUndefined(); + set_face(other.face()); + + return *this; +} + +// BrowserFontTextRun ---------------------------------------------------------- + +BrowserFontTextRun::BrowserFontTextRun() { + pp_text_run_.text = text_.pp_var(); + pp_text_run_.rtl = PP_FALSE; + pp_text_run_.override_direction = PP_FALSE; +} + +BrowserFontTextRun::BrowserFontTextRun(const std::string& text, + bool rtl, + bool override_direction) + : text_(text) { + pp_text_run_.text = text_.pp_var(); + pp_text_run_.rtl = PP_FromBool(rtl); + pp_text_run_.override_direction = PP_FromBool(override_direction); +} + +BrowserFontTextRun::BrowserFontTextRun(const BrowserFontTextRun& other) + : text_(other.text_) { + pp_text_run_.text = text_.pp_var(); + pp_text_run_.rtl = other.pp_text_run_.rtl; + pp_text_run_.override_direction = other.pp_text_run_.override_direction; +} + +BrowserFontTextRun::~BrowserFontTextRun() { +} + +BrowserFontTextRun& BrowserFontTextRun::operator=( + const BrowserFontTextRun& other) { + pp_text_run_ = other.pp_text_run_; + text_ = other.text_; + pp_text_run_.text = text_.pp_var(); + return *this; +} + +// BrowserFont_Trusted --------------------------------------------------------- + +BrowserFont_Trusted::BrowserFont_Trusted() : Resource() { +} + +BrowserFont_Trusted::BrowserFont_Trusted(PP_Resource resource) + : Resource(resource) { +} + +BrowserFont_Trusted::BrowserFont_Trusted( + const InstanceHandle& instance, + const BrowserFontDescription& description) { + if (has_interface<PPB_BrowserFont_Trusted_1_0>()) { + PassRefFromConstructor(get_interface<PPB_BrowserFont_Trusted_1_0>()->Create( + instance.pp_instance(), + &description.pp_font_description())); + } else if (!has_interface<PPB_Font_Dev_0_6>()) { + PassRefFromConstructor(get_interface<PPB_Font_Dev_0_6>()->Create( + instance.pp_instance(), + BrowserFontDescToFontDesc(&description.pp_font_description()))); + } +} + +BrowserFont_Trusted::BrowserFont_Trusted(const BrowserFont_Trusted& other) + : Resource(other) { +} + +BrowserFont_Trusted& BrowserFont_Trusted::operator=( + const BrowserFont_Trusted& other) { + Resource::operator=(other); + return *this; +} + +// static +Var BrowserFont_Trusted::GetFontFamilies(const InstanceHandle& instance) { + if (!has_interface<PPB_Font_Dev_0_6>()) + return Var(); + return Var(PASS_REF, + get_interface<PPB_Font_Dev_0_6>()->GetFontFamilies( + instance.pp_instance())); +} + +bool BrowserFont_Trusted::Describe( + BrowserFontDescription* description, + PP_BrowserFont_Trusted_Metrics* metrics) const { + // Be careful with ownership of the |face| string. It will come back with + // a ref of 1, which we want to assign to the |face_| member of the C++ class. + if (has_interface<PPB_BrowserFont_Trusted_1_0>()) { + if (!get_interface<PPB_BrowserFont_Trusted_1_0>()->Describe( + pp_resource(), &description->pp_font_description_, metrics)) + return false; + } else if (!has_interface<PPB_Font_Dev_0_6>()) { + if (!get_interface<PPB_Font_Dev_0_6>()->Describe( + pp_resource(), + BrowserFontDescToFontDesc(&description->pp_font_description_), + BrowserFontMetricsToFontMetrics(metrics))) + return false; + } + description->face_ = Var(PASS_REF, + description->pp_font_description_.face); + return true; +} + +bool BrowserFont_Trusted::DrawTextAt(ImageData* dest, + const BrowserFontTextRun& text, + const Point& position, + uint32_t color, + const Rect& clip, + bool image_data_is_opaque) const { + if (has_interface<PPB_BrowserFont_Trusted_1_0>()) { + return PP_ToBool(get_interface<PPB_BrowserFont_Trusted_1_0>()->DrawTextAt( + pp_resource(), + dest->pp_resource(), + &text.pp_text_run(), + &position.pp_point(), + color, + &clip.pp_rect(), + PP_FromBool(image_data_is_opaque))); + } else if (!has_interface<PPB_Font_Dev_0_6>()) { + return PP_ToBool(get_interface<PPB_Font_Dev_0_6>()->DrawTextAt( + pp_resource(), + dest->pp_resource(), + BrowserFontTextRunToFontTextRun(&text.pp_text_run()), + &position.pp_point(), + color, + &clip.pp_rect(), + PP_FromBool(image_data_is_opaque))); + } + return false; +} + +int32_t BrowserFont_Trusted::MeasureText(const BrowserFontTextRun& text) const { + if (has_interface<PPB_BrowserFont_Trusted_1_0>()) { + return get_interface<PPB_BrowserFont_Trusted_1_0>()->MeasureText( + pp_resource(), + &text.pp_text_run()); + } else if (!has_interface<PPB_Font_Dev_0_6>()) { + return get_interface<PPB_Font_Dev_0_6>()->MeasureText( + pp_resource(), + BrowserFontTextRunToFontTextRun(&text.pp_text_run())); + } + return -1; +} + +uint32_t BrowserFont_Trusted::CharacterOffsetForPixel( + const BrowserFontTextRun& text, + int32_t pixel_position) const { + if (has_interface<PPB_BrowserFont_Trusted_1_0>()) { + return get_interface<PPB_BrowserFont_Trusted_1_0>()-> + CharacterOffsetForPixel( + pp_resource(), + &text.pp_text_run(), + pixel_position); + } else if (!has_interface<PPB_Font_Dev_0_6>()) { + return get_interface<PPB_Font_Dev_0_6>()->CharacterOffsetForPixel( + pp_resource(), + BrowserFontTextRunToFontTextRun(&text.pp_text_run()), + pixel_position); + } + return 0; +} + +int32_t BrowserFont_Trusted::PixelOffsetForCharacter( + const BrowserFontTextRun& text, + uint32_t char_offset) const { + if (has_interface<PPB_BrowserFont_Trusted_1_0>()) { + return get_interface<PPB_BrowserFont_Trusted_1_0>()-> + PixelOffsetForCharacter( + pp_resource(), + &text.pp_text_run(), + char_offset); + } else if (!has_interface<PPB_Font_Dev_0_6>()) { + return get_interface<PPB_Font_Dev_0_6>()->PixelOffsetForCharacter( + pp_resource(), + BrowserFontTextRunToFontTextRun(&text.pp_text_run()), + char_offset); + } + return 0; +} + +bool BrowserFont_Trusted::DrawSimpleText( + ImageData* dest, + const std::string& text, + const Point& position, + uint32_t color, + bool image_data_is_opaque) const { + return DrawTextAt(dest, BrowserFontTextRun(text), position, color, + Rect(dest->size()), image_data_is_opaque); +} + +int32_t BrowserFont_Trusted::MeasureSimpleText(const std::string& text) const { + return MeasureText(BrowserFontTextRun(text)); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/trusted/browser_font_trusted.h b/chromium/ppapi/cpp/trusted/browser_font_trusted.h new file mode 100644 index 00000000000..7225b269ee5 --- /dev/null +++ b/chromium/ppapi/cpp/trusted/browser_font_trusted.h @@ -0,0 +1,147 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_TRUSTED_BROWSER_FONT_TRUSTED_H_ +#define PPAPI_CPP_TRUSTED_BROWSER_FONT_TRUSTED_H_ + +#include <string> + +#include "ppapi/c/trusted/ppb_browser_font_trusted.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +class ImageData; +class InstanceHandle; +class Point; +class Rect; + +// BrowserFontDescription ------------------------------------------------------ + +class BrowserFontDescription { + public: + BrowserFontDescription(); + BrowserFontDescription(const BrowserFontDescription& other); + ~BrowserFontDescription(); + + BrowserFontDescription& operator=(const BrowserFontDescription& other); + + const PP_BrowserFont_Trusted_Description& pp_font_description() const { + return pp_font_description_; + } + + Var face() const { return face_; } + void set_face(const Var& face) { + face_ = face; + pp_font_description_.face = face_.pp_var(); + } + + PP_BrowserFont_Trusted_Family family() const { + return pp_font_description_.family; + } + void set_family(PP_BrowserFont_Trusted_Family f) { + pp_font_description_.family = f; + } + + uint32_t size() const { return pp_font_description_.size; } + void set_size(uint32_t s) { pp_font_description_.size = s; } + + PP_BrowserFont_Trusted_Weight weight() const { + return pp_font_description_.weight; + } + void set_weight(PP_BrowserFont_Trusted_Weight w) { + pp_font_description_.weight = w; + } + + bool italic() const { return PP_ToBool(pp_font_description_.italic); } + void set_italic(bool i) { pp_font_description_.italic = PP_FromBool(i); } + + bool small_caps() const { + return PP_ToBool(pp_font_description_.small_caps); + } + void set_small_caps(bool s) { + pp_font_description_.small_caps = PP_FromBool(s); + } + + int letter_spacing() const { return pp_font_description_.letter_spacing; } + void set_letter_spacing(int s) { pp_font_description_.letter_spacing = s; } + + int word_spacing() const { return pp_font_description_.word_spacing; } + void set_word_spacing(int w) { pp_font_description_.word_spacing = w; } + + private: + friend class BrowserFont_Trusted; + + Var face_; // Manages memory for pp_font_description_.face + PP_BrowserFont_Trusted_Description pp_font_description_; +}; + +// BrowserFontTextRun ---------------------------------------------------------- + +class BrowserFontTextRun { + public: + BrowserFontTextRun(); + BrowserFontTextRun(const std::string& text, + bool rtl = false, + bool override_direction = false); + BrowserFontTextRun(const BrowserFontTextRun& other); + ~BrowserFontTextRun(); + + BrowserFontTextRun& operator=(const BrowserFontTextRun& other); + + const PP_BrowserFont_Trusted_TextRun& pp_text_run() const { + return pp_text_run_; + } + + private: + Var text_; // Manages memory for the reference in pp_text_run_. + PP_BrowserFont_Trusted_TextRun pp_text_run_; +}; + +// BrowserFont_Trusted --------------------------------------------------------- + +// Provides access to system fonts. +class BrowserFont_Trusted : public Resource { + public: + // Creates an is_null() Font object. + BrowserFont_Trusted(); + + explicit BrowserFont_Trusted(PP_Resource resource); + BrowserFont_Trusted(const InstanceHandle& instance, + const BrowserFontDescription& description); + BrowserFont_Trusted(const BrowserFont_Trusted& other); + + BrowserFont_Trusted& operator=(const BrowserFont_Trusted& other); + + // PPB_Font methods: + static Var GetFontFamilies(const InstanceHandle& instance); + bool Describe(BrowserFontDescription* description, + PP_BrowserFont_Trusted_Metrics* metrics) const; + bool DrawTextAt(ImageData* dest, + const BrowserFontTextRun& text, + const Point& position, + uint32_t color, + const Rect& clip, + bool image_data_is_opaque) const; + int32_t MeasureText(const BrowserFontTextRun& text) const; + uint32_t CharacterOffsetForPixel(const BrowserFontTextRun& text, + int32_t pixel_position) const; + int32_t PixelOffsetForCharacter(const BrowserFontTextRun& text, + uint32_t char_offset) const; + + // Convenience function that assumes a left-to-right string with no clipping. + bool DrawSimpleText(ImageData* dest, + const std::string& text, + const Point& position, + uint32_t color, + bool image_data_is_opaque = false) const; + + // Convenience function that assumes a left-to-right string. + int32_t MeasureSimpleText(const std::string& text) const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_TRUSTED_BROWSER_FONT_TRUSTED_H_ diff --git a/chromium/ppapi/cpp/trusted/file_chooser_trusted.cc b/chromium/ppapi/cpp/trusted/file_chooser_trusted.cc new file mode 100644 index 00000000000..caa1b73cfae --- /dev/null +++ b/chromium/ppapi/cpp/trusted/file_chooser_trusted.cc @@ -0,0 +1,81 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/trusted/file_chooser_trusted.h" + +#include "ppapi/c/pp_bool.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" +#include "ppapi/c/trusted/ppb_file_chooser_trusted.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_FileChooserTrusted_0_5>() { + return PPB_FILECHOOSER_TRUSTED_INTERFACE_0_5; +} + +template <> const char* interface_name<PPB_FileChooserTrusted_0_6>() { + return PPB_FILECHOOSER_TRUSTED_INTERFACE_0_6; +} + +} // namespace + +FileChooser_Trusted::FileChooser_Trusted() : save_as_(false) { +} + +FileChooser_Trusted::FileChooser_Trusted(const InstanceHandle& instance, + PP_FileChooserMode_Dev mode, + const Var& accept_types, + bool save_as, + const std::string& suggested_file_name) + : FileChooser_Dev(instance, mode, accept_types), + save_as_(save_as), + suggested_file_name_(suggested_file_name) { +} + +FileChooser_Trusted::FileChooser_Trusted(const FileChooser_Trusted& other) + : FileChooser_Dev(other), + save_as_(other.save_as_), + suggested_file_name_(other.suggested_file_name_) { +} + +FileChooser_Trusted& FileChooser_Trusted::operator=( + const FileChooser_Trusted& other) { + FileChooser_Dev::operator=(other); + save_as_ = other.save_as_; + suggested_file_name_ = other.suggested_file_name_; + return *this; +} + +int32_t FileChooser_Trusted::Show( + const CompletionCallbackWithOutput< std::vector<FileRef> >& callback) { + if (has_interface<PPB_FileChooserTrusted_0_6>()) { + return get_interface<PPB_FileChooserTrusted_0_6>()->ShowWithoutUserGesture( + pp_resource(), + PP_FromBool(save_as_), + Var(suggested_file_name_).pp_var(), + callback.output(), + callback.pp_completion_callback()); + } + if (has_interface<PPB_FileChooserTrusted_0_5>()) { + // Data for our callback. The callback handler will delete it. + ChooseCallbackData0_5* data = new ChooseCallbackData0_5; + data->file_chooser = pp_resource(); + data->output = callback.output(); + data->original_callback = callback.pp_completion_callback(); + + return get_interface<PPB_FileChooserTrusted_0_5>()->ShowWithoutUserGesture( + pp_resource(), + PP_FromBool(save_as_), + Var(suggested_file_name_).pp_var(), + PP_MakeCompletionCallback(&CallbackConverter, data)); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/trusted/file_chooser_trusted.h b/chromium/ppapi/cpp/trusted/file_chooser_trusted.h new file mode 100644 index 00000000000..cdb70b0be68 --- /dev/null +++ b/chromium/ppapi/cpp/trusted/file_chooser_trusted.h @@ -0,0 +1,41 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_TRUSTED_FILE_CHOOSER_TRUSTED_H_ +#define PPAPI_CPP_TRUSTED_FILE_CHOOSER_TRUSTED_H_ + +#include <string> + +#include "ppapi/cpp/dev/file_chooser_dev.h" + +namespace pp { + +class FileChooser_Trusted : public FileChooser_Dev { + public: + /// Creates an is_null() FileChooser_Trusted object. + FileChooser_Trusted(); + + FileChooser_Trusted(const InstanceHandle& instance, + PP_FileChooserMode_Dev mode, + const Var& accept_types, + bool save_as, + const std::string& suggested_file_name); + + FileChooser_Trusted(const FileChooser_Trusted& other); + + FileChooser_Trusted& operator=(const FileChooser_Trusted& other); + + // Overrides of method in superclass. This shows without requiring a user + // gesture (and can also show save dialogs). + virtual int32_t Show( + const CompletionCallbackWithOutput< std::vector<FileRef> >& callback); + + private: + bool save_as_; + std::string suggested_file_name_; +}; + +} // namespace pp + +#endif // PPAPI_CPP_TRUSTED_FILE_CHOOSER_TRUSTED_H_ diff --git a/chromium/ppapi/cpp/trusted/file_io_trusted.cc b/chromium/ppapi/cpp/trusted/file_io_trusted.cc new file mode 100644 index 00000000000..a3123cac188 --- /dev/null +++ b/chromium/ppapi/cpp/trusted/file_io_trusted.cc @@ -0,0 +1,54 @@ +// Copyright (c) 2011 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 "ppapi/cpp/trusted/file_io_trusted.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/trusted/ppb_file_io_trusted.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/file_io.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_FileIOTrusted>() { + return PPB_FILEIOTRUSTED_INTERFACE_0_4; +} + +} // namespace + +FileIO_Trusted::FileIO_Trusted() { +} + +int32_t FileIO_Trusted::GetOSFileDescriptor(const FileIO& file_io) { + const int32_t kInvalidOSFileDescriptor = -1; + if (!has_interface<PPB_FileIOTrusted>()) + return kInvalidOSFileDescriptor; + return get_interface<PPB_FileIOTrusted>()->GetOSFileDescriptor( + file_io.pp_resource()); +} + +int32_t FileIO_Trusted::WillWrite(const FileIO& file_io, + int64_t offset, + int32_t bytes_to_write, + const CompletionCallback& callback) { + if (!has_interface<PPB_FileIOTrusted>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_FileIOTrusted>()->WillWrite( + file_io.pp_resource(), offset, bytes_to_write, + callback.pp_completion_callback()); +} + +int32_t FileIO_Trusted::WillSetLength(const FileIO& file_io, + int64_t length, + const CompletionCallback& callback) { + if (!has_interface<PPB_FileIOTrusted>()) + return callback.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_FileIOTrusted>()->WillSetLength( + file_io.pp_resource(), length, callback.pp_completion_callback()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/trusted/file_io_trusted.h b/chromium/ppapi/cpp/trusted/file_io_trusted.h new file mode 100644 index 00000000000..3ba2140832b --- /dev/null +++ b/chromium/ppapi/cpp/trusted/file_io_trusted.h @@ -0,0 +1,36 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_TRUSTED_FILE_IO_TRUSTED_H_ +#define PPAPI_CPP_TRUSTED_FILE_IO_TRUSTED_H_ + +#include <string> + +#include "ppapi/c/pp_stdint.h" + +namespace pp { + +class FileIO; +class CompletionCallback; + +class FileIO_Trusted { + public: + /// Creates a FileIO_Trusted object. + FileIO_Trusted(); + + int32_t GetOSFileDescriptor(const FileIO& file_io); + + int32_t WillWrite(const FileIO& file_io, + int64_t offset, + int32_t bytes_to_write, + const CompletionCallback& callback); + + int32_t WillSetLength(const FileIO& file_io, + int64_t length, + const CompletionCallback& callback); +}; + +} // namespace pp + +#endif // PPAPI_CPP_TRUSTED_FILE_IO_TRUSTED_H_ diff --git a/chromium/ppapi/cpp/udp_socket.cc b/chromium/ppapi/cpp/udp_socket.cc new file mode 100644 index 00000000000..bb4b1c895b0 --- /dev/null +++ b/chromium/ppapi/cpp/udp_socket.cc @@ -0,0 +1,110 @@ +// Copyright 2013 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 "ppapi/cpp/udp_socket.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_UDPSocket_1_0>() { + return PPB_UDPSOCKET_INTERFACE_1_0; +} + +} // namespace + +UDPSocket::UDPSocket() { +} + +UDPSocket::UDPSocket(const InstanceHandle& instance) { + if (has_interface<PPB_UDPSocket_1_0>()) { + PassRefFromConstructor(get_interface<PPB_UDPSocket_1_0>()->Create( + instance.pp_instance())); + } +} + +UDPSocket::UDPSocket(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +UDPSocket::UDPSocket(const UDPSocket& other) : Resource(other) { +} + +UDPSocket::~UDPSocket() { +} + +UDPSocket& UDPSocket::operator=(const UDPSocket& other) { + Resource::operator=(other); + return *this; +} + +// static +bool UDPSocket::IsAvailable() { + return has_interface<PPB_UDPSocket_1_0>(); +} + +int32_t UDPSocket::Bind(const NetAddress& addr, + const CompletionCallback& callback) { + if (has_interface<PPB_UDPSocket_1_0>()) { + return get_interface<PPB_UDPSocket_1_0>()->Bind( + pp_resource(), addr.pp_resource(), callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +NetAddress UDPSocket::GetBoundAddress() { + if (has_interface<PPB_UDPSocket_1_0>()) { + return NetAddress( + PASS_REF, + get_interface<PPB_UDPSocket_1_0>()->GetBoundAddress(pp_resource())); + } + return NetAddress(); +} + +int32_t UDPSocket::RecvFrom( + char* buffer, + int32_t num_bytes, + const CompletionCallbackWithOutput<NetAddress>& callback) { + if (has_interface<PPB_UDPSocket_1_0>()) { + return get_interface<PPB_UDPSocket_1_0>()->RecvFrom( + pp_resource(), buffer, num_bytes, callback.output(), + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +int32_t UDPSocket::SendTo(const char* buffer, + int32_t num_bytes, + const NetAddress& addr, + const CompletionCallback& callback) { + if (has_interface<PPB_UDPSocket_1_0>()) { + return get_interface<PPB_UDPSocket_1_0>()->SendTo( + pp_resource(), buffer, num_bytes, addr.pp_resource(), + callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +void UDPSocket::Close() { + if (has_interface<PPB_UDPSocket_1_0>()) + return get_interface<PPB_UDPSocket_1_0>()->Close(pp_resource()); +} + +int32_t UDPSocket::SetOption(PP_UDPSocket_Option name, + const Var& value, + const CompletionCallback& callback) { + if (has_interface<PPB_UDPSocket_1_0>()) { + return get_interface<PPB_UDPSocket_1_0>()->SetOption( + pp_resource(), name, value.pp_var(), callback.pp_completion_callback()); + } + return callback.MayForce(PP_ERROR_NOINTERFACE); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/udp_socket.h b/chromium/ppapi/cpp/udp_socket.h new file mode 100644 index 00000000000..fa599d71d84 --- /dev/null +++ b/chromium/ppapi/cpp/udp_socket.h @@ -0,0 +1,160 @@ +// Copyright 2013 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. + +#ifndef PPAPI_CPP_UDP_SOCKET_H_ +#define PPAPI_CPP_UDP_SOCKET_H_ + +#include "ppapi/c/ppb_udp_socket.h" +#include "ppapi/cpp/net_address.h" +#include "ppapi/cpp/pass_ref.h" +#include "ppapi/cpp/resource.h" + +namespace pp { + +class CompletionCallback; +class InstanceHandle; +class Var; + +template <typename T> class CompletionCallbackWithOutput; + +/// The <code>UDPSocket</code> class provides UDP socket operations. +/// +/// Permissions: Apps permission <code>socket</code> with subrule +/// <code>udp-bind</code> is required for <code>Bind()</code>; subrule +/// <code>udp-send-to</code> is required for <code>SendTo()</code>. +/// For more details about network communication permissions, please see: +/// http://developer.chrome.com/apps/app_network.html +class UDPSocket : public Resource { + public: + /// Default constructor for creating an is_null() <code>UDPSocket</code> + /// object. + UDPSocket(); + + /// A constructor used to create a <code>UDPSocket</code> object. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit UDPSocket(const InstanceHandle& instance); + + /// A constructor used when you have received a <code>PP_Resource</code> as a + /// return value that has had 1 ref added for you. + /// + /// @param[in] resource A <code>PPB_UDPSocket</code> resource. + UDPSocket(PassRef, PP_Resource resource); + + /// The copy constructor for <code>UDPSocket</code>. + /// + /// @param[in] other A reference to another <code>UDPSocket</code>. + UDPSocket(const UDPSocket& other); + + /// The destructor. + virtual ~UDPSocket(); + + /// The assignment operator for <code>UDPSocket</code>. + /// + /// @param[in] other A reference to another <code>UDPSocket</code>. + /// + /// @return A reference to this <code>UDPSocket</code> object. + UDPSocket& operator=(const UDPSocket& other); + + /// Static function for determining whether the browser supports the + /// <code>PPB_UDPSocket</code> interface. + /// + /// @return true if the interface is available, false otherwise. + static bool IsAvailable(); + + /// Binds the socket to the given address. + /// + /// @param[in] addr A <code>NetAddress</code> object. + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion. + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + /// <code>PP_ERROR_NOACCESS</code> will be returned if the caller doesn't have + /// required permissions. <code>PP_ERROR_ADDRESS_IN_USE</code> will be + /// returned if the address is already in use. + int32_t Bind(const NetAddress& addr, + const CompletionCallback& callback); + + /// Get the address that the socket is bound to. The socket must be bound. + /// + /// @return A <code>NetAddress</code> object. The object will be null + /// (i.e., is_null() returns true) on failure. + NetAddress GetBoundAddress(); + + /// Receives data from the socket and stores the source address. The socket + /// must be bound. + /// + /// <strong>Caveat:</strong> You should be careful about the lifetime of + /// <code>buffer</code>. Typically you will use a + /// <code>CompletionCallbackFactory</code> to scope callbacks to the lifetime + /// of your class. When your class goes out of scope, the callback factory + /// will not actually cancel the operation, but will rather just skip issuing + /// the callback on your class. This means that if the underlying + /// <code>PPB_UDPSocket</code> resource outlives your class, the browser + /// will still try to write into your buffer when the operation completes. + /// The buffer must be kept valid until then to avoid memory corruption. + /// If you want to release the buffer while the <code>RecvFrom()</code> call + /// is still pending, you should call <code>Close()</code> to ensure that the + /// buffer won't be accessed in the future. + /// + /// @param[out] buffer The buffer to store the received data on success. It + /// must be at least as large as <code>num_bytes</code>. + /// @param[in] num_bytes The number of bytes to receive. + /// @param[in] callback A <code>CompletionCallbackWithOutput</code> to be + /// called upon completion. + /// + /// @return A non-negative number on success to indicate how many bytes have + /// been received; otherwise, an error code from <code>pp_errors.h</code>. + int32_t RecvFrom( + char* buffer, + int32_t num_bytes, + const CompletionCallbackWithOutput<NetAddress>& callback); + + /// Sends data to a specific destination. The socket must be bound. + /// + /// @param[in] buffer The buffer containing the data to send. + /// @param[in] num_bytes The number of bytes to send. + /// @param[in] addr A <code>NetAddress</code> object holding the destination + /// address. + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion. + /// + /// @return A non-negative number on success to indicate how many bytes have + /// been sent; otherwise, an error code from <code>pp_errors.h</code>. + /// <code>PP_ERROR_NOACCESS</code> will be returned if the caller doesn't have + /// required permissions. + int32_t SendTo(const char* buffer, + int32_t num_bytes, + const NetAddress& addr, + const CompletionCallback& callback); + + /// Cancels all pending reads and writes, and closes the socket. Any pending + /// callbacks will still run, reporting <code>PP_ERROR_ABORTED</code> if + /// pending IO was interrupted. After a call to this method, no output + /// paramters passed into previous <code>RecvFrom()</code> calls will be + /// accessed. It is not valid to call <code>Bind()</code> again. + /// + /// The socket is implicitly closed if it is destroyed, so you are not + /// required to call this method. + void Close(); + + /// Sets a socket option on the UDP socket. + /// Please see the <code>PP_UDPSocket_Option</code> description for option + /// names, value types and allowed values. + /// + /// @param[in] name The option to set. + /// @param[in] value The option value to set. + /// @param[in] callback A <code>CompletionCallback</code> to be called upon + /// completion. + /// + /// @return An int32_t containing an error code from <code>pp_errors.h</code>. + int32_t SetOption(PP_UDPSocket_Option name, + const Var& value, + const CompletionCallback& callback); +}; + +} // namespace pp + +#endif // PPAPI_CPP_UDP_SOCKET_H_ diff --git a/chromium/ppapi/cpp/url_loader.cc b/chromium/ppapi/cpp/url_loader.cc new file mode 100644 index 00000000000..1be87a777b0 --- /dev/null +++ b/chromium/ppapi/cpp/url_loader.cc @@ -0,0 +1,103 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/url_loader.h" + +#include "ppapi/c/ppb_url_loader.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/url_request_info.h" +#include "ppapi/cpp/url_response_info.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_URLLoader_1_0>() { + return PPB_URLLOADER_INTERFACE_1_0; +} + +} // namespace + +URLLoader::URLLoader(PP_Resource resource) : Resource(resource) { +} + +URLLoader::URLLoader(const InstanceHandle& instance) { + if (!has_interface<PPB_URLLoader_1_0>()) + return; + PassRefFromConstructor(get_interface<PPB_URLLoader_1_0>()->Create( + instance.pp_instance())); +} + +URLLoader::URLLoader(const URLLoader& other) : Resource(other) { +} + +int32_t URLLoader::Open(const URLRequestInfo& request_info, + const CompletionCallback& cc) { + if (!has_interface<PPB_URLLoader_1_0>()) + return cc.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_URLLoader_1_0>()->Open(pp_resource(), + request_info.pp_resource(), + cc.pp_completion_callback()); +} + +int32_t URLLoader::FollowRedirect(const CompletionCallback& cc) { + if (!has_interface<PPB_URLLoader_1_0>()) + return cc.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_URLLoader_1_0>()->FollowRedirect( + pp_resource(), cc.pp_completion_callback()); +} + +bool URLLoader::GetUploadProgress(int64_t* bytes_sent, + int64_t* total_bytes_to_be_sent) const { + if (!has_interface<PPB_URLLoader_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_URLLoader_1_0>()->GetUploadProgress( + pp_resource(), bytes_sent, total_bytes_to_be_sent)); +} + +bool URLLoader::GetDownloadProgress( + int64_t* bytes_received, + int64_t* total_bytes_to_be_received) const { + if (!has_interface<PPB_URLLoader_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_URLLoader_1_0>()->GetDownloadProgress( + pp_resource(), bytes_received, total_bytes_to_be_received)); +} + +URLResponseInfo URLLoader::GetResponseInfo() const { + if (!has_interface<PPB_URLLoader_1_0>()) + return URLResponseInfo(); + return URLResponseInfo(PASS_REF, + get_interface<PPB_URLLoader_1_0>()->GetResponseInfo( + pp_resource())); +} + +int32_t URLLoader::ReadResponseBody(void* buffer, + int32_t bytes_to_read, + const CompletionCallback& cc) { + if (!has_interface<PPB_URLLoader_1_0>()) + return cc.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_URLLoader_1_0>()->ReadResponseBody( + pp_resource(), buffer, bytes_to_read, cc.pp_completion_callback()); +} + +int32_t URLLoader::FinishStreamingToFile(const CompletionCallback& cc) { + if (!has_interface<PPB_URLLoader_1_0>()) + return cc.MayForce(PP_ERROR_NOINTERFACE); + return get_interface<PPB_URLLoader_1_0>()->FinishStreamingToFile( + pp_resource(), cc.pp_completion_callback()); +} + +void URLLoader::Close() { + if (!has_interface<PPB_URLLoader_1_0>()) + return; + get_interface<PPB_URLLoader_1_0>()->Close(pp_resource()); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/url_loader.h b/chromium/ppapi/cpp/url_loader.h new file mode 100644 index 00000000000..00c086e14d5 --- /dev/null +++ b/chromium/ppapi/cpp/url_loader.h @@ -0,0 +1,168 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_URL_LOADER_H_ +#define PPAPI_CPP_URL_LOADER_H_ + +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the API for loading URLs. +namespace pp { + +class CompletionCallback; +class InstanceHandle; +class URLRequestInfo; +class URLResponseInfo; + +/// URLLoader provides an API for loading URLs. +/// Refer to <code>ppapi/examples/url_loader/streaming.cc</code> +/// for an example of how to use this class. +class URLLoader : public Resource { + public: + /// Default constructor for creating an is_null() + /// <code>URLLoader</code> object. + URLLoader() {} + + /// A constructor used when a <code>PP_Resource</code> is provided as a + /// return value whose reference count we need to increment. + /// + /// @param[in] resource A <code>PP_Resource</code> corresponding to a + /// <code>URLLoader</code> resource. + explicit URLLoader(PP_Resource resource); + + /// A constructor used to allocate a new URLLoader in the browser. The + /// resulting object will be <code>is_null</code> if the allocation failed. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit URLLoader(const InstanceHandle& instance); + + /// The copy constructor for <code>URLLoader</code>. + /// + /// @param other A <code>URLLoader</code> to be copied. + URLLoader(const URLLoader& other); + + /// This function begins loading the <code>URLRequestInfo</code>. + /// The operation completes when response headers are received or when an + /// error occurs. Use GetResponseInfo() to access the response + /// headers. + /// + /// @param[in] request_info A <code>URLRequestInfo</code> corresponding to a + /// URLRequestInfo. + /// @param[in] cc A <code>CompletionCallback</code> to run on asynchronous + /// completion of Open(). This callback will run when response + /// headers for the url are received or error occurred. This callback + /// will only run if Open() returns <code>PP_OK_COMPLETIONPENDING</code>. + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + int32_t Open(const URLRequestInfo& request_info, + const CompletionCallback& cc); + + /// This function can be invoked to follow a + /// redirect after Open() completed on receiving redirect headers. + /// + /// @param[in] cc A <code>CompletionCallback</code> to run on asynchronous + /// completion of FollowRedirect(). This callback will run when response + /// headers for the redirect url are received or error occurred. This callback + /// will only run if FollowRedirect() returns + /// <code>PP_OK_COMPLETIONPENDING</code>. + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + int32_t FollowRedirect(const CompletionCallback& cc); + + /// This function returns the current upload progress (which is only + /// meaningful after Open() has been called). Progress only refers to the + /// request body and does not include the headers. + /// + /// This data is only available if the <code>URLRequestInfo</code> passed to + /// Open() had the + /// <code>PP_URLREQUESTPROPERTY_REPORTUPLOADPROGRESS</code> property set to + /// <code>PP_TRUE</code>. + /// + /// @param[in] bytes_sent The number of bytes sent thus far. + /// @param[in] total_bytes_to_be_sent The total number of bytes to be sent. + /// + /// @return true if the upload progress is available, false if it is not + /// available. + bool GetUploadProgress(int64_t* bytes_sent, + int64_t* total_bytes_to_be_sent) const; + + /// This function returns the current download progress, which is meaningful + /// after Open() has been called. Progress only refers to the response body + /// and does not include the headers. + /// + /// This data is only available if the <code>URLRequestInfo</code> passed to + /// Open() had the + /// <code>PP_URLREQUESTPROPERTY_REPORTDOWNLOADPROGRESS</code> property set to + /// PP_TRUE. + /// + /// @param[in] bytes_received The number of bytes received thus far. + /// @param[in] total_bytes_to_be_received The total number of bytes to be + /// received. The total bytes to be received may be unknown, in which case + /// <code>total_bytes_to_be_received</code> will be set to -1. + /// + /// @return true if the download progress is available, false if it is + /// not available. + bool GetDownloadProgress(int64_t* bytes_received, + int64_t* total_bytes_to_be_received) const; + + /// This is a function that returns the current + /// <code>URLResponseInfo</code> object. + /// + /// @return A <code>URLResponseInfo</code> corresponding to the + /// <code>URLResponseInfo</code> if successful, an <code>is_null</code> + /// object if the loader is not a valid resource or if Open() has not been + /// called. + URLResponseInfo GetResponseInfo() const; + + /// This function is used to read the response body. The size of the buffer + /// must be large enough to hold the specified number of bytes to read. + /// This function might perform a partial read. + /// + /// @param[in,out] buffer A pointer to the buffer for the response body. + /// @param[in] bytes_to_read The number of bytes to read. + /// @param[in] cc A <code>CompletionCallback</code> to run on asynchronous + /// completion. The callback will run if the bytes (full or partial) are + /// read or an error occurs asynchronously. This callback will run only if + /// this function returns <code>PP_OK_COMPLETIONPENDING</code>. + /// + /// @return An int32_t containing the number of bytes read or an error code + /// from <code>pp_errors.h</code>. + int32_t ReadResponseBody(void* buffer, + int32_t bytes_to_read, + const CompletionCallback& cc); + + /// This function is used to wait for the response body to be completely + /// downloaded to the file provided by the GetBodyAsFileRef() in the current + /// <code>URLResponseInfo</code>. This function is only used if + /// <code>PP_URLREQUESTPROPERTY_STREAMTOFILE</code> was set on the + /// <code>URLRequestInfo</code> passed to Open(). + /// + /// @param[in] cc A <code>CompletionCallback</code> to run on asynchronous + /// completion. This callback will run when body is downloaded or an error + /// occurs after FinishStreamingToFile() returns + /// <code>PP_OK_COMPLETIONPENDING</code>. + /// + /// @return An int32_t containing the number of bytes read or an error code + /// from <code>pp_errors.h</code>. + int32_t FinishStreamingToFile(const CompletionCallback& cc); + + /// This function is used to cancel any pending IO and close the URLLoader + /// object. Any pending callbacks will still run, reporting + /// <code>PP_ERROR_ABORTED</code> if pending IO was interrupted. It is NOT + /// valid to call Open() again after a call to this function. + /// + /// <strong>Note:</strong> If the <code>URLLoader</code> object is destroyed + /// while it is still open, then it will be implicitly closed so you are not + /// required to call Close(). + void Close(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_URL_LOADER_H_ diff --git a/chromium/ppapi/cpp/url_request_info.cc b/chromium/ppapi/cpp/url_request_info.cc new file mode 100644 index 00000000000..f6053f990fb --- /dev/null +++ b/chromium/ppapi/cpp/url_request_info.cc @@ -0,0 +1,76 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/url_request_info.h" + +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_URLRequestInfo_1_0>() { + return PPB_URLREQUESTINFO_INTERFACE_1_0; +} + +} // namespace + +URLRequestInfo::URLRequestInfo(const InstanceHandle& instance) { + if (!has_interface<PPB_URLRequestInfo_1_0>()) + return; + PassRefFromConstructor( + get_interface<PPB_URLRequestInfo_1_0>()->Create(instance.pp_instance())); +} + +URLRequestInfo::URLRequestInfo(const URLRequestInfo& other) + : Resource(other) { +} + +bool URLRequestInfo::SetProperty(PP_URLRequestProperty property, + const Var& value) { + if (!has_interface<PPB_URLRequestInfo_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_URLRequestInfo_1_0>()->SetProperty( + pp_resource(), property, value.pp_var())); +} + +bool URLRequestInfo::AppendDataToBody(const void* data, uint32_t len) { + if (!has_interface<PPB_URLRequestInfo_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_URLRequestInfo_1_0>()->AppendDataToBody( + pp_resource(), data, len)); +} + +bool URLRequestInfo::AppendFileToBody(const FileRef& file_ref, + PP_Time expected_last_modified_time) { + if (!has_interface<PPB_URLRequestInfo_1_0>()) + return false; + return PP_ToBool( + get_interface<PPB_URLRequestInfo_1_0>()->AppendFileToBody( + pp_resource(), + file_ref.pp_resource(), + 0, + -1, + expected_last_modified_time)); +} + +bool URLRequestInfo::AppendFileRangeToBody( + const FileRef& file_ref, + int64_t start_offset, + int64_t length, + PP_Time expected_last_modified_time) { + if (!has_interface<PPB_URLRequestInfo_1_0>()) + return false; + return PP_ToBool(get_interface<PPB_URLRequestInfo_1_0>()->AppendFileToBody( + pp_resource(), + file_ref.pp_resource(), + start_offset, + length, + expected_last_modified_time)); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/url_request_info.h b/chromium/ppapi/cpp/url_request_info.h new file mode 100644 index 00000000000..c476be480ff --- /dev/null +++ b/chromium/ppapi/cpp/url_request_info.h @@ -0,0 +1,334 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_URL_REQUEST_INFO_H_ +#define PPAPI_CPP_URL_REQUEST_INFO_H_ + +#include "ppapi/c/ppb_url_request_info.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" + +/// @file +/// This file defines the API for creating and manipulating URL requests. +namespace pp { + +class FileRef; +class InstanceHandle; + +/// URLRequestInfo provides an API for creating and manipulating URL requests. +class URLRequestInfo : public Resource { + public: + /// Default constructor. This constructor creates an + /// <code>is_null</code> resource. + URLRequestInfo() {} + + /// A constructor used to allocate a new <code>URLLoader</code> in the + /// browser. The resulting object will be <code>is_null</code> if the + /// allocation failed. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit URLRequestInfo(const InstanceHandle& instance); + + /// The copy constructor for <code>URLRequestInfo</code>. + /// + /// @param[in] other A <code>URLRequestInfo</code> to be copied. + URLRequestInfo(const URLRequestInfo& other); + + /// SetProperty() sets a request property. The value of the property must be + /// the correct type according to the property being set. + /// + /// @param[in] property A <code>PP_URLRequestProperty</code> identifying the + /// property to set. + /// @param[in] value A <code>Var</code> containing the property value. + /// + /// @return true if successful, false if any of the + /// parameters are invalid. + bool SetProperty(PP_URLRequestProperty property, const Var& value); + + /// AppendDataToBody() appends data to the request body. A content-length + /// request header will be automatically generated. + /// + /// @param[in] data A pointer to a buffer holding the data. + /// @param[in] len The length, in bytes, of the data. + /// + /// @return true if successful, false if any of the + /// parameters are invalid. + bool AppendDataToBody(const void* data, uint32_t len); + + /// AppendFileToBody() is used to append an entire file, to be uploaded, to + /// the request body. A content-length request header will be automatically + /// generated. + /// + /// @param[in] file_ref A <code>FileRef</code> containing the file + /// reference. + + /// @param[in] expected_last_modified_time An optional (non-zero) last + /// modified time stamp used to validate that the file was not modified since + /// the given time before it was uploaded. The upload will fail with an error + /// code of <code>PP_ERROR_FILECHANGED</code> if the file has been modified + /// since the given time. If expected_last_modified_time is 0, then no + /// validation is performed. + /// + /// @return true if successful, false if any of the + /// parameters are invalid. + bool AppendFileToBody(const FileRef& file_ref, + PP_Time expected_last_modified_time = 0); + + /// AppendFileRangeToBody() is a pointer to a function used to append part or + /// all of a file, to be uploaded, to the request body. A content-length + /// request header will be automatically generated. + /// + /// @param[in] file_ref A <code>FileRef</code> containing the file + /// reference. + /// @param[in] start_offset An optional starting point offset within the + /// file. + /// @param[in] length An optional number of bytes of the file to + /// be included. If the value is -1, then the sub-range to upload extends + /// to the end of the file. + /// @param[in] expected_last_modified_time An optional (non-zero) last + /// modified time stamp used to validate that the file was not modified since + /// the given time before it was uploaded. The upload will fail with an error + /// code of <code>PP_ERROR_FILECHANGED</code> if the file has been modified + /// since the given time. If expected_last_modified_time is 0, then no + /// validation is performed. + /// + /// @return true if successful, false if any of the + /// parameters are invalid. + bool AppendFileRangeToBody(const FileRef& file_ref, + int64_t start_offset, + int64_t length, + PP_Time expected_last_modified_time = 0); + + /// SetURL() sets the <code>PP_URLREQUESTPROPERTY_URL</code> + /// property for the request. + /// + /// @param[in] url_string A <code>Var</code> containing the property value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetURL(const Var& url_string) { + return SetProperty(PP_URLREQUESTPROPERTY_URL, url_string); + } + + /// SetMethod() sets the <code>PP_URLREQUESTPROPERTY_METHOD</code> + /// (corresponding to a string of type <code>PP_VARTYPE_STRING</code>) + /// property for the request. This string is either a POST or GET. Refer to + /// the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html">HTTP + /// Methods</a> documentation for further information. + /// + /// @param[in] method_string A <code>Var</code> containing the property + /// value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetMethod(const Var& method_string) { + return SetProperty(PP_URLREQUESTPROPERTY_METHOD, method_string); + } + + /// SetHeaders() sets the <code>PP_URLREQUESTPROPERTY_HEADERS</code> + /// (corresponding to a <code>\n</code> delimited string of type + /// <code>PP_VARTYPE_STRING</code>) property for the request. + /// Refer to the + /// <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html"Header + /// Field Definitions</a> documentation for further information. + /// + /// @param[in] headers_string A <code>Var</code> containing the property + /// value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetHeaders(const Var& headers_string) { + return SetProperty(PP_URLREQUESTPROPERTY_HEADERS, headers_string); + } + + /// SetStreamToFile() sets the + /// <code>PP_URLREQUESTPROPERTY_STREAMTOFILE</code> (corresponding + /// to a bool of type <code>PP_VARTYPE_BOOL</code>). The default of the + /// property is false. Set this value to true if you want to download the + /// data to a file. Use URL_Loader::FinishStreamingToFile() to complete + /// the download. + /// + /// @param[in] enable A <code>bool</code> containing the property value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetStreamToFile(bool enable) { + return SetProperty(PP_URLREQUESTPROPERTY_STREAMTOFILE, enable); + } + + /// SetFollowRedirects() sets the + /// <code>PP_URLREQUESTPROPERTY_FOLLOWREDIRECT</code> (corresponding + /// to a bool of type <code>PP_VARTYPE_BOOL</code>). The default of the + /// property is true. Set this value to false if you want to use + /// URLLoader::FollowRedirects() to follow the redirects only after examining + /// redirect headers. + /// + /// @param[in] enable A <code>bool</code> containing the property value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetFollowRedirects(bool enable) { + return SetProperty(PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS, enable); + } + + /// SetRecordDownloadProgress() sets the + /// <code>PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGESS</code> + /// (corresponding to a bool of type <code>PP_VARTYPE_BOOL</code>). The + /// default of the property is false. Set this value to true if you want to + /// be able to poll the download progress using + /// URLLoader::GetDownloadProgress(). + /// + /// @param[in] enable A <code>bool</code> containing the property value. + //// + /// @return true if successful, false if the parameter is invalid. + bool SetRecordDownloadProgress(bool enable) { + return SetProperty(PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGRESS, enable); + } + + /// SetRecordUploadProgress() sets the + /// <code>PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS</code> + /// (corresponding to a bool of type <code>PP_VARTYPE_BOOL</code>). The + /// default of the property is false. Set this value to true if you want to + /// be able to poll the upload progress using URLLoader::GetUploadProgress(). + /// + /// @param[in] enable A <code>bool</code> containing the property value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetRecordUploadProgress(bool enable) { + return SetProperty(PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS, enable); + } + + /// SetCustomReferrerURL() sets the + /// <code>PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL</code> + /// (corresponding to a string of type <code>PP_VARTYPE_STRING</code> or + /// might be set to undefined as <code>PP_VARTYPE_UNDEFINED</code>). Set it + /// to a string to set a custom referrer (if empty, the referrer header will + /// be omitted), or to undefined to use the default referrer. Only loaders + /// with universal access (only available on trusted implementations) will + /// accept <code>URLRequestInfo</code> objects that try to set a custom + /// referrer; if given to a loader without universal access, + /// <code>PP_ERROR_BADARGUMENT</code> will result. + /// + /// @param[in] url A <code>Var</code> containing the property value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetCustomReferrerURL(const Var& url) { + return SetProperty(PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL, url); + } + + /// SetAllowCrossOriginRequests() sets the + /// <code>PP_URLREQUESTPROPERTY_ALLOWCROSSORIGINREQUESTS</code> + /// (corresponding to a bool of type <code>PP_VARTYPE_BOOL</code>). The + /// default of the property is false. Whether cross-origin requests are + /// allowed. Cross-origin requests are made using the CORS (Cross-Origin + /// Resource Sharing) algorithm to check whether the request should be + /// allowed. For the complete CORS algorithm, refer to the + /// <a href="http://www.w3.org/TR/access-control">Cross-Origin Resource + /// Sharing</a> documentation. + /// + /// @param[in] enable A <code>bool</code> containing the property value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetAllowCrossOriginRequests(bool enable) { + return SetProperty(PP_URLREQUESTPROPERTY_ALLOWCROSSORIGINREQUESTS, enable); + } + + /// SetAllowCredentials() sets the + /// <code>PP_URLREQUESTPROPERTY_ALLOWCREDENTIALS</code> + /// (corresponding to a bool of type <code>PP_VARTYPE_BOOL</code>). The + /// default of the property is false. Whether HTTP credentials are sent with + /// cross-origin requests. If false, no credentials are sent with the request + /// and cookies are ignored in the response. If the request is not + /// cross-origin, this property is ignored. + /// + /// @param[in] enable A <code>bool</code> containing the property value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetAllowCredentials(bool enable) { + return SetProperty(PP_URLREQUESTPROPERTY_ALLOWCREDENTIALS, enable); + } + + /// SetCustomContentTransferEncoding() sets the + /// <code>PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING</code> + /// (corresponding to a string of type <code>PP_VARTYPE_STRING</code> or + /// might be set to undefined as <code>PP_VARTYPE_UNDEFINED</code>). Set it + /// to a string to set a custom content-transfer-encoding header (if empty, + /// that header will be omitted), or to undefined to use the default (if + /// any). Only loaders with universal access (only available on trusted + /// implementations) will accept <code>URLRequestInfo</code> objects that try + /// to set a custom content transfer encoding; if given to a loader without + /// universal access, <code>PP_ERROR_BADARGUMENT</code> will result. + /// + /// @param[in] content_transfer_encoding A <code>Var</code> containing the + /// property value. To use the default content transfer encoding, set + /// <code>content_transfer_encoding</code> to an undefined <code>Var</code>. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetCustomContentTransferEncoding(const Var& content_transfer_encoding) { + return SetProperty(PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING, + content_transfer_encoding); + } + + /// SetPrefetchBufferUpperThreshold() sets the + /// <code>PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD</code> + /// (corresponding to a integer of type <code>PP_VARTYPE_INT32</code>). The + /// default is not defined and is set by the browser possibly depending on + /// system capabilities. Set it to an integer to set an upper threshold for + /// the prefetched buffer of an asynchronous load. When exceeded, the browser + /// will defer loading until + /// <code>PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERERTHRESHOLD</code> is hit, + /// at which time it will begin prefetching again. When setting this + /// property, + /// <code>PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERERTHRESHOLD</code> must + /// also be set. Behavior is undefined if the former is <= the latter. + /// + /// @param[in] size An int32_t containing the property value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetPrefetchBufferUpperThreshold(int32_t size) { + return SetProperty(PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD, + size); + } + + /// SetPrefetchBufferLowerThreshold() sets the + /// <code>PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERTHRESHOLD</code> + /// (corresponding to a integer of type <code>PP_VARTYPE_INT32</code>). The + /// default is not defined and is set by the browser to a value appropriate + /// for the default + /// <code>PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD</code>. + /// Set it to an integer to set a lower threshold for the prefetched buffer + /// of an asynchronous load. When reached, the browser will resume loading if + /// If <code>PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERERTHRESHOLD</code> had + /// previously been reached. + /// When setting this property, + /// <code>PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD</code> must also + /// be set. Behavior is undefined if the former is >= the latter. + /// + /// @param[in] size An int32_t containing the property value. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetPrefetchBufferLowerThreshold(int32_t size) { + return SetProperty(PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERTHRESHOLD, + size); + } + + /// SetCustomUserAgent() sets the + /// <code>PP_URLREQUESTPROPERTY_CUSTOMUSERAGENT</code> (corresponding to a + /// string of type <code>PP_VARTYPE_STRING</code> or might be set to undefined + /// as <code>PP_VARTYPE_UNDEFINED</code>). Set it to a string to set a custom + /// user-agent header (if empty, that header will be omitted), or to undefined + /// to use the default. Only loaders with universal access (only available on + /// trusted implementations) will accept <code>URLRequestInfo</code> objects + /// that try to set a custom user agent; if given to a loader without + /// universal access, <code>PP_ERROR_BADARGUMENT</code> will result. + /// + /// @param[in] user_agent A <code>Var</code> containing the property value. To + /// use the default user agent, set <code>user_agent</code> to an undefined + /// <code>Var</code>. + /// + /// @return true if successful, false if the parameter is invalid. + bool SetCustomUserAgent(const Var& user_agent) { + return SetProperty(PP_URLREQUESTPROPERTY_CUSTOMUSERAGENT, user_agent); + } +}; + +} // namespace pp + +#endif // PPAPI_CPP_URL_REQUEST_INFO_H_ diff --git a/chromium/ppapi/cpp/url_response_info.cc b/chromium/ppapi/cpp/url_response_info.cc new file mode 100644 index 00000000000..032b40585ed --- /dev/null +++ b/chromium/ppapi/cpp/url_response_info.cc @@ -0,0 +1,45 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/url_response_info.h" + +#include "ppapi/cpp/file_ref.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_URLResponseInfo_1_0>() { + return PPB_URLRESPONSEINFO_INTERFACE_1_0; +} + +} // namespace + +URLResponseInfo::URLResponseInfo(const URLResponseInfo& other) + : Resource(other) { +} + +URLResponseInfo::URLResponseInfo(PassRef, PP_Resource resource) + : Resource(PASS_REF, resource) { +} + +Var URLResponseInfo::GetProperty(PP_URLResponseProperty property) const { + if (!has_interface<PPB_URLResponseInfo_1_0>()) + return Var(); + return Var(PASS_REF, + get_interface<PPB_URLResponseInfo_1_0>()->GetProperty(pp_resource(), + property)); +} + +FileRef URLResponseInfo::GetBodyAsFileRef() const { + if (!has_interface<PPB_URLResponseInfo_1_0>()) + return FileRef(); + return FileRef(PASS_REF, + get_interface<PPB_URLResponseInfo_1_0>()->GetBodyAsFileRef( + pp_resource())); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/url_response_info.h b/chromium/ppapi/cpp/url_response_info.h new file mode 100644 index 00000000000..f9e60cfb828 --- /dev/null +++ b/chromium/ppapi/cpp/url_response_info.h @@ -0,0 +1,120 @@ +// Copyright (c) 2011 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. + +#ifndef PPAPI_CPP_URL_RESPONSE_INFO_H_ +#define PPAPI_CPP_URL_RESPONSE_INFO_H_ + +#include "ppapi/c/ppb_url_response_info.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/var.h" + +/// @file +/// This file defines the API for examining URL responses. +namespace pp { + +class FileRef; + +/// URLResponseInfo provides an API for examining URL responses. +class URLResponseInfo : public Resource { + public: + /// Default constructor. This constructor creates an <code>is_null</code> + /// resource. + URLResponseInfo() {} + + /// A constructor used when you have received a <code>PP_Resource</code> as a + /// return value that has already been reference counted. + /// + /// @param[in] resource A <code>PP_Resource</code> corresponding to a + /// resource. + URLResponseInfo(PassRef, PP_Resource resource); + + /// The copy constructor for <code>URLResponseInfo</code>. + URLResponseInfo(const URLResponseInfo& other); + + /// This function gets a response property. + /// + /// @param[in] property A <code>PP_URLResponseProperty</code> identifying the + /// type of property in the response. + /// + /// @return A <code>Var</code> containing the response property value if + /// successful, <code>is_undefined Var</code> if an input parameter is + /// invalid. + Var GetProperty(PP_URLResponseProperty property) const; + + /// This function returns a <code>FileRef</code> + /// pointing to the file containing the response body. This + /// is only valid if <code>PP_URLREQUESTPROPERTY_STREAMTOFILE</code> was set + /// on the <code>URLRequestInfo</code> used to produce this response. This + /// file remains valid until the <code>URLLoader</code> associated with this + /// <code>URLResponseInfo</code> is closed or destroyed. + /// + /// @return A <code>FileRef</code> corresponding to a + /// <code>FileRef</code> if successful, an <code>is_null</code> object if + /// <code>PP_URLREQUESTPROPERTY_STREAMTOFILE</code> was not requested or if + /// the <code>URLLoader</code> has not been opened yet. + FileRef GetBodyAsFileRef() const; + + /// This function gets the <code>PP_URLRESPONSEPROPERTY_URL</code> + /// property for the response. + /// + /// @return An <code>is_string Var</code> containing the response property + /// value if successful, <code>is_undefined Var</code> if an input parameter + /// is invalid. + Var GetURL() const { + return GetProperty(PP_URLRESPONSEPROPERTY_URL); + } + + /// This function gets the <code>PP_URLRESPONSEPROPERTY_REDIRECTURL</code> + /// property for the response. + /// + /// @return An <code>is_string Var</code> containing the response property + /// value if successful, <code>is_undefined Var</code> if an input parameter + /// is invalid. + Var GetRedirectURL() const { + return GetProperty(PP_URLRESPONSEPROPERTY_REDIRECTURL); + } + + /// This function gets the <code>PP_URLRESPONSEPROPERTY_REDIRECTMETHOD</code> + /// property for the response. + /// + /// @return An <code>is_string Var</code> containing the response property + /// value if successful, <code>is_undefined Var</code> if an input parameter + /// is invalid. + Var GetRedirectMethod() const { + return GetProperty(PP_URLRESPONSEPROPERTY_REDIRECTMETHOD); + } + + /// This function gets the <code>PP_URLRESPONSEPROPERTY_STATUSCODE</code> + /// property for the response. + /// + /// @return A int32_t containing the response property value if successful, + /// <code>is_undefined Var</code> if an input parameter is invalid. + int32_t GetStatusCode() const { + return GetProperty(PP_URLRESPONSEPROPERTY_STATUSCODE).AsInt(); + } + + /// This function gets the <code>PP_URLRESPONSEPROPERTY_STATUSLINE</code> + /// property for the response. + /// + /// @return An <code>is_string Var</code> containing the response property + /// value if successful, <code>is_undefined Var</code> if an input parameter + /// is invalid. + Var GetStatusLine() const { + return GetProperty(PP_URLRESPONSEPROPERTY_STATUSLINE); + } + + /// This function gets the <code>PP_URLRESPONSEPROPERTY_HEADERS</code> + /// property for the response. + /// + /// @return An <code>is_string Var</code> containing the response property + /// value if successful, <code>is_undefined Var</code> if an input parameter + /// is invalid. + Var GetHeaders() const { + return GetProperty(PP_URLRESPONSEPROPERTY_HEADERS); + } +}; + +} // namespace pp + +#endif // PPAPI_CPP_URL_RESPONSE_INFO_H_ diff --git a/chromium/ppapi/cpp/var.cc b/chromium/ppapi/cpp/var.cc new file mode 100644 index 00000000000..1108e05ef46 --- /dev/null +++ b/chromium/ppapi/cpp/var.cc @@ -0,0 +1,258 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/var.h" + +#include <stdio.h> +#include <string.h> + +#include <algorithm> + +#include "ppapi/c/pp_var.h" +#include "ppapi/c/ppb_var.h" +#include "ppapi/cpp/instance.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" + +// Define equivalent to snprintf on Windows. +#if defined(_MSC_VER) +# define snprintf sprintf_s +#endif + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_Var_1_1>() { + return PPB_VAR_INTERFACE_1_1; +} +template <> const char* interface_name<PPB_Var_1_0>() { + return PPB_VAR_INTERFACE_1_0; +} + +// Technically you can call AddRef and Release on any Var, but it may involve +// cross-process calls depending on the plugin. This is an optimization so we +// only do refcounting on the necessary objects. +inline bool NeedsRefcounting(const PP_Var& var) { + return var.type > PP_VARTYPE_DOUBLE; +} + +// This helper function detects whether PPB_Var version 1.1 is available. If so, +// it uses it to create a PP_Var for the given string. Otherwise it falls back +// to PPB_Var version 1.0. +PP_Var VarFromUtf8Helper(const char* utf8_str, uint32_t len) { + if (has_interface<PPB_Var_1_1>()) { + return get_interface<PPB_Var_1_1>()->VarFromUtf8(utf8_str, len); + } else if (has_interface<PPB_Var_1_0>()) { + return get_interface<PPB_Var_1_0>()->VarFromUtf8(Module::Get()->pp_module(), + utf8_str, + len); + } else { + return PP_MakeNull(); + } +} + +} // namespace + +Var::Var() { + memset(&var_, 0, sizeof(var_)); + var_.type = PP_VARTYPE_UNDEFINED; + is_managed_ = true; +} + +Var::Var(Null) { + memset(&var_, 0, sizeof(var_)); + var_.type = PP_VARTYPE_NULL; + is_managed_ = true; +} + +Var::Var(bool b) { + var_.type = PP_VARTYPE_BOOL; + var_.padding = 0; + var_.value.as_bool = PP_FromBool(b); + is_managed_ = true; +} + +Var::Var(int32_t i) { + var_.type = PP_VARTYPE_INT32; + var_.padding = 0; + var_.value.as_int = i; + is_managed_ = true; +} + +Var::Var(double d) { + var_.type = PP_VARTYPE_DOUBLE; + var_.padding = 0; + var_.value.as_double = d; + is_managed_ = true; +} + +Var::Var(const char* utf8_str) { + uint32_t len = utf8_str ? static_cast<uint32_t>(strlen(utf8_str)) : 0; + var_ = VarFromUtf8Helper(utf8_str, len); + is_managed_ = true; +} + +Var::Var(const std::string& utf8_str) { + var_ = VarFromUtf8Helper(utf8_str.c_str(), + static_cast<uint32_t>(utf8_str.size())); + is_managed_ = true; +} + + +Var::Var(const PP_Var& var) { + var_ = var; + is_managed_ = true; + if (NeedsRefcounting(var_)) { + if (has_interface<PPB_Var_1_0>()) + get_interface<PPB_Var_1_0>()->AddRef(var_); + else + var_.type = PP_VARTYPE_NULL; + } +} + +Var::Var(const Var& other) { + var_ = other.var_; + is_managed_ = true; + if (NeedsRefcounting(var_)) { + if (has_interface<PPB_Var_1_0>()) + get_interface<PPB_Var_1_0>()->AddRef(var_); + else + var_.type = PP_VARTYPE_NULL; + } +} + +Var::~Var() { + if (NeedsRefcounting(var_) && + is_managed_ && + has_interface<PPB_Var_1_0>()) + get_interface<PPB_Var_1_0>()->Release(var_); +} + +Var& Var::operator=(const Var& other) { + // Early return for self-assignment. Note however, that two distinct vars + // can refer to the same object, so we still need to be careful about the + // refcounting below. + if (this == &other) + return *this; + + // Be careful to keep the ref alive for cases where we're assigning an + // object to itself by addrefing the new one before releasing the old one. + bool old_is_managed = is_managed_; + is_managed_ = true; + if (NeedsRefcounting(other.var_)) { + // Assume we already has_interface<PPB_Var_1_0> for refcounted vars or else + // we couldn't have created them in the first place. + get_interface<PPB_Var_1_0>()->AddRef(other.var_); + } + if (NeedsRefcounting(var_) && old_is_managed) + get_interface<PPB_Var_1_0>()->Release(var_); + + var_ = other.var_; + return *this; +} + +bool Var::operator==(const Var& other) const { + if (var_.type != other.var_.type) + return false; + switch (var_.type) { + case PP_VARTYPE_UNDEFINED: + case PP_VARTYPE_NULL: + return true; + case PP_VARTYPE_BOOL: + return AsBool() == other.AsBool(); + case PP_VARTYPE_INT32: + return AsInt() == other.AsInt(); + case PP_VARTYPE_DOUBLE: + return AsDouble() == other.AsDouble(); + case PP_VARTYPE_STRING: + if (var_.value.as_id == other.var_.value.as_id) + return true; + return AsString() == other.AsString(); + case PP_VARTYPE_OBJECT: + case PP_VARTYPE_ARRAY: + case PP_VARTYPE_ARRAY_BUFFER: + case PP_VARTYPE_DICTIONARY: + default: // Objects, arrays, dictionaries. + return var_.value.as_id == other.var_.value.as_id; + } +} + +bool Var::AsBool() const { + if (!is_bool()) { + PP_NOTREACHED(); + return false; + } + return PP_ToBool(var_.value.as_bool); +} + +int32_t Var::AsInt() const { + if (is_int()) + return var_.value.as_int; + if (is_double()) + return static_cast<int>(var_.value.as_double); + PP_NOTREACHED(); + return 0; +} + +double Var::AsDouble() const { + if (is_double()) + return var_.value.as_double; + if (is_int()) + return static_cast<double>(var_.value.as_int); + PP_NOTREACHED(); + return 0.0; +} + +std::string Var::AsString() const { + if (!is_string()) { + PP_NOTREACHED(); + return std::string(); + } + + if (!has_interface<PPB_Var_1_0>()) + return std::string(); + uint32_t len; + const char* str = get_interface<PPB_Var_1_0>()->VarToUtf8(var_, &len); + return std::string(str, len); +} + +std::string Var::DebugString() const { + char buf[256]; + if (is_undefined()) { + snprintf(buf, sizeof(buf), "Var(UNDEFINED)"); + } else if (is_null()) { + snprintf(buf, sizeof(buf), "Var(NULL)"); + } else if (is_bool()) { + snprintf(buf, sizeof(buf), AsBool() ? "Var(true)" : "Var(false)"); + } else if (is_int()) { + snprintf(buf, sizeof(buf), "Var(%d)", static_cast<int>(AsInt())); + } else if (is_double()) { + snprintf(buf, sizeof(buf), "Var(%f)", AsDouble()); + } else if (is_string()) { + char format[] = "Var<'%s'>"; + size_t decoration = sizeof(format) - 2; // The %s is removed. + size_t available = sizeof(buf) - decoration; + std::string str = AsString(); + if (str.length() > available) { + str.resize(available - 3); // Reserve space for ellipsis. + str.append("..."); + } + snprintf(buf, sizeof(buf), format, str.c_str()); + } else if (is_object()) { + snprintf(buf, sizeof(buf), "Var(OBJECT)"); + } else if (is_array()) { + snprintf(buf, sizeof(buf), "Var(ARRAY)"); + } else if (is_dictionary()) { + snprintf(buf, sizeof(buf), "Var(DICTIONARY)"); + } else if (is_array_buffer()) { + snprintf(buf, sizeof(buf), "Var(ARRAY_BUFFER)"); + } else { + buf[0] = '\0'; + } + return buf; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/var.h b/chromium/ppapi/cpp/var.h new file mode 100644 index 00000000000..fe30e10614b --- /dev/null +++ b/chromium/ppapi/cpp/var.h @@ -0,0 +1,310 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_VAR_H_ +#define PPAPI_CPP_VAR_H_ + +#include <string> +#include <vector> + +#include "ppapi/c/pp_var.h" +#include "ppapi/cpp/pass_ref.h" + +/// @file +/// This file defines the API for handling the passing of data types between +/// your module and the page. +namespace pp { + +/// A generic type used for passing data types between the module and the page. +class Var { + public: + /// Special value passed to constructor to make <code>NULL</code>. + struct Null {}; + + /// Default constructor. Creates a <code>Var</code> of type + /// <code>Undefined</code>. + Var(); + + /// A constructor used to create a <code>Var</code> of type <code>Null</code>. + Var(Null); + + /// A constructor used to create a <code>Var</code> of type <code>Bool</code>. + /// + /// @param[in] b A boolean value. + Var(bool b); + + /// A constructor used to create a 32 bit integer <code>Var</code>. + /// + /// @param[in] i A 32 bit integer value. + Var(int32_t i); + + /// A constructor used to create a double value <code>Var</code>. + /// + /// @param[in] d A double value. + Var(double d); + + /// A constructor used to create a UTF-8 character <code>Var</code>. + Var(const char* utf8_str); // Must be encoded in UTF-8. + + /// A constructor used to create a UTF-8 character <code>Var</code>. + Var(const std::string& utf8_str); // Must be encoded in UTF-8. + + /// A constructor used when you have received a <code>Var</code> as a return + /// value that has had its reference count incremented for you. + /// + /// You will not normally need to use this constructor because + /// the reference count will not normally be incremented for you. + Var(PassRef, const PP_Var& var) { + var_ = var; + is_managed_ = true; + } + + /// A constructor that increments the reference count. + explicit Var(const PP_Var& var); + + struct DontManage {}; + + // TODO(brettw): remove DontManage when this bug is fixed + // http://code.google.com/p/chromium/issues/detail?id=52105 + /// This constructor is used when we've given a <code>PP_Var</code> as an + /// input argument from somewhere and that reference is managing the + /// reference count for us. The object will not have its reference count + /// increased or decreased by this class instance. + /// + /// @param[in] var A <code>Var</code>. + Var(DontManage, const PP_Var& var) { + var_ = var; + is_managed_ = false; + } + + /// A constructor for copying a <code>Var</code>. + Var(const Var& other); + + /// Destructor. + virtual ~Var(); + + /// This function assigns one <code>Var</code> to another <code>Var</code>. + /// + /// @param[in] other The <code>Var</code> to be assigned. + /// + /// @return A resulting <code>Var</code>. + virtual Var& operator=(const Var& other); + + /// This function compares object identity (rather than value identity) for + /// objects, dictionaries, and arrays + /// + /// @param[in] other The <code>Var</code> to be compared to this Var. + /// + /// @return true if the <code>other</code> <code>Var</code> is the same as + /// this <code>Var</code>, otherwise false. + bool operator==(const Var& other) const; + + /// This function determines if this <code>Var</code> is an undefined value. + /// + /// @return true if this <code>Var</code> is undefined, otherwise false. + bool is_undefined() const { return var_.type == PP_VARTYPE_UNDEFINED; } + + /// This function determines if this <code>Var</code> is a null value. + /// + /// @return true if this <code>Var</code> is null, otherwise false. + bool is_null() const { return var_.type == PP_VARTYPE_NULL; } + + /// This function determines if this <code>Var</code> is a bool value. + /// + /// @return true if this <code>Var</code> is a bool, otherwise false. + bool is_bool() const { return var_.type == PP_VARTYPE_BOOL; } + + /// This function determines if this <code>Var</code> is a string value. + /// + /// @return true if this <code>Var</code> is a string, otherwise false. + bool is_string() const { return var_.type == PP_VARTYPE_STRING; } + + /// This function determines if this <code>Var</code> is an object. + /// + /// @return true if this <code>Var</code> is an object, otherwise false. + bool is_object() const { return var_.type == PP_VARTYPE_OBJECT; } + + /// This function determines if this <code>Var</code> is an array. + /// + /// @return true if this <code>Var</code> is an array, otherwise false. + bool is_array() const { return var_.type == PP_VARTYPE_ARRAY; } + + /// This function determines if this <code>Var</code> is a dictionary. + /// + /// @return true if this <code>Var</code> is a dictionary, otherwise false. + bool is_dictionary() const { return var_.type == PP_VARTYPE_DICTIONARY; } + + /// This function determines if this <code>Var</code> is an integer value. + /// The <code>is_int</code> function returns the internal representation. + /// The JavaScript runtime may convert between the two as needed, so the + /// distinction may not be relevant in all cases (int is really an + /// optimization inside the runtime). So most of the time, you will want + /// to check is_number(). + /// + /// @return true if this <code>Var</code> is an integer, otherwise false. + bool is_int() const { return var_.type == PP_VARTYPE_INT32; } + + /// This function determines if this <code>Var</code> is a double value. + /// The <code>is_double</code> function returns the internal representation. + /// The JavaScript runtime may convert between the two as needed, so the + /// distinction may not be relevant in all cases (int is really an + /// optimization inside the runtime). So most of the time, you will want to + /// check is_number(). + /// + /// @return true if this <code>Var</code> is a double, otherwise false. + bool is_double() const { return var_.type == PP_VARTYPE_DOUBLE; } + + /// This function determines if this <code>Var</code> is a number. + /// + /// @return true if this <code>Var</code> is an int32 or double number, + /// otherwise false. + bool is_number() const { + return var_.type == PP_VARTYPE_INT32 || + var_.type == PP_VARTYPE_DOUBLE; + } + + /// This function determines if this <code>Var</code> is an ArrayBuffer. + bool is_array_buffer() const { return var_.type == PP_VARTYPE_ARRAY_BUFFER; } + + /// AsBool() converts this <code>Var</code> to a bool. Assumes the + /// internal representation is_bool(). If it's not, it will assert in debug + /// mode, and return false. + /// + /// @return A bool version of this <code>Var</code>. + bool AsBool() const; + + /// AsInt() converts this <code>Var</code> to an int32_t. This function + /// is required because JavaScript doesn't have a concept of ints and doubles, + /// only numbers. The distinction between the two is an optimization inside + /// the compiler. Since converting from a double to an int may be lossy, if + /// you care about the distinction, either always work in doubles, or check + /// !is_double() before calling AsInt(). + /// + /// These functions will assert in debug mode and return 0 if the internal + /// representation is not is_number(). + /// + /// @return An int32_t version of this <code>Var</code>. + int32_t AsInt() const; + + /// AsDouble() converts this <code>Var</code> to a double. This function is + /// necessary because JavaScript doesn't have a concept of ints and doubles, + /// only numbers. The distinction between the two is an optimization inside + /// the compiler. Since converting from a double to an int may be lossy, if + /// you care about the distinction, either always work in doubles, or check + /// !is_double() before calling AsInt(). + /// + /// These functions will assert in debug mode and return 0 if the internal + /// representation is not is_number(). + /// + /// @return An double version of this <code>Var</code>. + double AsDouble() const; + + /// AsString() converts this <code>Var</code> to a string. If this object is + /// not a string, it will assert in debug mode, and return an empty string. + /// + /// @return A string version of this <code>Var</code>. + std::string AsString() const; + + /// This function returns the internal <code>PP_Var</code> + /// managed by this <code>Var</code> object. + /// + /// @return A const reference to a <code>PP_Var</code>. + const PP_Var& pp_var() const { + return var_; + } + + /// Detach() detaches from the internal <code>PP_Var</code> of this + /// object, keeping the reference count the same. This is used when returning + /// a <code>PP_Var</code> from an API function where the caller expects the + /// return value to have the reference count incremented for it. + /// + /// @return A detached version of this object without affecting the reference + /// count. + PP_Var Detach() { + PP_Var ret = var_; + var_ = PP_MakeUndefined(); + is_managed_ = true; + return ret; + } + + /// DebugString() returns a short description "Var<X>" that can be used for + /// logging, where "X" is the underlying scalar or "UNDEFINED" or "OBJ" as + /// it does not call into the browser to get the object description. + /// + /// @return A string displaying the value of this <code>Var</code>. This + /// function is used for debugging. + std::string DebugString() const; + + /// This class is used when calling the raw C PPAPI when using the C++ + /// <code>Var</code> as a possible NULL exception. This class will handle + /// getting the address of the internal value out if it's non-NULL and + /// fixing up the reference count. + /// + /// <strong>Warning:</strong> this will only work for things with exception + /// semantics, i.e. that the value will not be changed if it's a + /// non-undefined exception. Otherwise, this class will mess up the + /// refcounting. + /// + /// This is a bit subtle: + /// - If NULL is passed, we return NULL from get() and do nothing. + /// + /// - If a undefined value is passed, we return the address of a undefined + /// var from get and have the output value take ownership of that var. + /// + /// - If a non-undefined value is passed, we return the address of that var + /// from get, and nothing else should change. + /// + /// Example: + /// void FooBar(a, b, Var* exception = NULL) { + /// foo_interface->Bar(a, b, Var::OutException(exception).get()); + /// } + class OutException { + public: + /// A constructor. + OutException(Var* v) + : output_(v), + originally_had_exception_(v && !v->is_undefined()) { + if (output_) { + temp_ = output_->var_; + } else { + temp_.padding = 0; + temp_.type = PP_VARTYPE_UNDEFINED; + } + } + + /// Destructor. + ~OutException() { + if (output_ && !originally_had_exception_) + *output_ = Var(PASS_REF, temp_); + } + + PP_Var* get() { + if (output_) + return &temp_; + return NULL; + } + + private: + Var* output_; + bool originally_had_exception_; + PP_Var temp_; + }; + + protected: + PP_Var var_; + + // |is_managed_| indicates if the instance manages |var_|. + // You need to check if |var_| is refcounted to call Release(). + bool is_managed_; + + private: + // Prevent an arbitrary pointer argument from being implicitly converted to + // a bool at Var construction. If somebody makes such a mistake, (s)he will + // get a compilation error. + Var(void* non_scriptable_object_pointer); +}; + +} // namespace pp + +#endif // PPAPI_CPP_VAR_H_ diff --git a/chromium/ppapi/cpp/var_array.cc b/chromium/ppapi/cpp/var_array.cc new file mode 100644 index 00000000000..7a504e7cb58 --- /dev/null +++ b/chromium/ppapi/cpp/var_array.cc @@ -0,0 +1,96 @@ +// Copyright 2013 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 "ppapi/cpp/var_array.h" + +#include "ppapi/c/ppb_var_array.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_VarArray_1_0>() { + return PPB_VAR_ARRAY_INTERFACE_1_0; +} + +} // namespace + +VarArray::VarArray() : Var(Null()) { + if (has_interface<PPB_VarArray_1_0>()) + var_ = get_interface<PPB_VarArray_1_0>()->Create(); + else + PP_NOTREACHED(); +} + +VarArray::VarArray(const Var& var) : Var(var) { + if (!var.is_array()) { + PP_NOTREACHED(); + + // This takes care of releasing the reference that this object holds. + Var::operator=(Var(Null())); + } +} + +VarArray::VarArray(const PP_Var& var) : Var(var) { + if (var.type != PP_VARTYPE_ARRAY) { + PP_NOTREACHED(); + + // This takes care of releasing the reference that this object holds. + Var::operator=(Var(Null())); + } +} + +VarArray::VarArray(const VarArray& other) : Var(other) { +} + +VarArray::~VarArray() { +} + +VarArray& VarArray::operator=(const VarArray& other) { + Var::operator=(other); + return *this; +} + +Var& VarArray::operator=(const Var& other) { + if (other.is_array()) { + Var::operator=(other); + } else { + PP_NOTREACHED(); + Var::operator=(Var(Null())); + } + return *this; +} + +Var VarArray::Get(uint32_t index) const { + if (!has_interface<PPB_VarArray_1_0>()) + return Var(); + + return Var(PASS_REF, get_interface<PPB_VarArray_1_0>()->Get(var_, index)); +} + +bool VarArray::Set(uint32_t index, const Var& value) { + if (!has_interface<PPB_VarArray_1_0>()) + return false; + + return PP_ToBool(get_interface<PPB_VarArray_1_0>()->Set(var_, index, + value.pp_var())); +} + +uint32_t VarArray::GetLength() const { + if (!has_interface<PPB_VarArray_1_0>()) + return 0; + + return get_interface<PPB_VarArray_1_0>()->GetLength(var_); +} + +bool VarArray::SetLength(uint32_t length) { + if (!has_interface<PPB_VarArray_1_0>()) + return false; + + return PP_ToBool(get_interface<PPB_VarArray_1_0>()->SetLength(var_, length)); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/var_array.h b/chromium/ppapi/cpp/var_array.h new file mode 100644 index 00000000000..49373ff260b --- /dev/null +++ b/chromium/ppapi/cpp/var_array.h @@ -0,0 +1,90 @@ +// Copyright 2013 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. + +#ifndef PPAPI_CPP_VAR_ARRAY_H_ +#define PPAPI_CPP_VAR_ARRAY_H_ + +#include "ppapi/c/pp_bool.h" +#include "ppapi/c/pp_stdint.h" +#include "ppapi/cpp/var.h" + +/// @file +/// This file defines the API for interacting with array vars. + +namespace pp { + +class VarArray : public Var { + public: + /// Constructs a new array var. + VarArray(); + + /// Constructs a <code>VarArray</code> given a var for which is_array() is + /// true. This will refer to the same array var, but allow you to access + /// methods specific to arrays. + /// + /// @param[in] var An array var. + explicit VarArray(const Var& var); + + /// Constructs a <code>VarArray</code> given a <code>PP_Var</code> of type + /// PP_VARTYPE_ARRAY. + /// + /// @param[in] var A <code>PP_Var</code> of type PP_VARTYPE_ARRAY. + explicit VarArray(const PP_Var& var); + + /// Copy constructor. + VarArray(const VarArray& other); + + virtual ~VarArray(); + + /// Assignment operator. + VarArray& operator=(const VarArray& other); + + /// The <code>Var</code> assignment operator is overridden here so that we can + /// check for assigning a non-array var to a <code>VarArray</code>. + /// + /// @param[in] other The array var to be assigned. + /// + /// @return The resulting <code>VarArray</code> (as a <code>Var</code>&). + virtual Var& operator=(const Var& other); + + /// Gets an element from the array. + /// + /// @param[in] index An index indicating which element to return. + /// + /// @return The element at the specified position. If <code>index</code> is + /// larger than or equal to the array length, an undefined var is returned. + Var Get(uint32_t index) const; + + /// Sets the value of an element in the array. + /// + /// @param[in] index An index indicating which element to modify. If + /// <code>index</code> is larger than or equal to the array length, the length + /// is updated to be <code>index</code> + 1. Any position in the array that + /// hasn't been set before is set to undefined, i.e., <code>PP_Var</code> of + /// type <code>PP_VARTYPE_UNDEFINED</code>. + /// @param[in] value The value to set. + /// + /// @return A <code>bool</code> indicating whether the operation succeeds. + bool Set(uint32_t index, const Var& value); + + /// Gets the array length. + /// + /// @return The array length. + uint32_t GetLength() const; + + /// Sets the array length. + /// + /// @param[in] length The new array length. If <code>length</code> is smaller + /// than its current value, the array is truncated to the new length; any + /// elements that no longer fit are removed. If <code>length</code> is larger + /// than its current value, undefined vars are appended to increase the array + /// to the specified length. + /// + /// @return A <code>bool</code> indicating whether the operation succeeds. + bool SetLength(uint32_t length); +}; + +} // namespace pp + +#endif // PPAPI_CPP_VAR_ARRAY_H_ diff --git a/chromium/ppapi/cpp/var_array_buffer.cc b/chromium/ppapi/cpp/var_array_buffer.cc new file mode 100644 index 00000000000..0bc8ea57ad7 --- /dev/null +++ b/chromium/ppapi/cpp/var_array_buffer.cc @@ -0,0 +1,88 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/var_array_buffer.h" + +#include <limits> + +#include "ppapi/c/ppb_var_array_buffer.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_VarArrayBuffer_1_0>() { + return PPB_VAR_ARRAY_BUFFER_INTERFACE_1_0; +} + +} // namespace + +VarArrayBuffer::VarArrayBuffer() { + ConstructWithSize(0); +} + +VarArrayBuffer::VarArrayBuffer(const Var& var) : Var(var) { + if (!var.is_array_buffer()) { + PP_NOTREACHED(); + var_ = PP_MakeNull(); + } +} + +VarArrayBuffer::VarArrayBuffer(uint32_t size_in_bytes) { + ConstructWithSize(size_in_bytes); +} + +pp::VarArrayBuffer& VarArrayBuffer::operator=(const VarArrayBuffer& other) { + Var::operator=(other); + return *this; +} + +pp::Var& VarArrayBuffer::operator=(const Var& other) { + if (other.is_array_buffer()) { + return Var::operator=(other); + } else { + PP_NOTREACHED(); + return *this; + } +} + +uint32_t VarArrayBuffer::ByteLength() const { + uint32_t byte_length = std::numeric_limits<uint32_t>::max(); + if (is_array_buffer() && has_interface<PPB_VarArrayBuffer_1_0>()) + get_interface<PPB_VarArrayBuffer_1_0>()->ByteLength(var_, &byte_length); + else + PP_NOTREACHED(); + return byte_length; +} + +void* VarArrayBuffer::Map() { + if (is_array_buffer() && has_interface<PPB_VarArrayBuffer_1_0>()) + return get_interface<PPB_VarArrayBuffer_1_0>()->Map(var_); + PP_NOTREACHED(); + return NULL; +} + +void VarArrayBuffer::Unmap() { + if (is_array_buffer() && has_interface<PPB_VarArrayBuffer_1_0>()) + get_interface<PPB_VarArrayBuffer_1_0>()->Unmap(var_); + else + PP_NOTREACHED(); +} + + +void VarArrayBuffer::ConstructWithSize(uint32_t size_in_bytes) { + PP_DCHECK(is_undefined()); + + if (has_interface<PPB_VarArrayBuffer_1_0>()) { + var_ = get_interface<PPB_VarArrayBuffer_1_0>()->Create(size_in_bytes); + } else { + PP_NOTREACHED(); + var_ = PP_MakeNull(); + } + is_managed_ = true; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/var_array_buffer.h b/chromium/ppapi/cpp/var_array_buffer.h new file mode 100644 index 00000000000..7d1f9ad48c4 --- /dev/null +++ b/chromium/ppapi/cpp/var_array_buffer.h @@ -0,0 +1,104 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_VAR_ARRAY_BUFFER_H_ +#define PPAPI_CPP_VAR_ARRAY_BUFFER_H_ + +#include "ppapi/cpp/var.h" + +/// @file +/// This file defines the API for interacting with a JavaScript ArrayBuffer. + +namespace pp { + +/// <code>VarArrayBuffer</code> provides a way to interact with JavaScript +/// ArrayBuffers, which represent a contiguous sequence of bytes. Note that +/// these vars are not part of the embedding page's DOM, and can only be +/// shared with JavaScript using the <code>PostMessage</code> and +/// <code>HandleMessage</code> functions of <code>Instance</code>. +class VarArrayBuffer : public Var { + public: + /// The default constructor constructs a <code>VarArrayBuffer</code> which is + /// 0 byte long. + VarArrayBuffer(); + + /// Construct a <code>VarArrayBuffer</code> given a var for which + /// is_array_buffer() is true. This will refer to the same + /// <code>ArrayBuffer</code> as var, but allows you to access methods + /// specific to <code>VarArrayBuffer</code>. + /// + /// @param[in] var An <code>ArrayBuffer</code> var. + explicit VarArrayBuffer(const Var& var); + + /// Construct a new <code>VarArrayBuffer</code> which is + /// <code>size_in_bytes</code> bytes long and initialized to zero. + /// + /// @param[in] size_in_bytes The size of the constructed + /// <code>ArrayBuffer</code> in bytes. + explicit VarArrayBuffer(uint32_t size_in_bytes); + + /// Copy constructor. + VarArrayBuffer(const VarArrayBuffer& buffer) : Var(buffer) {} + + virtual ~VarArrayBuffer() {} + + /// This function assigns one <code>VarArrayBuffer</code> to another + /// <code>VarArrayBuffer</code>. + /// + /// @param[in] other The <code>VarArrayBuffer</code> to be assigned. + /// + /// @return The resulting <code>VarArrayBuffer</code>. + VarArrayBuffer& operator=(const VarArrayBuffer& other); + + /// This function assigns one <code>VarArrayBuffer</code> to another + /// <code>VarArrayBuffer</code>. A Var's assignment operator is overloaded + /// here so that we can check for assigning a non-ArrayBuffer var to a + /// <code>VarArrayBuffer</code>. + /// + /// @param[in] other The <code>VarArrayBuffer</code> to be assigned. + /// + /// @return The resulting <code>VarArrayBuffer</code> (as a Var&). + virtual Var& operator=(const Var& other); + + /// ByteLength() retrieves the length of the <code>VarArrayBuffer</code> in + /// bytes. + /// + /// @return The length of the <code>VarArrayBuffer</code> in bytes. + uint32_t ByteLength() const; + + /// Map() maps the <code>ArrayBuffer</code> in to the module's address space + /// and returns a pointer to the beginning of the internal buffer for + /// this <code>ArrayBuffer</code>. ArrayBuffers are copied when transmitted, + /// so changes to the underlying memory are not automatically available to + /// the embedding page. + /// + /// Note that calling Map() can be a relatively expensive operation. Use care + /// when calling it in performance-critical code. For example, you should call + /// it only once when looping over an <code>ArrayBuffer</code>. + /// + /// <strong>Example:</strong> + /// + /// @code + /// char* data = static_cast<char*>(array_buffer_var.Map()); + /// uint32_t byte_length = array_buffer_var.ByteLength(); + /// for (uint32_t i = 0; i < byte_length; ++i) + /// data[i] = 'A'; + /// @endcode + /// + /// @return A pointer to the internal buffer for this + /// <code>ArrayBuffer</code>. + void* Map(); + + /// Unmap() unmaps this <code>ArrayBuffer</code> var from the module address + /// space. Use this if you want to save memory but might want to call Map() + /// to map the buffer again later. + void Unmap(); + + private: + void ConstructWithSize(uint32_t size_in_bytes); +}; + +} // namespace pp + +#endif // PPAPI_CPP_VAR_ARRAY_BUFFER_H_ diff --git a/chromium/ppapi/cpp/var_dictionary.cc b/chromium/ppapi/cpp/var_dictionary.cc new file mode 100644 index 00000000000..600b1f2d9d7 --- /dev/null +++ b/chromium/ppapi/cpp/var_dictionary.cc @@ -0,0 +1,111 @@ +// Copyright 2013 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 "ppapi/cpp/var_dictionary.h" + +#include "ppapi/c/ppb_var_dictionary.h" +#include "ppapi/cpp/logging.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_VarDictionary_1_0>() { + return PPB_VAR_DICTIONARY_INTERFACE_1_0; +} + +} // namespace + +VarDictionary::VarDictionary() : Var(Null()) { + if (has_interface<PPB_VarDictionary_1_0>()) + var_ = get_interface<PPB_VarDictionary_1_0>()->Create(); + else + PP_NOTREACHED(); +} + +VarDictionary::VarDictionary(const Var& var) : Var(var) { + if (!var.is_dictionary()) { + PP_NOTREACHED(); + + // This takes care of releasing the reference that this object holds. + Var::operator=(Var(Null())); + } +} + +VarDictionary::VarDictionary(const PP_Var& var) : Var(var) { + if (var.type != PP_VARTYPE_DICTIONARY) { + PP_NOTREACHED(); + + // This takes care of releasing the reference that this object holds. + Var::operator=(Var(Null())); + } +} + +VarDictionary::VarDictionary(const VarDictionary& other) + : Var(other) { +} + +VarDictionary::~VarDictionary() { +} + +VarDictionary& VarDictionary::operator=( + const VarDictionary& other) { + Var::operator=(other); + return *this; +} + +Var& VarDictionary::operator=(const Var& other) { + if (other.is_dictionary()) { + Var::operator=(other); + } else { + PP_NOTREACHED(); + Var::operator=(Var(Null())); + } + return *this; +} + +Var VarDictionary::Get(const Var& key) const { + if (!has_interface<PPB_VarDictionary_1_0>()) + return Var(); + + return Var( + PASS_REF, + get_interface<PPB_VarDictionary_1_0>()->Get(var_, key.pp_var())); +} + +bool VarDictionary::Set(const Var& key, const Var& value) { + if (!has_interface<PPB_VarDictionary_1_0>()) + return false; + + return PP_ToBool(get_interface<PPB_VarDictionary_1_0>()->Set( + var_, key.pp_var(), value.pp_var())); +} + +void VarDictionary::Delete(const Var& key) { + if (has_interface<PPB_VarDictionary_1_0>()) + get_interface<PPB_VarDictionary_1_0>()->Delete(var_, key.pp_var()); +} + +bool VarDictionary::HasKey(const Var& key) const { + if (!has_interface<PPB_VarDictionary_1_0>()) + return false; + + return PP_ToBool(get_interface<PPB_VarDictionary_1_0>()->HasKey( + var_, key.pp_var())); +} + +VarArray VarDictionary::GetKeys() const { + if (!has_interface<PPB_VarDictionary_1_0>()) + return VarArray(); + + Var result(PASS_REF, + get_interface<PPB_VarDictionary_1_0>()->GetKeys(var_)); + if (result.is_array()) + return VarArray(result); + else + return VarArray(); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/var_dictionary.h b/chromium/ppapi/cpp/var_dictionary.h new file mode 100644 index 00000000000..1c5bd2bb2e2 --- /dev/null +++ b/chromium/ppapi/cpp/var_dictionary.h @@ -0,0 +1,93 @@ +// Copyright 2013 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. + +#ifndef PPAPI_CPP_VAR_DICTIONARY_H_ +#define PPAPI_CPP_VAR_DICTIONARY_H_ + +#include "ppapi/c/pp_bool.h" +#include "ppapi/cpp/var.h" +#include "ppapi/cpp/var_array.h" + +/// @file +/// This file defines the API for interacting with dictionary vars. + +namespace pp { + +class VarDictionary : public Var { + public: + /// Constructs a new dictionary var. + VarDictionary(); + + /// Constructs a <code>VarDictionary</code> given a var for which + /// is_dictionary() is true. This will refer to the same dictionary var, but + /// allow you to access methods specific to dictionary. + /// + /// @param[in] var A dictionary var. + explicit VarDictionary(const Var& var); + + /// Constructs a <code>VarDictionary</code> given a <code>PP_Var</code> + /// of type PP_VARTYPE_DICTIONARY. + /// + /// @param[in] var A <code>PP_Var</code> of type PP_VARTYPE_DICTIONARY. + explicit VarDictionary(const PP_Var& var); + + /// Copy constructor. + VarDictionary(const VarDictionary& other); + + virtual ~VarDictionary(); + + /// Assignment operator. + VarDictionary& operator=(const VarDictionary& other); + + /// The <code>Var</code> assignment operator is overridden here so that we can + /// check for assigning a non-dictionary var to a + /// <code>VarDictionary</code>. + /// + /// @param[in] other The dictionary var to be assigned. + /// + /// @return The resulting <code>VarDictionary</code> (as a + /// <code>Var</code>&). + virtual Var& operator=(const Var& other); + + /// Gets the value associated with the specified key. + /// + /// @param[in] key A string var. + /// + /// @return The value that is associated with <code>key</code>. If + /// <code>key</code> is not a string var, or it doesn't exist in the + /// dictionary, an undefined var is returned. + Var Get(const Var& key) const; + + /// Sets the value associated with the specified key. + /// + /// @param[in] key A string var. If this key hasn't existed in the dictionary, + /// it is added and associated with <code>value</code>; otherwise, the + /// previous value is replaced with <code>value</code>. + /// @param[in] value The value to set. + /// + /// @return A <code>bool</code> indicating whether the operation succeeds. + bool Set(const Var& key, const Var& value); + + /// Deletes the specified key and its associated value, if the key exists. + /// + /// @param[in] key A string var. + void Delete(const Var& key); + + /// Checks whether a key exists. + /// + /// @param[in] key A string var. + /// + /// @return A <code>bool</code> indicating whether the key exists. + bool HasKey(const Var& key) const; + + /// Gets all the keys in the dictionary. + /// + /// @return An array var which contains all the keys of the dictionary. + /// The elements are string vars. Returns an empty array var if failed. + VarArray GetKeys() const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_VAR_DICTIONARY_H_ diff --git a/chromium/ppapi/cpp/view.cc b/chromium/ppapi/cpp/view.cc new file mode 100644 index 00000000000..ce347859d70 --- /dev/null +++ b/chromium/ppapi/cpp/view.cc @@ -0,0 +1,98 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/view.h" + +#include "ppapi/c/ppb_view.h" +#include "ppapi/cpp/module_impl.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_View_1_0>() { + return PPB_VIEW_INTERFACE_1_0; +} + +template <> const char* interface_name<PPB_View_1_1>() { + return PPB_VIEW_INTERFACE_1_1; +} + +} // namespace + +View::View() : Resource() { +} + +View::View(PP_Resource view_resource) : Resource(view_resource) { +} + +Rect View::GetRect() const { + PP_Rect out; + if (has_interface<PPB_View_1_1>()) { + if (PP_ToBool(get_interface<PPB_View_1_1>()->GetRect(pp_resource(), &out))) + return Rect(out); + } else if (has_interface<PPB_View_1_0>()) { + if (PP_ToBool(get_interface<PPB_View_1_0>()->GetRect(pp_resource(), &out))) + return Rect(out); + } + return Rect(); +} + +bool View::IsFullscreen() const { + if (has_interface<PPB_View_1_1>()) { + return PP_ToBool(get_interface<PPB_View_1_1>()->IsFullscreen( + pp_resource())); + } else if (has_interface<PPB_View_1_0>()) { + return PP_ToBool(get_interface<PPB_View_1_0>()->IsFullscreen( + pp_resource())); + } + return false; +} + +bool View::IsVisible() const { + if (has_interface<PPB_View_1_1>()) + return PP_ToBool(get_interface<PPB_View_1_1>()->IsVisible(pp_resource())); + else if (has_interface<PPB_View_1_0>()) + return PP_ToBool(get_interface<PPB_View_1_0>()->IsVisible(pp_resource())); + return false; +} + +bool View::IsPageVisible() const { + if (has_interface<PPB_View_1_1>()) { + return PP_ToBool(get_interface<PPB_View_1_1>()->IsPageVisible( + pp_resource())); + } else if (has_interface<PPB_View_1_0>()) { + return PP_ToBool(get_interface<PPB_View_1_0>()->IsPageVisible( + pp_resource())); + } + return true; +} + +Rect View::GetClipRect() const { + PP_Rect out; + if (has_interface<PPB_View_1_1>()) { + if (PP_ToBool(get_interface<PPB_View_1_1>()->GetClipRect(pp_resource(), + &out))) + return Rect(out); + } else if (has_interface<PPB_View_1_0>()) { + if (PP_ToBool(get_interface<PPB_View_1_0>()->GetClipRect(pp_resource(), + &out))) + return Rect(out); + } + return Rect(); +} + +float View::GetDeviceScale() const { + if (has_interface<PPB_View_1_1>()) + return get_interface<PPB_View_1_1>()->GetDeviceScale(pp_resource()); + return 1.0f; +} + +float View::GetCSSScale() const { + if (has_interface<PPB_View_1_1>()) + return get_interface<PPB_View_1_1>()->GetCSSScale(pp_resource()); + return 1.0f; +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/view.h b/chromium/ppapi/cpp/view.h new file mode 100644 index 00000000000..7ffd1682294 --- /dev/null +++ b/chromium/ppapi/cpp/view.h @@ -0,0 +1,145 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_VIEW_H_ +#define PPAPI_CPP_VIEW_H_ + +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/rect.h" +#include "ppapi/cpp/size.h" + +/// @file +/// This file defines the API for getting the state of a the view for an +/// instance. + +namespace pp { + +/// This class represents the state of the view for an instance and contains +/// functions for retrieving the current state of that view. +class View : public Resource { + public: + /// Default constructor for creating an is_null() <code>View</code> object. + View(); + + /// Creates a View resource, taking and holding an additional reference to + /// the given resource handle. + View(PP_Resource view_resource); + + /// GetRect() retrieves the rectangle of the module instance associated + /// with a view changed notification relative to the upper-left of the browser + /// viewport. This position changes when the page is scrolled. + /// + /// The returned rectangle may not be inside the visible portion of the + /// viewport if the module instance is scrolled off the page. Therefore, the + /// position may be negative or larger than the size of the page. The size + /// will always reflect the size of the module were it to be scrolled + /// entirely into view. + /// + /// In general, most modules will not need to worry about the position of the + ///module instance in the viewport, and only need to use the size. + /// + /// @return The rectangle of the instance. The default return value for + /// an invalid View is the empty rectangle. + Rect GetRect() const; + + /// IsFullscreen() returns whether the instance is currently + /// displaying in fullscreen mode. + /// + /// @return <code>true</code> if the instance is in full screen mode, + /// or <code>false</code> if it's not or the resource is invalid. + bool IsFullscreen() const; + + /// IsVisible() determines whether the module instance might be visible to + /// the user. For example, the Chrome window could be minimized or another + /// window could be over it. In both of these cases, the module instance + /// would not be visible to the user, but IsVisible() will return true. + /// + /// Use the result to speed up or stop updates for invisible module + /// instances. + /// + /// This function performs the duties of GetRect() (determining whether the + /// module instance is scrolled into view and the clip rectangle is nonempty) + /// and IsPageVisible() (whether the page is visible to the user). + /// + /// @return <code>true</code> if the instance might be visible to the + /// user, <code>false</code> if it is definitely not visible. + bool IsVisible() const; + + /// IsPageVisible() determines if the page that contains the module instance + /// is visible. The most common cause of invisible pages is that + /// the page is in a background tab in the browser. + /// + /// Most applications should use IsVisible() instead of this function since + /// the module instance could be scrolled off of a visible page, and this + /// function will still return true. However, depending on how your module + /// interacts with the page, there may be certain updates that you may want + /// to perform when the page is visible even if your specific module instance + /// is not visible. + /// + /// @return <code>true</code> if the instance might be visible to the + /// user, <code>false</code> if it is definitely not visible. + bool IsPageVisible() const; + + /// GetClipRect() returns the clip rectangle relative to the upper-left corner + /// of the module instance. This rectangle indicates the portions of the + /// module instance that are scrolled into view. + /// + /// If the module instance is scrolled off the view, the return value will be + /// (0, 0, 0, 0). This clip rectangle does <i>not</i> take into account page + /// visibility. Therefore, if the module instance is scrolled into view, but + /// the page itself is on a tab that is not visible, the return rectangle will + /// contain the visible rectangle as though the page were visible. Refer to + /// IsPageVisible() and IsVisible() if you want to account for page + /// visibility. + /// + /// Most applications will not need to worry about the clip rectangle. The + /// recommended behavior is to do full updates if the module instance is + /// visible, as determined by IsVisible(), and do no updates if it is not + /// visible. + /// + /// However, if the cost for computing pixels is very high for your + /// application, or the pages you're targeting frequently have very large + /// module instances with small visible portions, you may wish to optimize + /// further. In this case, the clip rectangle will tell you which parts of + /// the module to update. + /// + /// Note that painting of the page and sending of view changed updates + /// happens asynchronously. This means when the user scrolls, for example, + /// it is likely that the previous backing store of the module instance will + /// be used for the first paint, and will be updated later when your + /// application generates new content with the new clip. This may cause + /// flickering at the boundaries when scrolling. If you do choose to do + /// partial updates, you may want to think about what color the invisible + /// portions of your backing store contain (be it transparent or some + /// background color) or to paint a certain region outside the clip to reduce + /// the visual distraction when this happens. + /// + /// @return The rectangle representing the visible part of the module + /// instance. If the resource is invalid, the empty rectangle is returned. + Rect GetClipRect() const; + + /// GetDeviceScale returns the scale factor between device pixels and DIPs + /// (also known as logical pixels or UI pixels on some platforms). This allows + /// the developer to render their contents at device resolution, even as + /// coordinates / sizes are given in DIPs through the API. + /// + /// Note that the coordinate system for Pepper APIs is DIPs. Also note that + /// one DIP might not equal one CSS pixel - when page scale/zoom is in effect. + /// + /// @return A <code>float</code> value representing the number of device + /// pixels per DIP. + float GetDeviceScale() const; + + /// GetCSSScale returns the scale factor between DIPs and CSS pixels. This + /// allows proper scaling between DIPs - as sent via the Pepper API - and CSS + /// pixel coordinates used for Web content. + /// + /// @return A <code>float</code> value representing the number of DIPs per CSS + /// pixel. + float GetCSSScale() const; +}; + +} // namespace pp + +#endif // PPAPI_CPP_VIEW_H_ diff --git a/chromium/ppapi/cpp/websocket.cc b/chromium/ppapi/cpp/websocket.cc new file mode 100644 index 00000000000..f0ae5fa0c30 --- /dev/null +++ b/chromium/ppapi/cpp/websocket.cc @@ -0,0 +1,152 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ppapi/cpp/websocket.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/pp_macros.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/module_impl.h" +#include "ppapi/cpp/var.h" + +namespace pp { + +namespace { + +template <> const char* interface_name<PPB_WebSocket_1_0>() { + return PPB_WEBSOCKET_INTERFACE_1_0; +} + +} // namespace + +WebSocket::WebSocket(const InstanceHandle& instance) { + if (!has_interface<PPB_WebSocket_1_0>()) + return; + PassRefFromConstructor(get_interface<PPB_WebSocket_1_0>()->Create( + instance.pp_instance())); +} + +WebSocket::~WebSocket() { +} + +int32_t WebSocket::Connect(const Var& url, const Var protocols[], + uint32_t protocol_count, const CompletionCallback& callback) { + if (!has_interface<PPB_WebSocket_1_0>()) + return PP_ERROR_BADRESOURCE; + + // Convert protocols to C interface. + PP_Var *c_protocols = NULL; + if (protocol_count) { + c_protocols = new PP_Var[protocol_count]; + if (!c_protocols) + return PP_ERROR_NOMEMORY; + } + for (uint32_t i = 0; i < protocol_count; ++i) + c_protocols[i] = protocols[i].pp_var(); + + int32_t result = get_interface<PPB_WebSocket_1_0>()->Connect( + pp_resource(), url.pp_var(), c_protocols, protocol_count, + callback.pp_completion_callback()); + if (c_protocols) + delete[] c_protocols; + return result; +} + +int32_t WebSocket::Close(uint16_t code, const Var& reason, + const CompletionCallback& callback) { + if (!has_interface<PPB_WebSocket_1_0>()) + return PP_ERROR_BADRESOURCE; + + return get_interface<PPB_WebSocket_1_0>()->Close( + pp_resource(), code, reason.pp_var(), + callback.pp_completion_callback()); +} + +int32_t WebSocket::ReceiveMessage(Var* message, + const CompletionCallback& callback) { + if (!has_interface<PPB_WebSocket_1_0>()) + return PP_ERROR_BADRESOURCE; + + // Initialize |message| to release old internal PP_Var of reused |message|. + if (message) + *message = Var(); + + return get_interface<PPB_WebSocket_1_0>()->ReceiveMessage( + pp_resource(), const_cast<PP_Var*>(&message->pp_var()), + callback.pp_completion_callback()); +} + +int32_t WebSocket::SendMessage(const Var& message) { + if (!has_interface<PPB_WebSocket_1_0>()) + return PP_ERROR_BADRESOURCE; + + return get_interface<PPB_WebSocket_1_0>()->SendMessage( + pp_resource(), message.pp_var()); +} + +uint64_t WebSocket::GetBufferedAmount() { + if (!has_interface<PPB_WebSocket_1_0>()) + return 0; + + return get_interface<PPB_WebSocket_1_0>()->GetBufferedAmount(pp_resource()); +} + +uint16_t WebSocket::GetCloseCode() { + if (!has_interface<PPB_WebSocket_1_0>()) + return 0; + + return get_interface<PPB_WebSocket_1_0>()->GetCloseCode(pp_resource()); +} + +Var WebSocket::GetCloseReason() { + if (!has_interface<PPB_WebSocket_1_0>()) + return 0; + + return Var(PASS_REF, + get_interface<PPB_WebSocket_1_0>()->GetCloseReason(pp_resource())); +} + +bool WebSocket::GetCloseWasClean() { + if (!has_interface<PPB_WebSocket_1_0>()) + return false; + + PP_Bool result = + get_interface<PPB_WebSocket_1_0>()->GetCloseWasClean(pp_resource()); + return PP_ToBool(result); +} + +Var WebSocket::GetExtensions() { + if (!has_interface<PPB_WebSocket_1_0>()) + return Var(); + + return Var(PASS_REF, + get_interface<PPB_WebSocket_1_0>()->GetExtensions(pp_resource())); +} + +Var WebSocket::GetProtocol() { + if (!has_interface<PPB_WebSocket_1_0>()) + return Var(); + + return Var(PASS_REF, + get_interface<PPB_WebSocket_1_0>()->GetProtocol(pp_resource())); +} + +PP_WebSocketReadyState WebSocket::GetReadyState() { + if (!has_interface<PPB_WebSocket_1_0>()) + return PP_WEBSOCKETREADYSTATE_INVALID; + + return get_interface<PPB_WebSocket_1_0>()->GetReadyState(pp_resource()); +} + +Var WebSocket::GetURL() { + if (!has_interface<PPB_WebSocket_1_0>()) + return Var(); + + return Var(PASS_REF, + get_interface<PPB_WebSocket_1_0>()->GetURL(pp_resource())); +} + +} // namespace pp diff --git a/chromium/ppapi/cpp/websocket.h b/chromium/ppapi/cpp/websocket.h new file mode 100644 index 00000000000..0c72dc0eda9 --- /dev/null +++ b/chromium/ppapi/cpp/websocket.h @@ -0,0 +1,218 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PPAPI_CPP_WEBSOCKET_H_ +#define PPAPI_CPP_WEBSOCKET_H_ + +#include "ppapi/c/ppb_websocket.h" +#include "ppapi/cpp/resource.h" + +/// @file +/// This file defines the WebSocket interface providing bi-directional, +/// full-duplex, communications over a single TCP socket. + +// Windows headers will redefine SendMessage. +#ifdef SendMessage +#undef SendMessage +#endif + +namespace pp { + +class CompletionCallback; +class InstanceHandle; +class Var; + +/// The <code>WebSocket</code> class providing bi-directional, +/// full-duplex, communications over a single TCP socket. +class WebSocket : public Resource { + public: + /// Constructs a WebSocket object. + /// + /// @param[in] instance The instance with which this resource will be + /// associated. + explicit WebSocket(const InstanceHandle& instance); + + /// Destructs a WebSocket object. + virtual ~WebSocket(); + + /// Connect() connects to the specified WebSocket server. You can call this + /// function once for an object. + /// + /// @param[in] url A <code>Var</code> of string type representing a WebSocket + /// server URL. + /// + /// @param[in] protocols A pointer to an array of <code>Var</code> of string + /// type specifying sub-protocols. Each <code>Var</code> represents one + /// sub-protocol. This argument can be null only if + /// <code>protocol_count</code> is 0. + /// + /// @param[in] protocol_count The number of sub-protocols in + /// <code>protocols</code>. + /// + /// @param[in] callback A <code>CompletionCallback</code> called + /// when a connection is established or an error occurs in establishing + /// connection. + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + /// Returns <code>PP_ERROR_BADARGUMENT</code> if specified <code>url</code>, + /// or <code>protocols</code> contains invalid string as defined in + /// the WebSocket API specification. <code>PP_ERROR_BADARGUMENT</code> + /// corresponds to a SyntaxError in the WebSocket API specification. + /// Returns <code>PP_ERROR_NOACCESS</code> if the protocol specified in the + /// <code>url</code> is not a secure protocol, but the origin of the caller + /// has a secure scheme. Also returns <code>PP_ERROR_NOACCESS</code> if the + /// port specified in the <code>url</code> is a port that the user agent is + /// configured to block access to because it is a well-known port like SMTP. + /// <code>PP_ERROR_NOACCESS</code> corresponds to a SecurityError of the + /// specification. + /// Returns <code>PP_ERROR_INPROGRESS</code> if this is not the first call to + /// Connect(). + int32_t Connect(const Var& url, const Var protocols[], + uint32_t protocol_count, const CompletionCallback& callback); + + /// Close() closes the specified WebSocket connection by specifying + /// <code>code</code> and <code>reason</code>. + /// + /// @param[in] code The WebSocket close code. This is ignored if it is 0. + /// <code>PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE</code> must be used for the + /// usual case. To indicate some specific error cases, codes in the range + /// <code>PP_WEBSOCKETSTATUSCODE_USER_REGISTERED_MIN</code> to + /// <code>PP_WEBSOCKETSTATUSCODE_USER_REGISTERED_MAX</code>, and in the range + /// <code>PP_WEBSOCKETSTATUSCODE_USER_PRIVATE_MIN</code> to + /// <code>PP_WEBSOCKETSTATUSCODE_USER_PRIVATE_MAX</code> are available. + /// + /// @param[in] reason A <code>Var</code> of string type representing the + /// close reason. This is ignored if it is an undefined type. + /// + /// @param[in] callback A <code>CompletionCallback</code> called when the + /// connection is closed or an error occurs in closing the connection. + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + /// Returns <code>PP_ERROR_BADARGUMENT</code> if <code>reason</code> contains + /// an invalid character as a UTF-8 string, or is longer than 123 bytes. + /// <code>PP_ERROR_BADARGUMENT</code> corresponds to a JavaScript + /// SyntaxError in the WebSocket API specification. + /// Returns <code>PP_ERROR_NOACCESS</code> if the code is not an integer + /// equal to 1000 or in the range 3000 to 4999. + /// <code>PP_ERROR_NOACCESS</code> corresponds to an InvalidAccessError in + /// the WebSocket API specification. Returns <code>PP_ERROR_INPROGRESS</code> + /// if a previous call to Close() is not finished. + int32_t Close(uint16_t code, const Var& reason, + const CompletionCallback& callback); + + /// ReceiveMessage() receives a message from the WebSocket server. + /// This interface only returns a single message. That is, this interface + /// must be called at least N times to receive N messages, no matter the size + /// of each message. + /// + /// @param[out] message The received message is copied to provided + /// <code>message</code>. The <code>message</code> must remain valid until + /// ReceiveMessage() completes. Its received <code>Var</code> will be of + /// string or ArrayBuffer type. + /// + /// @param[in] callback A <code>CompletionCallback</code> called when + /// ReceiveMessage() completes. This callback is ignored if ReceiveMessage() + /// completes synchronously and returns <code>PP_OK</code>. + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + /// If an error is detected or connection is closed, ReceiveMessage() returns + /// <code>PP_ERROR_FAILED</code> after all buffered messages are received. + /// Until buffered message become empty, ReceiveMessage() continues to return + /// <code>PP_OK</code> as if connection is still established without errors. + int32_t ReceiveMessage(Var* message, + const CompletionCallback& callback); + + /// SendMessage() sends a message to the WebSocket server. + /// + /// @param[in] message A message to send. The message is copied to an internal + /// buffer, so the caller can free <code>message</code> safely after returning + /// from the function. This <code>Var</code> must be of string or + /// ArrayBuffer types. + /// + /// @return An int32_t containing an error code from + /// <code>pp_errors.h</code>. + /// Returns <code>PP_ERROR_FAILED</code> if the ReadyState is + /// <code>PP_WEBSOCKETREADYSTATE_CONNECTING</code>. + /// <code>PP_ERROR_FAILED</code> corresponds to a JavaScript + /// InvalidStateError in the WebSocket API specification. + /// Returns <code>PP_ERROR_BADARGUMENT</code> if the provided + /// <code>message</code> contains an invalid character as a + /// UTF-8 string. <code>PP_ERROR_BADARGUMENT</code> corresponds to a + /// JavaScript SyntaxError in the WebSocket API specification. + /// Otherwise, returns <code>PP_OK</code>, but it doesn't necessarily mean + /// that the server received the message. + int32_t SendMessage(const Var& message); + + /// GetBufferedAmount() returns the number of bytes of text and binary + /// messages that have been queued for the WebSocket connection to send, but + /// have not been transmitted to the network yet. + /// + /// @return Returns the number of bytes. + uint64_t GetBufferedAmount(); + + /// GetCloseCode() returns the connection close code for the WebSocket + /// connection. + /// + /// @return Returns 0 if called before the close code is set. + uint16_t GetCloseCode(); + + /// GetCloseReason() returns the connection close reason for the WebSocket + /// connection. + /// + /// @return Returns a <code>Var</code> of string type. If called before the + /// close reason is set, the return value contains an empty string. Returns a + /// <code>PP_VARTYPE_UNDEFINED</code> if called on an invalid resource. + Var GetCloseReason(); + + /// GetCloseWasClean() returns if the connection was closed cleanly for the + /// specified WebSocket connection. + /// + /// @return Returns <code>false</code> if called before the connection is + /// closed, called on an invalid resource, or closed for abnormal reasons. + /// Otherwise, returns <code>true</code> if the connection was closed + /// cleanly. + bool GetCloseWasClean(); + + /// GetExtensions() returns the extensions selected by the server for the + /// specified WebSocket connection. + /// + /// @return Returns a <code>Var</code> of string type. If called before the + /// connection is established, the <code>Var</code>'s data is an empty + /// string. Returns a <code>PP_VARTYPE_UNDEFINED</code> if called on an + /// invalid resource. Currently the <code>Var</code>'s data for valid + /// resources are always an empty string. + Var GetExtensions(); + + /// GetProtocol() returns the sub-protocol chosen by the server for the + /// specified WebSocket connection. + /// + /// @return Returns a <code>Var</code> of string type. If called before the + /// connection is established, the <code>Var</code> contains the empty + /// string. Returns a code>PP_VARTYPE_UNDEFINED</code> if called on an + /// invalid resource. + Var GetProtocol(); + + /// GetReadyState() returns the ready state of the specified WebSocket + /// connection. + /// + /// @return Returns <code>PP_WEBSOCKETREADYSTATE_INVALID</code> if called + /// before Connect() is called, or if this function is called on an + /// invalid resource. + PP_WebSocketReadyState GetReadyState(); + + /// GetURL() returns the URL associated with specified WebSocket connection. + /// + /// @return Returns a <code>Var</code> of string type. If called before the + /// connection is established, the <code>Var</code> contains the empty + /// string. Returns a <code>PP_VARTYPE_UNDEFINED</code> if this function + /// is called on an invalid resource. + Var GetURL(); +}; + +} // namespace pp + +#endif // PPAPI_CPP_WEBSOCKET_H_ |